AI: Remove deprecated SrsRtcPublisherAsync and SrsRtcPlayerAsync use WHIP/WHEP.

This commit is contained in:
OSSRS-AI 2025-10-26 09:33:45 -04:00 committed by winlin
parent 51ab6403a3
commit 4ae9871285
28 changed files with 434 additions and 1085 deletions

View File

@ -1,6 +1,6 @@
// The MIT License (MIT) // The MIT License (MIT)
// //
// Copyright (c) 2025 Winlin // # Copyright (c) 2025 Winlin
// //
// Permission is hereby granted, free of charge, to any person obtaining a copy of // Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in // this software and associated documentation files (the "Software"), to deal in

View File

@ -2,88 +2,88 @@
// //
// The traditional error handling idiom in Go is roughly akin to // The traditional error handling idiom in Go is roughly akin to
// //
// if err != nil { // if err != nil {
// return err // return err
// } // }
// //
// which applied recursively up the call stack results in error reports // which applied recursively up the call stack results in error reports
// without context or debugging information. The errors package allows // without context or debugging information. The errors package allows
// programmers to add context to the failure path in their code in a way // programmers to add context to the failure path in their code in a way
// that does not destroy the original value of the error. // that does not destroy the original value of the error.
// //
// Adding context to an error // # Adding context to an error
// //
// The errors.Wrap function returns a new error that adds context to the // The errors.Wrap function returns a new error that adds context to the
// original error by recording a stack trace at the point Wrap is called, // original error by recording a stack trace at the point Wrap is called,
// and the supplied message. For example // and the supplied message. For example
// //
// _, err := ioutil.ReadAll(r) // _, err := ioutil.ReadAll(r)
// if err != nil { // if err != nil {
// return errors.Wrap(err, "read failed") // return errors.Wrap(err, "read failed")
// } // }
// //
// If additional control is required the errors.WithStack and errors.WithMessage // If additional control is required the errors.WithStack and errors.WithMessage
// functions destructure errors.Wrap into its component operations of annotating // functions destructure errors.Wrap into its component operations of annotating
// an error with a stack trace and an a message, respectively. // an error with a stack trace and an a message, respectively.
// //
// Retrieving the cause of an error // # Retrieving the cause of an error
// //
// Using errors.Wrap constructs a stack of errors, adding context to the // Using errors.Wrap constructs a stack of errors, adding context to the
// preceding error. Depending on the nature of the error it may be necessary // preceding error. Depending on the nature of the error it may be necessary
// to reverse the operation of errors.Wrap to retrieve the original error // to reverse the operation of errors.Wrap to retrieve the original error
// for inspection. Any error value which implements this interface // for inspection. Any error value which implements this interface
// //
// type causer interface { // type causer interface {
// Cause() error // Cause() error
// } // }
// //
// can be inspected by errors.Cause. errors.Cause will recursively retrieve // can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error which does not implement causer, which is assumed to be // the topmost error which does not implement causer, which is assumed to be
// the original cause. For example: // the original cause. For example:
// //
// switch err := errors.Cause(err).(type) { // switch err := errors.Cause(err).(type) {
// case *MyError: // case *MyError:
// // handle specifically // // handle specifically
// default: // default:
// // unknown error // // unknown error
// } // }
// //
// causer interface is not exported by this package, but is considered a part // causer interface is not exported by this package, but is considered a part
// of stable public API. // of stable public API.
// //
// Formatted printing of errors // # Formatted printing of errors
// //
// All error values returned from this package implement fmt.Formatter and can // All error values returned from this package implement fmt.Formatter and can
// be formatted by the fmt package. The following verbs are supported // be formatted by the fmt package. The following verbs are supported
// //
// %s print the error. If the error has a Cause it will be // %s print the error. If the error has a Cause it will be
// printed recursively // printed recursively
// %v see %s // %v see %s
// %+v extended format. Each Frame of the error's StackTrace will // %+v extended format. Each Frame of the error's StackTrace will
// be printed in detail. // be printed in detail.
// //
// Retrieving the stack trace of an error or wrapper // # Retrieving the stack trace of an error or wrapper
// //
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are // New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface. // invoked. This information can be retrieved with the following interface.
// //
// type stackTracer interface { // type stackTracer interface {
// StackTrace() errors.StackTrace // StackTrace() errors.StackTrace
// } // }
// //
// Where errors.StackTrace is defined as // Where errors.StackTrace is defined as
// //
// type StackTrace []Frame // type StackTrace []Frame
// //
// The Frame type represents a call site in the stack trace. Frame supports // The Frame type represents a call site in the stack trace. Frame supports
// the fmt.Formatter interface that can be used for printing information about // the fmt.Formatter interface that can be used for printing information about
// the stack trace of this error. For example: // the stack trace of this error. For example:
// //
// if err, ok := err.(stackTracer); ok { // if err, ok := err.(stackTracer); ok {
// for _, f := range err.StackTrace() { // for _, f := range err.StackTrace() {
// fmt.Printf("%+s:%d", f) // fmt.Printf("%+s:%d", f)
// } // }
// } // }
// //
// stackTracer interface is not exported by this package, but is considered a part // stackTracer interface is not exported by this package, but is considered a part
// of stable public API. // of stable public API.
@ -247,9 +247,9 @@ func (w *withMessage) Format(s fmt.State, verb rune) {
// An error value has a cause if it implements the following // An error value has a cause if it implements the following
// interface: // interface:
// //
// type causer interface { // type causer interface {
// Cause() error // Cause() error
// } // }
// //
// If the error does not implement Cause, the original error will // If the error does not implement Cause, the original error will
// be returned. If the error is nil, nil will be returned without further // be returned. If the error is nil, nil will be returned without further

View File

@ -40,15 +40,15 @@ func (f Frame) line() int {
// Format formats the frame according to the fmt.Formatter interface. // Format formats the frame according to the fmt.Formatter interface.
// //
// %s source file // %s source file
// %d source line // %d source line
// %n function name // %n function name
// %v equivalent to %s:%d // %v equivalent to %s:%d
// //
// Format accepts flags that alter the printing of some verbs, as follows: // Format accepts flags that alter the printing of some verbs, as follows:
// //
// %+s path of source file relative to the compile time GOPATH // %+s path of source file relative to the compile time GOPATH
// %+v equivalent to %+s:%d // %+v equivalent to %+s:%d
func (f Frame) Format(s fmt.State, verb rune) { func (f Frame) Format(s fmt.State, verb rune) {
switch verb { switch verb {
case 's': case 's':
@ -82,12 +82,12 @@ type StackTrace []Frame
// Format formats the stack of Frames according to the fmt.Formatter interface. // Format formats the stack of Frames according to the fmt.Formatter interface.
// //
// %s lists source files for each Frame in the stack // %s lists source files for each Frame in the stack
// %v lists the source file and line number for each Frame in the stack // %v lists the source file and line number for each Frame in the stack
// //
// Format accepts flags that alter the printing of some verbs, as follows: // Format accepts flags that alter the printing of some verbs, as follows:
// //
// %+v Prints filename, function, and line number for each Frame in the stack. // %+v Prints filename, function, and line number for each Frame in the stack.
func (st StackTrace) Format(s fmt.State, verb rune) { func (st StackTrace) Format(s fmt.State, verb rune) {
switch verb { switch verb {
case 'v': case 'v':

View File

@ -19,6 +19,7 @@
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build go1.7
// +build go1.7 // +build go1.7
package logger package logger

View File

@ -20,18 +20,23 @@
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// The oryx logger package provides connection-oriented log service. // The oryx logger package provides connection-oriented log service.
// logger.I(ctx, ...) //
// logger.T(ctx, ...) // logger.I(ctx, ...)
// logger.W(ctx, ...) // logger.T(ctx, ...)
// logger.E(ctx, ...) // logger.W(ctx, ...)
// logger.E(ctx, ...)
//
// Or use format: // Or use format:
// logger.If(ctx, format, ...) //
// logger.Tf(ctx, format, ...) // logger.If(ctx, format, ...)
// logger.Wf(ctx, format, ...) // logger.Tf(ctx, format, ...)
// logger.Ef(ctx, format, ...) // logger.Wf(ctx, format, ...)
// logger.Ef(ctx, format, ...)
//
// @remark the Context is optional thus can be nil. // @remark the Context is optional thus can be nil.
// @remark From 1.7+, the ctx could be context.Context, wrap by logger.WithContext, // @remark From 1.7+, the ctx could be context.Context, wrap by logger.WithContext,
// please read ExampleLogger_ContextGO17(). //
// please read ExampleLogger_ContextGO17().
package logger package logger
import ( import (

View File

@ -19,6 +19,7 @@
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//go:build !go1.7
// +build !go1.7 // +build !go1.7
package logger package logger

View File

@ -8,8 +8,8 @@
// This package currently lacks some features found in alternative // This package currently lacks some features found in alternative
// and more actively maintained WebSocket packages: // and more actively maintained WebSocket packages:
// //
// https://godoc.org/github.com/gorilla/websocket // https://godoc.org/github.com/gorilla/websocket
// https://godoc.org/nhooyr.io/websocket // https://godoc.org/nhooyr.io/websocket
package websocket // import "golang.org/x/net/websocket" package websocket // import "golang.org/x/net/websocket"
import ( import (
@ -416,7 +416,6 @@ Trivial usage:
// send binary frame // send binary frame
data = []byte{0, 1, 2} data = []byte{0, 1, 2}
websocket.Message.Send(ws, data) websocket.Message.Send(ws, data)
*/ */
var Message = Codec{marshal, unmarshal} var Message = Codec{marshal, unmarshal}

View File

@ -1,32 +1,23 @@
/** //
* The MIT License (MIT) // Copyright (c) 2013-2025 Winlin
* //
* Copyright (c) 2013-2025 Winlin // SPDX-License-Identifier: MIT
* //
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict'; 'use strict';
function SrsError(name, message) {
this.name = name;
this.message = message;
this.stack = (new Error()).stack;
}
SrsError.prototype = Object.create(Error.prototype);
SrsError.prototype.constructor = SrsError;
// Depends on adapter-7.4.0.min.js from https://github.com/webrtc/adapter // Depends on adapter-7.4.0.min.js from https://github.com/webrtc/adapter
// Async-awat-prmise based SRS RTC Publisher. // Async-awat-prmise based SRS RTC Publisher by WHIP.
function SrsRtcPublisherAsync() { function SrsRtcWhipWhepAsync() {
var self = {}; var self = {};
// https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia // https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia
@ -37,80 +28,144 @@ function SrsRtcPublisherAsync() {
} }
}; };
// @see https://github.com/rtcdn/rtcdn-draft // Store media streams to stop tracks when closing.
// @url The WebRTC url to play with, for example: self.displayStream = null;
// webrtc://r.ossrs.net/live/livestream self.userStream = null;
// 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(ip) of answer:
// webrtc://r.ossrs.net/live/livestream?eip=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://datatracker.ietf.org/doc/draft-ietf-wish-whip/
// @url The WebRTC url to publish with, for example:
// http://localhost:1985/rtc/v1/whip/?app=live&stream=livestream
// @options The options to control playing, supports:
// camera: boolean, whether capture video from camera, default to true.
// screen: boolean, whether capture video from screen, default to false.
// audio: boolean, whether play audio, default to true.
self.publish = async function (url, options) {
if (url.indexOf('/whip/') === -1) throw new Error(`invalid WHIP url ${url}`);
const hasAudio = options?.audio ?? true;
const useCamera = options?.camera ?? true;
const useScreen = options?.screen ?? false;
// @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addStream#Migrating_to_addTrack if (!hasAudio && !useCamera && !useScreen) throw new Error(`The camera, screen and audio can't be false at the same time`);
stream.getTracks().forEach(function (track) {
self.pc.addTrack(track);
// Notify about local track when stream is ok. if (hasAudio) {
self.ontrack && self.ontrack({track: track}); self.pc.addTransceiver("audio", {direction: "sendonly"});
}); } else {
self.constraints.audio = false;
}
if (useCamera || useScreen) {
self.pc.addTransceiver("video", {direction: "sendonly"});
}
if (!useCamera) {
self.constraints.video = false;
}
if (!navigator.mediaDevices && window.location.protocol === 'http:' && window.location.hostname !== 'localhost') {
throw new SrsError('HttpsRequiredError', `Please use HTTPS or localhost to publish, read https://github.com/ossrs/srs/issues/2762#issuecomment-983147576`);
}
if (useScreen) {
self.displayStream = await navigator.mediaDevices.getDisplayMedia({
video: true
});
// @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addStream#Migrating_to_addTrack
self.displayStream.getTracks().forEach(function (track) {
self.pc.addTrack(track);
// Notify about local track when stream is ok.
self.ontrack && self.ontrack({track: track});
});
}
if (useCamera || hasAudio) {
self.userStream = await navigator.mediaDevices.getUserMedia(self.constraints);
self.userStream.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(); var offer = await self.pc.createOffer();
await self.pc.setLocalDescription(offer); await self.pc.setLocalDescription(offer);
var session = await new Promise(function (resolve, reject) { const answer = await new Promise(function (resolve, reject) {
// @see https://github.com/rtcdn/rtcdn-draft console.log(`Generated offer: ${offer.sdp}`);
var data = {
api: conf.apiUrl, tid: conf.tid, streamurl: conf.streamUrl,
clientip: null, sdp: offer.sdp
};
console.log("Generated offer: ", data);
$.ajax({ const xhr = new XMLHttpRequest();
type: "POST", url: conf.apiUrl, data: JSON.stringify(data), xhr.onload = function() {
contentType: 'application/json', dataType: 'json' if (xhr.readyState !== xhr.DONE) return;
}).done(function (data) { if (xhr.status !== 200 && xhr.status !== 201) return reject(xhr);
const data = xhr.responseText;
console.log("Got answer: ", data); console.log("Got answer: ", data);
if (data.code) { return data.code ? reject(xhr) : resolve(data);
reject(data); }
return; xhr.open('POST', url, true);
} xhr.setRequestHeader('Content-type', 'application/sdp');
xhr.send(offer.sdp);
resolve(data);
}).fail(function (reason) {
reject(reason);
});
}); });
await self.pc.setRemoteDescription( await self.pc.setRemoteDescription(
new RTCSessionDescription({type: 'answer', sdp: session.sdp}) new RTCSessionDescription({type: 'answer', sdp: answer})
); );
session.simulator = conf.schema + '//' + conf.urlObject.server + ':' + conf.port + '/rtc/v1/nack/';
return session; return self.__internal.parseId(url, offer.sdp, answer);
};
// See https://datatracker.ietf.org/doc/draft-ietf-wish-whip/
// @url The WebRTC url to play with, for example:
// http://localhost:1985/rtc/v1/whep/?app=live&stream=livestream
// @options The options to control playing, supports:
// videoOnly: boolean, whether only play video, default to false.
// audioOnly: boolean, whether only play audio, default to false.
self.play = async function(url, options) {
if (url.indexOf('/whip-play/') === -1 && url.indexOf('/whep/') === -1) throw new Error(`invalid WHEP url ${url}`);
if (options?.videoOnly && options?.audioOnly) throw new Error(`The videoOnly and audioOnly in options can't be true at the same time`);
if (!options?.videoOnly) self.pc.addTransceiver("audio", {direction: "recvonly"});
if (!options?.audioOnly) self.pc.addTransceiver("video", {direction: "recvonly"});
var offer = await self.pc.createOffer();
await self.pc.setLocalDescription(offer);
const answer = await new Promise(function(resolve, reject) {
console.log(`Generated offer: ${offer.sdp}`);
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.readyState !== xhr.DONE) return;
if (xhr.status !== 200 && xhr.status !== 201) return reject(xhr);
const data = xhr.responseText;
console.log("Got answer: ", data);
return data.code ? reject(xhr) : resolve(data);
}
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/sdp');
xhr.send(offer.sdp);
});
await self.pc.setRemoteDescription(
new RTCSessionDescription({type: 'answer', sdp: answer})
);
return self.__internal.parseId(url, offer.sdp, answer);
}; };
// Close the publisher. // Close the publisher.
self.close = function () { self.close = function () {
self.pc && self.pc.close(); self.pc && self.pc.close();
self.pc = null; self.pc = null;
// Stop all media tracks to release camera/microphone.
if (self.displayStream) {
self.displayStream.getTracks().forEach(function (track) {
track.stop();
});
self.displayStream = null;
}
if (self.userStream) {
self.userStream.getTracks().forEach(function (track) {
track.stop();
});
self.userStream = null;
}
}; };
// The callback when got local stream. // The callback when got local stream.
@ -120,147 +175,6 @@ function SrsRtcPublisherAsync() {
self.stream.addTrack(event.track); self.stream.addTrack(event.track);
}; };
// 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).slice(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.substring(1, a.pathname.lastIndexOf("/"));
var stream = a.pathname.slice(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.slice(app.indexOf("?"));
app = app.slice(0, app.indexOf("?"));
if (params.indexOf("vhost=") > 0) {
vhost = params.slice(params.indexOf("vhost=") + "vhost=".length);
if (vhost.indexOf("&") > 0) {
vhost = vhost.slice(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.slice(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); self.pc = new RTCPeerConnection(null);
// To keep api consistent between player and publisher. // To keep api consistent between player and publisher.
@ -268,231 +182,23 @@ function SrsRtcPublisherAsync() {
// @see https://webrtc.org/getting-started/media-devices // @see https://webrtc.org/getting-started/media-devices
self.stream = new MediaStream(); self.stream = new MediaStream();
return self;
}
// 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 = {};
// @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(ip) of answer:
// webrtc://r.ossrs.net/live/livestream?eip=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);
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);
$.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 player.
self.close = function() {
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. // Internal APIs.
self.__internal = { self.__internal = {
defaultPath: '/rtc/v1/play/', parseId: (url, offer, answer) => {
prepareUrl: function (webrtcUrl) { let sessionid = offer.substr(offer.indexOf('a=ice-ufrag:') + 'a=ice-ufrag:'.length);
var urlObject = self.__internal.parse(webrtcUrl); sessionid = sessionid.substr(0, sessionid.indexOf('\n') - 1) + ':';
sessionid += answer.substr(answer.indexOf('a=ice-ufrag:') + 'a=ice-ufrag:'.length);
// If user specifies the schema, use it as API schema. sessionid = sessionid.substr(0, sessionid.indexOf('\n'));
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;
const a = document.createElement("a");
a.href = url;
return { return {
apiUrl: apiUrl, streamUrl: streamUrl, schema: schema, urlObject: urlObject, port: port, sessionid: sessionid, // Should be ice-ufrag of answer:offer.
tid: Number(parseInt(new Date().getTime()*Math.random()*100)).toString(16).slice(0, 7) simulator: a.protocol + '//' + a.host + '/rtc/v1/nack/',
}; };
}, },
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.substring(1, a.pathname.lastIndexOf("/"));
var stream = a.pathname.slice(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.slice(app.indexOf("?"));
app = app.slice(0, app.indexOf("?"));
if (params.indexOf("vhost=") > 0) {
vhost = params.slice(params.indexOf("vhost=") + "vhost=".length);
if (vhost.indexOf("&") > 0) {
vhost = vhost.slice(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.slice(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);
// 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 // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/ontrack
self.pc.ontrack = function(event) { self.pc.ontrack = function(event) {
if (self.ontrack) { if (self.ontrack) {
@ -503,33 +209,29 @@ function SrsRtcPlayerAsync() {
return self; return self;
} }
// Format the codec of RTCRtpSender, kind(audio/video) is optional filter. // https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport
// https://developer.mozilla.org/en-US/docs/Web/Media/Formats/WebRTC_codecs#getting_the_supported_codecs function SrsRtcFormatStats(stats, kind) {
function SrsRtcFormatSenders(senders, kind) {
var codecs = []; var codecs = [];
senders.forEach(function (sender) { stats.forEach((report) => {
var params = sender.getParameters(); if (report.type === 'codec' && report.mimeType?.toLowerCase().startsWith(kind)) {
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 = ''; var s = '';
s += c.mimeType.replace('audio/', '').replace('video/', ''); s += report.mimeType.split('/')[1] || report.mimeType;
s += ', ' + c.clockRate + 'HZ';
if (sender.track.kind === "audio") { if (report.clockRate) {
s += ', channels: ' + c.channels; s += ', ' + report.clockRate + 'HZ';
}
if (kind === 'audio' && report.channels) {
s += ', channels: ' + report.channels;
}
if (report.payloadType) {
s += ', pt: ' + report.payloadType;
} }
s += ', pt: ' + c.payloadType;
codecs.push(s); codecs.push(s);
}); }
}); });
return codecs.join(", "); return codecs.join(", ");
} }

View File

@ -213,23 +213,33 @@
} }
}; };
// Convert webrtc:// URL to WHIP URL
var convertToWhipUrl = function(host, room, display) {
var schema = window.location.protocol;
var port = 1985;
if (schema === 'https:') {
port = 443;
}
return schema + '//' + host + ':' + port + '/rtc/v1/whip/?app=' + room + '&stream=' + display + conf.query.replace('?', '&');
};
var startPublish = function (host, room, display) { var startPublish = function (host, room, display) {
$(".ff_first").each(function(i,e) { $(".ff_first").each(function(i,e) {
$(e).text(display); $(e).text(display);
}); });
var url = 'webrtc://' + host + '/' + room + '/' + display + conf.query; var whipUrl = convertToWhipUrl(host, room, display);
$('#rtc_media_publisher').show(); $('#rtc_media_publisher').show();
$('#publisher').show(); $('#publisher').show();
if (publisher) { if (publisher) {
publisher.close(); publisher.close();
} }
publisher = new SrsRtcPublisherAsync(); publisher = new SrsRtcWhipWhepAsync();
$('#rtc_media_publisher').prop('srcObject', publisher.stream); $('#rtc_media_publisher').prop('srcObject', publisher.stream);
return publisher.publish(url).then(function(session){ return publisher.publish(whipUrl).then(function(session){
$('#self').text('Self: ' + url); $('#self').text('Self: ' + display);
}).catch(function (reason) { }).catch(function (reason) {
publisher.close(); publisher.close();
$('#rtc_media_publisher').hide(); $('#rtc_media_publisher').hide();
@ -237,12 +247,22 @@
}); });
}; };
// Convert webrtc:// URL to WHEP URL
var convertToWhepUrl = function(host, room, display) {
var schema = window.location.protocol;
var port = 1985;
if (schema === 'https:') {
port = 443;
}
return schema + '//' + host + ':' + port + '/rtc/v1/whep/?app=' + room + '&stream=' + display + conf.query.replace('?', '&');
};
var startPlay = function (host, room, display) { var startPlay = function (host, room, display) {
$(".ff_second").each(function(i,e) { $(".ff_second").each(function(i,e) {
$(e).text(display); $(e).text(display);
}); });
var url = 'webrtc://' + host + '/' + room + '/' + display + conf.query; var whepUrl = convertToWhepUrl(host, room, display);
$('#rtc_media_player').show(); $('#rtc_media_player').show();
$('#player').show(); $('#player').show();
@ -250,10 +270,10 @@
player.close(); player.close();
} }
player = new SrsRtcPlayerAsync(); player = new SrsRtcWhipWhepAsync();
$('#rtc_media_player').prop('srcObject', player.stream); $('#rtc_media_player').prop('srcObject', player.stream);
player.play(url).then(function(session){ player.play(whepUrl).then(function(session){
$('#peer').text('Peer: ' + display); $('#peer').text('Peer: ' + display);
$('#rtc_media_player').prop('muted', false); $('#rtc_media_player').prop('muted', false);
}).catch(function (reason) { }).catch(function (reason) {

View File

@ -126,23 +126,33 @@
}); });
}; };
// Convert webrtc:// URL to WHIP URL
var convertToWhipUrl = function(host, room, display) {
var schema = window.location.protocol;
var port = 1985;
if (schema === 'https:') {
port = 443;
}
return schema + '//' + host + ':' + port + '/rtc/v1/whip/?app=' + room + '&stream=' + display + conf.query.replace('?', '&');
};
var startPublish = function (host, room, display) { var startPublish = function (host, room, display) {
$(".ff_first").each(function(i,e) { $(".ff_first").each(function(i,e) {
$(e).text(display); $(e).text(display);
}); });
var url = 'webrtc://' + host + '/' + room + '/' + display + conf.query; var whipUrl = convertToWhipUrl(host, room, display);
$('#rtc_media_publisher').show(); $('#rtc_media_publisher').show();
$('#publisher').show(); $('#publisher').show();
if (publisher) { if (publisher) {
publisher.close(); publisher.close();
} }
publisher = new SrsRtcPublisherAsync(); publisher = new SrsRtcWhipWhepAsync();
$('#rtc_media_publisher').prop('srcObject', publisher.stream); $('#rtc_media_publisher').prop('srcObject', publisher.stream);
return publisher.publish(url).then(function(session){ return publisher.publish(whipUrl).then(function(session){
$('#self').text('Self: ' + url); $('#self').text('Self: ' + display);
}).catch(function (reason) { }).catch(function (reason) {
publisher.close(); publisher.close();
$('#rtc_media_publisher').hide(); $('#rtc_media_publisher').hide();
@ -150,6 +160,16 @@
}); });
}; };
// Convert webrtc:// URL to WHEP URL
var convertToWhepUrl = function(host, room, display) {
var schema = window.location.protocol;
var port = 1985;
if (schema === 'https:') {
port = 443;
}
return schema + '//' + host + ':' + port + '/rtc/v1/whep/?app=' + room + '&stream=' + display + conf.query.replace('?', '&');
};
var startPlay = function (host, room, display) { var startPlay = function (host, room, display) {
$(".ff_second").each(function(i,e) { $(".ff_second").each(function(i,e) {
$(e).text(display); $(e).text(display);
@ -165,20 +185,20 @@
let ui = $('#player').clone().attr('id', 'player-' + display); let ui = $('#player').clone().attr('id', 'player-' + display);
let video = ui.children('#rtc_media_player'); let video = ui.children('#rtc_media_player');
console.log(video.length); console.log(video.length);
let player = new SrsRtcPlayerAsync(); let player = new SrsRtcWhipWhepAsync();
players[display] = {ui:ui, video:video, player:player}; players[display] = {ui:ui, video:video, player:player};
$('.srs_players').append(ui); $('.srs_players').append(ui);
// Start play for this user. // Start play for this user.
var url = 'webrtc://' + host + '/' + room + '/' + display + conf.query; var whepUrl = convertToWhepUrl(host, room, display);
video.show(); video.show();
ui.show(); ui.show();
video.prop('srcObject', player.stream); video.prop('srcObject', player.stream);
player.play(url).then(function(session){ player.play(whepUrl).then(function(session){
ui.children('#peer').text('Peer: ' + url); ui.children('#peer').text('Peer: ' + display);
video.prop('muted', false); video.prop('muted', false);
}).catch(function (reason) { }).catch(function (reason) {
player.close(); player.close();

View File

@ -21,12 +21,13 @@
package blackbox package blackbox
import ( import (
"github.com/ossrs/go-oryx-lib/logger"
"io/ioutil" "io/ioutil"
"math/rand" "math/rand"
"os" "os"
"testing" "testing"
"time" "time"
"github.com/ossrs/go-oryx-lib/logger"
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {

View File

@ -23,14 +23,15 @@ package blackbox
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"math/rand" "math/rand"
"os" "os"
"path" "path"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
func TestFast_RtmpPublish_DvrFlv_Basic(t *testing.T) { func TestFast_RtmpPublish_DvrFlv_Basic(t *testing.T) {

View File

@ -23,8 +23,6 @@ package blackbox
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"math/rand" "math/rand"
"os" "os"
"path" "path"
@ -32,6 +30,9 @@ import (
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
func TestSlow_RtmpPublish_RtmpPlay_HEVC_Basic(t *testing.T) { func TestSlow_RtmpPublish_RtmpPlay_HEVC_Basic(t *testing.T) {

View File

@ -23,14 +23,15 @@ package blackbox
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"math/rand" "math/rand"
"os" "os"
"path" "path"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
func TestFast_RtmpPublish_HlsPlay_Basic(t *testing.T) { func TestFast_RtmpPublish_HlsPlay_Basic(t *testing.T) {

View File

@ -23,12 +23,13 @@ package blackbox
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"net/http" "net/http"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
func TestFast_Http_Api_Basic_Auth(t *testing.T) { func TestFast_Http_Api_Basic_Auth(t *testing.T) {

View File

@ -23,14 +23,15 @@ package blackbox
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"math/rand" "math/rand"
"os" "os"
"path" "path"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
func TestFast_RtmpPublish_RtmpPlay_CodecMP3_Basic(t *testing.T) { func TestFast_RtmpPublish_RtmpPlay_CodecMP3_Basic(t *testing.T) {

View File

@ -23,14 +23,15 @@ package blackbox
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"math/rand" "math/rand"
"os" "os"
"path" "path"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
func TestFast_RtmpPublish_RtmpPlay_Basic(t *testing.T) { func TestFast_RtmpPublish_RtmpPlay_Basic(t *testing.T) {

View File

@ -23,14 +23,15 @@ package blackbox
import ( import (
"context" "context"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"math/rand" "math/rand"
"os" "os"
"path" "path"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
func TestFast_SrtPublish_SrtPlay_Basic(t *testing.T) { func TestFast_SrtPublish_SrtPlay_Basic(t *testing.T) {

View File

@ -26,9 +26,6 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
ohttp "github.com/ossrs/go-oryx-lib/http"
"github.com/ossrs/go-oryx-lib/logger"
"io/ioutil" "io/ioutil"
"math/rand" "math/rand"
"net/http" "net/http"
@ -41,6 +38,10 @@ import (
"sync" "sync"
"syscall" "syscall"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
ohttp "github.com/ossrs/go-oryx-lib/http"
"github.com/ossrs/go-oryx-lib/logger"
) )
var srsLog *bool var srsLog *bool

View File

@ -24,13 +24,14 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
type publisherInfo struct { type publisherInfo struct {

View File

@ -24,12 +24,13 @@ import (
"context" "context"
"flag" "flag"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"os" "os"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
var sr string var sr string

View File

@ -174,7 +174,7 @@ func Run(ctx context.Context) error {
gStatLive.Publishers.Alive-- gStatLive.Publishers.Alive--
logger.Tf(ctx, "Publisher %v done, alive=%v", pr, gStatLive.Publishers.Alive) logger.Tf(ctx, "Publisher %v done, alive=%v", pr, gStatLive.Publishers.Alive)
<- publisherStartedCtx.Done() <-publisherStartedCtx.Done()
if gStatLive.Publishers.Alive == 0 { if gStatLive.Publishers.Alive == 0 {
cancel() cancel()
} }

View File

@ -24,14 +24,15 @@ import (
"context" "context"
"flag" "flag"
"fmt" "fmt"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
"net" "net"
"net/http" "net/http"
"os" "os"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/ossrs/go-oryx-lib/errors"
"github.com/ossrs/go-oryx-lib/logger"
) )
var sr, dumpAudio, dumpVideo string var sr, dumpAudio, dumpVideo string

View File

@ -21,12 +21,13 @@
package srs package srs
import ( import (
"github.com/ossrs/go-oryx-lib/logger"
"io/ioutil" "io/ioutil"
"math/rand" "math/rand"
"os" "os"
"testing" "testing"
"time" "time"
"github.com/ossrs/go-oryx-lib/logger"
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {

View File

@ -15,512 +15,6 @@ function SrsError(name, message) {
SrsError.prototype = Object.create(Error.prototype); SrsError.prototype = Object.create(Error.prototype);
SrsError.prototype.constructor = SrsError; SrsError.prototype.constructor = SrsError;
// 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}
}
};
// Store media stream to stop tracks when closing.
self.userStream = null;
// @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"});
//self.pc.addTransceiver("video", {direction: "sendonly"});
//self.pc.addTransceiver("audio", {direction: "sendonly"});
if (!navigator.mediaDevices && window.location.protocol === 'http:' && window.location.hostname !== 'localhost') {
throw new SrsError('HttpsRequiredError', `Please use HTTPS or localhost to publish, read https://github.com/ossrs/srs/issues/2762#issuecomment-983147576`);
}
self.userStream = await navigator.mediaDevices.getUserMedia(self.constraints);
// @see https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addStream#Migrating_to_addTrack
self.userStream.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);
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.readyState !== xhr.DONE) return;
if (xhr.status !== 200 && xhr.status !== 201) return reject(xhr);
const data = JSON.parse(xhr.responseText);
console.log("Got answer: ", data);
return data.code ? reject(xhr) : resolve(data);
}
xhr.open('POST', conf.apiUrl, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
});
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;
// Stop all media tracks to release camera/microphone.
if (self.userStream) {
self.userStream.getTracks().forEach(function (track) {
track.stop();
});
self.userStream = 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);
};
// 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 += '/';
}
var 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
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).slice(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.substring(1, a.pathname.lastIndexOf("/"));
var stream = a.pathname.slice(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.slice(app.indexOf("?"));
app = app.slice(0, app.indexOf("?"));
if (params.indexOf("vhost=") > 0) {
vhost = params.slice(params.indexOf("vhost=") + "vhost=".length);
if (vhost.indexOf("&") > 0) {
vhost = vhost.slice(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.slice(0, url.indexOf("://"));
}
var port = a.port;
if (!port) {
// Finger out by webrtc url, if contains http or https port, to overwrite default 1985.
if (schema === 'webrtc' && url.indexOf(`webrtc://${a.host}:`) === 0) {
port = (url.indexOf(`webrtc://${a.host}:80`) === 0) ? 80 : 443;
}
// Guess by schema.
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;
}
// 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 = {};
// @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
// webrtc://r.ossrs.net:80/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);
self.pc.addTransceiver("audio", {direction: "recvonly"});
self.pc.addTransceiver("video", {direction: "recvonly"});
//self.pc.addTransceiver("video", {direction: "recvonly"});
//self.pc.addTransceiver("audio", {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);
const xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.readyState !== xhr.DONE) return;
if (xhr.status !== 200 && xhr.status !== 201) return reject(xhr);
const data = JSON.parse(xhr.responseText);
console.log("Got answer: ", data);
return data.code ? reject(xhr) : resolve(data);
}
xhr.open('POST', conf.apiUrl, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
});
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() {
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);
// 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 += '/';
}
var 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
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).slice(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.substring(1, a.pathname.lastIndexOf("/"));
var stream = a.pathname.slice(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.slice(app.indexOf("?"));
app = app.slice(0, app.indexOf("?"));
if (params.indexOf("vhost=") > 0) {
vhost = params.slice(params.indexOf("vhost=") + "vhost=".length);
if (vhost.indexOf("&") > 0) {
vhost = vhost.slice(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.slice(0, url.indexOf("://"));
}
var port = a.port;
if (!port) {
// Finger out by webrtc url, if contains http or https port, to overwrite default 1985.
if (schema === 'webrtc' && url.indexOf(`webrtc://${a.host}:`) === 0) {
port = (url.indexOf(`webrtc://${a.host}:80`) === 0) ? 80 : 443;
}
// Guess by schema.
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);
// 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;
}
// Depends on adapter-7.4.0.min.js from https://github.com/webrtc/adapter // Depends on adapter-7.4.0.min.js from https://github.com/webrtc/adapter
// Async-awat-prmise based SRS RTC Publisher by WHIP. // Async-awat-prmise based SRS RTC Publisher by WHIP.
function SrsRtcWhipWhepAsync() { function SrsRtcWhipWhepAsync() {

View File

@ -67,6 +67,31 @@
</div> </div>
<script type="text/javascript"> <script type="text/javascript">
$(function(){ $(function(){
// Convert webrtc:// URL to WHEP URL
// webrtc://domain:port/app/stream => http://domain:1985/rtc/v1/whep/?app=app&stream=stream
var convertToWhepUrl = function(webrtcUrl) {
var a = document.createElement("a");
a.href = webrtcUrl.replace("webrtc://", "http://").replace("rtc://", "http://");
var schema = window.location.protocol;
var port = a.port || 1985;
if (schema === 'https:') {
port = a.port || 443;
}
var app = a.pathname.substring(1, a.pathname.lastIndexOf("/"));
var stream = a.pathname.slice(a.pathname.lastIndexOf("/") + 1);
var whepUrl = schema + '//' + a.hostname + ':' + port + '/rtc/v1/whep/?app=' + app + '&stream=' + stream;
// Append query parameters from original URL
if (a.search) {
whepUrl += '&' + a.search.substring(1);
}
return whepUrl;
};
var sdk = null; // Global handler to do cleanup when replaying. var sdk = null; // Global handler to do cleanup when replaying.
var startPlay = function() { var startPlay = function() {
$('#rtc_media_player').show(); $('#rtc_media_player').show();
@ -75,7 +100,7 @@ $(function(){
if (sdk) { if (sdk) {
sdk.close(); sdk.close();
} }
sdk = new SrsRtcPlayerAsync(); sdk = new SrsRtcWhipWhepAsync();
// https://webrtc.org/getting-started/remote-streams // https://webrtc.org/getting-started/remote-streams
$('#rtc_media_player').prop('srcObject', sdk.stream); $('#rtc_media_player').prop('srcObject', sdk.stream);
@ -83,8 +108,10 @@ $(function(){
// sdk.ontrack = function (event) { console.log('Got track', event); sdk.stream.addTrack(event.track); }; // sdk.ontrack = function (event) { console.log('Got track', event); sdk.stream.addTrack(event.track); };
// For example: webrtc://r.ossrs.net/live/livestream // For example: webrtc://r.ossrs.net/live/livestream
// Convert to WHEP URL: http://localhost:1985/rtc/v1/whep/?app=live&stream=livestream
var url = $("#txt_url").val(); var url = $("#txt_url").val();
sdk.play(url).then(function(session){ var whepUrl = convertToWhepUrl(url);
sdk.play(whepUrl).then(function(session){
$('#sessionid').html(session.sessionid); $('#sessionid').html(session.sessionid);
$('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid); $('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid);
}).catch(function (reason) { }).catch(function (reason) {

View File

@ -71,7 +71,33 @@
</div> </div>
<script type="text/javascript"> <script type="text/javascript">
$(function(){ $(function(){
// Convert webrtc:// URL to WHIP URL
// webrtc://domain:port/app/stream => http://domain:1985/rtc/v1/whip/?app=app&stream=stream
var convertToWhipUrl = function(webrtcUrl) {
var a = document.createElement("a");
a.href = webrtcUrl.replace("webrtc://", "http://").replace("rtc://", "http://");
var schema = window.location.protocol;
var port = a.port || 1985;
if (schema === 'https:') {
port = a.port || 443;
}
var app = a.pathname.substring(1, a.pathname.lastIndexOf("/"));
var stream = a.pathname.slice(a.pathname.lastIndexOf("/") + 1);
var whipUrl = schema + '//' + a.hostname + ':' + port + '/rtc/v1/whip/?app=' + app + '&stream=' + stream;
// Append query parameters from original URL
if (a.search) {
whipUrl += '&' + a.search.substring(1);
}
return whipUrl;
};
var sdk = null; // Global handler to do cleanup when republishing. var sdk = null; // Global handler to do cleanup when republishing.
var statsTimer = null; // Timer for getting codec stats.
var startPublish = function() { var startPublish = function() {
$('#rtc_media_player').show(); $('#rtc_media_player').show();
@ -79,7 +105,11 @@ $(function(){
if (sdk) { if (sdk) {
sdk.close(); sdk.close();
} }
sdk = new SrsRtcPublisherAsync(); if (statsTimer) {
clearInterval(statsTimer);
statsTimer = null;
}
sdk = new SrsRtcWhipWhepAsync();
// User should set the stream when publish is done, @see https://webrtc.org/getting-started/media-devices // User should set the stream when publish is done, @see https://webrtc.org/getting-started/media-devices
// However SRS SDK provides a consist API like https://webrtc.org/getting-started/remote-streams // However SRS SDK provides a consist API like https://webrtc.org/getting-started/remote-streams
@ -87,17 +117,27 @@ $(function(){
// Optional callback, SDK will add track to stream. // Optional callback, SDK will add track to stream.
// sdk.ontrack = function (event) { console.log('Got track', event); sdk.stream.addTrack(event.track); }; // sdk.ontrack = function (event) { console.log('Got track', event); sdk.stream.addTrack(event.track); };
// https://developer.mozilla.org/en-US/docs/Web/Media/Formats/WebRTC_codecs#getting_the_supported_codecs // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/getStats
sdk.pc.onicegatheringstatechange = function (event) { statsTimer = setInterval(function() {
if (sdk.pc.iceGatheringState === "complete") { sdk.pc.getStats(null).then(function(stats) {
$('#acodecs').html(SrsRtcFormatSenders(sdk.pc.getSenders(), "audio")); var audioStatsOutput = SrsRtcFormatStats(stats, 'audio');
$('#vcodecs').html(SrsRtcFormatSenders(sdk.pc.getSenders(), "video")); var videoStatsOutput = SrsRtcFormatStats(stats, 'video');
}
}; $('#acodecs').html(audioStatsOutput);
$('#vcodecs').html(videoStatsOutput);
if (audioStatsOutput && videoStatsOutput) {
clearInterval(statsTimer);
statsTimer = null;
}
});
}, 1000);
// For example: webrtc://r.ossrs.net/live/livestream // For example: webrtc://r.ossrs.net/live/livestream
// Convert to WHIP URL: http://localhost:1985/rtc/v1/whip/?app=live&stream=livestream
var url = $("#txt_url").val(); var url = $("#txt_url").val();
sdk.publish(url).then(function(session){ var whipUrl = convertToWhipUrl(url);
sdk.publish(whipUrl).then(function(session){
$('#sessionid').html(session.sessionid); $('#sessionid').html(session.sessionid);
$('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid); $('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid);
}).catch(function (reason) { }).catch(function (reason) {

View File

@ -446,8 +446,34 @@
} }
// Async-await-promise based SRS RTC Player. // Convert webrtc:// URL to WHEP URL
function SrsRtcPlayerAsync() { // webrtc://domain:port/app/stream => http://domain:1985/rtc/v1/whep/?app=app&stream=stream
function convertToWhepUrl(webrtcUrl) {
var a = document.createElement("a");
a.href = webrtcUrl.replace("webrtc://", "http://").replace("rtc://", "http://");
var schema = window.location.protocol;
var port = a.port || 1985;
if (schema === 'https:') {
port = a.port || 443;
}
var app = a.pathname.substring(1, a.pathname.lastIndexOf("/"));
var stream = a.pathname.slice(a.pathname.lastIndexOf("/") + 1);
var whepUrl = schema + '//' + a.hostname + ':' + port + '/rtc/v1/whep/?app=' + app + '&stream=' + stream;
// Append query parameters from original URL
if (a.search) {
whepUrl += '&' + a.search.substring(1);
}
return whepUrl;
}
// Removed embedded SrsRtcPlayerAsync - now using SrsRtcWhipWhepAsync from srs.sdk.js
// The old API-based player is deprecated, use WHIP/WHEP instead
function SrsRtcPlayerAsync_Deprecated() {
var self = {}; var self = {};
// @see https://github.com/rtcdn/rtcdn-draft // @see https://github.com/rtcdn/rtcdn-draft
@ -1018,16 +1044,17 @@
sdk.close(); sdk.close();
} }
sdk = new SrsRtcPlayerAsync(); sdk = new SrsRtcWhipWhepAsync();
sdk.onaddstream = function (event) {
console.log('Start play, event: ', event); // https://webrtc.org/getting-started/remote-streams
$('#rtc_media_player').prop('srcObject', event.stream); $('#rtc_media_player').prop('srcObject', sdk.stream);
};
// For example: // For example:
// webrtc://r.ossrs.net/live/livestream // webrtc://r.ossrs.net/live/livestream
// Convert to WHEP URL: http://localhost:1985/rtc/v1/whep/?app=live&stream=livestream
var url = $("#txt_rtc_url").val(); var url = $("#txt_rtc_url").val();
sdk.play(url).then(function(session){ var whepUrl = convertToWhepUrl(url);
sdk.play(whepUrl).then(function(session){
$('#sessionid').html(session.sessionid); $('#sessionid').html(session.sessionid);
$('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid); $('#simulator-drop').attr('href', session.simulator + '?drop=1&username=' + session.sessionid);
}).catch(function (reason) { }).catch(function (reason) {