switch camera during call peer js webrtc? - webrtc

we are using peer js webrtc for video call. Everything is working fine just the problem is i am not able to switch camera during call. I have done some work where i can switch camera in local during call but its doesnt effect on remote area.
here is my code
$('select').on('change', function (e) {
navigator.mediaDevices.enumerateDevices().then(function (devices) {
var valueSelected = $("#myselect option:selected").val();
alert(valueSelected);
//var myselect = 0;
if (valueSelected == "0") {
var cameras = [];
devices.forEach(function (device) {
'videoinput' === device.kind && cameras.push(device.deviceId);
});
var constraints = { video: { deviceId: { exact: cameras[0] } } };
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
window.localStream = stream;
myapp.setMyVideo(window.localStream)
//if (callback)
// callback();
}, function (err) {
console.log("The following error occurred: " + err.name);
alert('Unable to call ' + err.name)
});
}
else {
var cameras = [];
devices.forEach(function (device) {
'videoinput' === device.kind && cameras.push(device.deviceId);
});
var constraints = { video: { deviceId: { exact: cameras[1] } } };
navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
window.localStream = stream;
myapp.setMyVideo(window.localStream)
//if (callback)
// callback();
}, function (err) {
console.log("The following error occurred: " + err.name);
alert('Unable to call ' + err.name)
});
}
//var myselect = $("#myselect option:selected").val();
});
});

The recommended way to change stream when a peer-to-peer connection is established is to use replaceTrack function that does not require ICE renegotiation:
RTCRtpSender.replaceTrack
The documentation says:
Among the use cases for replaceTrack() is the common need to switch between the rear- and front-facing cameras on a phone. With replaceTrack(), you can simply have a track object for each camera and switch between the two as needed. See the example...

Related

How can I receive remote stream using [agora.io]

I can't receive any data from the remote stream and the div with the id of the remote streams that I've created with Javascript doesn't show I don't understand why ! The Javascript code doesn't work on the browser it's a little bit strange it's my first time coming across with this kind of problem please help me solve it.
This is the code :
// Local stream
// rtc object
var rtc = {
client: null,
joined: false,
published: false,
localStream: null,
remoteStreams: [],
params: {}
};
// Options for joining a channel
var option = {
mode: "rtc",
codec: "h264",
appID: "22a27d03d0edf54749a03597d72ad82aaa78",
channel: "qiossa",
uid: null,
token: "006a27d03d0edf54749a03597d72ad82aaaIADHJF46Q3g4Jn+mjfRgh5Le76OO2BpUfEuvw1Qv+35XKFwgy+4AAAAAEACfOV6k44bGXgEAAQCIh8Ze"
};
// Create a client
rtc.client = AgoraRTC.createClient({mode: option.mode, codec: option.codec});
// Initialize the client
rtc.client.init(option.appID, function () {
console.log("init success");
}, (err) => {
console.error(err);
});
// Join a channel
rtc.client.join(option.token, option.channel, option.uid, function (uid) {
console.log("join channel: " + option.channel + " success, uid: " + uid);
rtc.params.uid = uid;
}, function(err) {
console.error("client join failed", err);
});
// Create a local stream
rtc.localStream = AgoraRTC.createStream({
streamID: rtc.params.uid,
audio: true,
video: true,
screen: false,
});
// Initialize the local stream
rtc.localStream.init(function () {
console.log("init local stream success");
// play stream with html element id "local_stream"
rtc.localStream.play("local_stream");
}, function (err) {
console.error("init local stream failed ", err);
});
// Publish the local stream
rtc.client.publish(rtc.localStream, function (err) {
console.log("publish failed");
console.error(err);
});
//*************************************************************************************************************//
// Remote stream
rtc.client.on("stream-added", function (evt) {
var remoteStream = evt.stream;
var id = remoteStream.getId();
if (id !== rtc.params.uid) {
rtc.client.subscribe(remoteStream, function (err) {
console.log("stream subscribe failed", err);
});
}
console.log("stream-added remote-uid: ", id);
});
rtc.client.on("stream-subscribed", function (evt) {
var remoteStream = evt.stream;
var id = remoteStream.getId();
// Add a view for the remote stream.
let streamDiv=document.createElement("div"); // Create a new div for every stream
streamDiv.id= id; // Assigning id to div
streamDiv.style.transform="rotateY(180deg)"; // Takes care of lateral inversion (mirror image)
remoteContainer.appendChild(streamDiv);
// Play the remote stream.
remoteStream.play("remote_video_" + id);
console.log("stream-subscribed remote-uid: ", id);
});
Photo of the problem
The local stream needs to be created, initialised, played and published within the join function.
This is the corrected code for the rtc.client.join() function:
rtc.client.join(option.token, option.channel, option.uid, (uid)=>{
console.log("join channel: " + option.channel + " success, uid: " + uid);
rtc.params.uid = uid;
// Create a local stream
rtc.localStream = AgoraRTC.createStream({
streamID: rtc.params.uid,
audio: true,
video: true,
screen: false,
});
// Initialize the local stream
rtc.localStream.init(function () {
console.log("init local stream success");
// play stream with html element id "local_stream"
rtc.localStream.play("local_stream");
}, function (err) {
console.error("init local stream failed ", err);
});
// Publish the local stream
rtc.client.publish(rtc.localStream, function (err) {
console.log("publish failed");
console.error(err);
});
}, function(err) {
console.error("client join failed", err);
});
Get back to us for any further queries.
console problems
// Local stream
// rtc object
var rtc = {
client: null,
joined: false,
published: false,
localStream: null,
remoteStreams: [],
params: {}
};
// Options for joining a channel
var option = {
mode: "rtc",
codec: "h264",
appID: "",
channel: "qiossa",
uid: null,
token: "006a27d03d0edf54749a03597d72ad82aaaIADkVIvop7lo0OEkm/7Tuz/Tp4M+TXhFd9DkLAAwu9fNllwgy+4AAAAAEAD4aAmV2FzKXgEAAQBjT8pe"
};
// Create a client
rtc.client = AgoraRTC.createClient({mode: option.mode, codec: option.codec});
// Initialize the client
rtc.client.init(option.appID, function () {
console.log("init success");
}, (err) => {
console.error(err);
});
// Join a channel
rtc.client.join(option.token, option.channel, option.uid, function (uid) {
console.log("join channel: " + option.channel + " success, uid: " + uid);
rtc.params.uid = uid;
// Create a local stream
rtc.localStream = AgoraRTC.createStream({
streamID: rtc.params.uid,
audio: true,
video: true,
screen: false,
});
// Initialize the local stream
rtc.localStream.init(function () {
console.log("init local stream success");
// play stream with html element id "local_stream"
rtc.localStream.play("local_stream");
}, function (err) {
console.error("init local stream failed ", err);
});
// Publish the local stream
rtc.client.publish(rtc.localStream, function (err) {
console.log("publish failed");
console.error(err);
});
}, function(err) {
console.error("client join failed", err);
});
//*************************************************************************************************************//
// Remote stream
rtc.client.on("stream-added", function (evt) {
var remoteStream = evt.stream;
var id = remoteStream.getId();
if (id !== rtc.params.uid) {
rtc.client.subscribe(remoteStream, function (err) {
console.log("stream subscribe failed", err);
});
}
console.log("stream-added remote-uid: ", id);
});
rtc.client.on("stream-subscribed", function (evt) {
var remoteStream = evt.stream;
var id = remoteStream.getId();
// Add a view for the remote stream.
addView(id);
// Play the remote stream.
remoteStream.play("remote_video_" + id);
console.log("stream-subscribed remote-uid: ", id);
});
rtc.client.on("stream-removed", function (evt) {
var remoteStream = evt.stream;
var id = remoteStream.getId();
// Stop playing the remote stream.
remoteStream.stop("remote_video_" + id);
// Remove the view of the remote stream.
removeView(id);
console.log("stream-removed remote-uid: ", id);
});
// Leave the channel
rtc.client.leave(function () {
// Stop playing the local stream
rtc.localStream.stop();
// Close the local stream
rtc.localStream.close();
// Stop playing the remote streams and remove the views
while (rtc.remoteStreams.length > 0) {
var stream = rtc.remoteStreams.shift();
var id = stream.getId();
stream.stop();
removeView(id);
}
console.log("client leaves channel success");
}, function (err) {
console.log("channel leave failed");
console.error(err);
});
function addView (id, show) {
if (!$("#" + id)[0]) {
$("<div/>", {
id: "remote_video_panel_" + id,
class: "video-view",
}).appendTo("#video")
$("<div/>", {
id: "remote_video_" + id,
class: "video-placeholder",
}).appendTo("#remote_video_panel_" + id)
$("<div/>", {
id: "remote_video_info_" + id,
class: "video-profile " + (show ? "" : "hide"),
}).appendTo("#remote_video_panel_" + id)
$("<div/>", {
id: "video_autoplay_"+ id,
class: "autoplay-fallback hide",
}).appendTo("#remote_video_panel_" + id)
}
}
function removeView (id) {
if ($("#remote_video_panel_" + id)[0]) {
$("#remote_video_panel_"+id).remove()
}
}

Anonymous meeting join - Skype UCWA for online

I am trying to join a meeting anonymously through a meeting URI and this does not seem to work. I went to the SKYPE UCWA site and went to the interactive SDK - and tried to join a meeting anonymously from there but the page does not do anything.
https://ucwa.skype.com/websdk
Below is the code that I am trying to join a meeting anonymously, but the call to client.signInManager.signIn never completes and neither any exception is thrown.
Looking for suggestions to resolve this issue. Also, if someone has working code of joining a meeting anonymously using SKYPE web sdk (UCWA), please share the same. Thanks.
function InitialiseSkype() {
Skype.initialize({ apiKey: config.apiKey }, function (api) {
window.skypeWebAppCtor = api.application;
window.skypeWebApp = new api.application();
client = new window.skypeWebAppCtor;
//once intialised, sign in
alert("Skype SDK Initialized");
JoinAnonymous();
}, function (err) {
console.log(err);
alert('Cannot load the SDK.');
});
}
function JoinAnonymous(){
client.signInManager.signIn({
version: config.Version,
name: $('#name').val(),
meeting: $('#meetingUri').val()
}).then(function () {
alert('Signed In, Anonymously');
var conversation = application.conversationsManager.getConversationByUri(uri);
}, function (error) {
alert(error);
});
}
Actually I did sign in anonymously using that code :
//Init
var config = {apiKey: 'a42fcebd-5b43-4b89-a065-74450fb91255', // SDK
apiKeyCC: '9c967f6b-a846-4df2-b43d-5167e47d81e1' // SDK+UI
};
Skype.initialize({ apiKey: config.apiKey }, function (api) {
window.skypeWebApp = new api.application;
}, function (err) {
console.log("cannot load the sdk package", err);
});
//Actual code
var uri ="sip:xxxxxxxx;gruu;opaque=app:conf:focus:id:xxxxxxxx";
window.skypeWebApp.signInManager.signIn({
name: "pseudo",
meeting:uri
}).then(function () {
alert('Signed In, Anonymously');
}, function (error) {
alert(error);
});
I did connect with the uri given in the ucwa.skype interactive web sdk page.
But I did not manage to join the conversation after that, probably because the interactive sample does not really create the room.
I can join a meeting from a office365 account while logged in with a sample account. However I can not join anonymously my meeting room.
Do you try with an on-premise account or with a office365 account ?
Looks like Anonymous join for a meeting is not yet available for Skype For Business online.
New update of WebSDK now support anonymous meeting join for SfB Online
(function () {
'use strict';
// this will be populated when the auth token is fetched
// it is later needed to sign into Skype for Business
var authDetails = {};
// A reference to the Skype SDK application object
// set during initialization
var app;
displayStep(0);
registerUIListeners();
// Initializing the Skype application
Skype.initialize({
apiKey: '9c967f6b-a846-4df2-b43d-5167e47d81e1'
}, function (api) {
console.log('Skype SDK initialization successful');
app = api.UIApplicationInstance;
// Once it is initialized, display a UI prompt for a meeting URL
displayStep(1);
}, function (err) {
console.error('Skype SDK initialization error:', err);
});
// After the user submits the meeting URL the next step is to
// fetch an auth token
function getToken(evt) {
var input = evt.target.querySelector('input'),
meetingUrl = input.value,
request = new XMLHttpRequest(),
data;
evt.preventDefault();
console.log('Fetching auth token from meeting url:', meetingUrl);
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
var sessionId = guid();
data = 'ApplicationSessionId=' + sessionId +
'&AllowedOrigins=' + encodeURIComponent(window.location.href) +
'&MeetingUrl=' + encodeURIComponent(meetingUrl);
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
authDetails.discoverUrl = response.DiscoverUri;
authDetails.authToken = "Bearer " + response.Token;
console.log('Successfully fetched the anonymous auth token and discoverUrl', authDetails);
displayStep(2);
}
else {
console.error('An error occured, fetching the anonymous auth token', request.responseText);
}
}
};
request.open('post', 'http://webrtctest.cloudapp.net/getAnonTokenJob');
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
// This uses the auth token and discovery URL to sign into Skype
// and join the meeting
function joinAVMeeting(evt) {
var input = evt.target.querySelector('input'),
name = input.value;
evt.preventDefault();
console.log('Joinig meeting as:', name);
app.signInManager.signIn({
name: name,
cors: true,
root: { user: authDetails.discoverUrl },
auth: function (req, send) {
// Send token with all requests except for the GET /discover
if (req.url != authDetails.discoverUrl)
req.headers['Authorization'] = authDetails.authToken;
return send(req);
}
}).then(function () {
// When joining a conference anonymously, the SDK automatically creates
// a conversation object to represent the conference being joined
var conversation = app.conversationsManager.conversations(0);
console.log('Successfully signed in with anonymous online meeting token');
registerAppListeners(conversation);
// This turns on local video and joins the meeting
startVideoService(conversation);
}).catch(function (error) {
console.error('Unable to join conference anonymously:', error);
});
function registerAppListeners(conversation) {
conversation.selfParticipant.video.state.when('Connected', function () {
console.log('Showing self video');
document.querySelector('.self').style.display = 'inline-block';
setupContainer(conversation.selfParticipant.video.channels(0), document.querySelector('.self .video'));
displayName(document.querySelector('.self'), conversation.selfParticipant);
console.log('The video mode of the application is:', conversation.videoService.videoMode());
if (conversation.videoService.videoMode() === 'MultiView') {
// Loading the sample in any other browser than Google Chrome means that
// the videoMode is set to 'MultiView'
// Please refer to https://msdn.microsoft.com/en-us/skype/websdk/docs/ptvideogroup
// on an example on how to implement group video.
}
// When in active speaker mode only one remote channel is available.
// To display videos of multiple remote parties the video in this one channel
// is switched out automatically, depending on who is currently speaking
if (conversation.videoService.videoMode() === 'ActiveSpeaker') {
var activeSpeaker = conversation.videoService.activeSpeaker;
setupContainer(activeSpeaker.channel, document.querySelector('.remote .video'));
activeSpeaker.channel.isVideoOn.when(true, function () {
document.querySelector('.remote').style.display = 'inline-block';
activeSpeaker.channel.isStarted(true);
console.log('ActiveSpeaker video is available and has been turned on.');
});
activeSpeaker.channel.isVideoOn.when(false, function () {
document.querySelector('.remote').style.display = 'none';
activeSpeaker.channel.isStarted(false);
console.log('ActiveSpeaker video is not available anymore and has been turned off.');
});
// the .participant object changes when the active speaker changes
activeSpeaker.participant.changed(function (newValue, reason, oldValue) {
console.log('The ActiveSpeaker has changed. Old ActiveSpeaker:', oldValue && oldValue.displayName(), 'New ActiveSpeaker:', newValue && newValue.displayName());
if (newValue) {
displayName(document.querySelector('.remote'), newValue);
}
});
}
});
conversation.state.changed(function (newValue, reason, oldValue) {
if (newValue === 'Disconnected' && (oldValue === 'Connected' || oldValue === 'Connecting')) {
console.log('The conversation has ended.');
reset();
}
});
}
function setupContainer(videoChannel, videoDiv) {
videoChannel.stream.source.sink.format('Stretch');
videoChannel.stream.source.sink.container(videoDiv);
}
function displayName(container, person) {
container.querySelector('.displayName .detail').innerHTML = person.displayName();
}
function startVideoService(conversation) {
conversation.videoService.start().then(null, function (error) {
console.error('An error occured joining the conversation:', error);
});
displayStep(3);
}
}
function endConversation(evt) {
var conversation = app.conversationsManager.conversations(0);
evt.preventDefault();
conversation.leave().then(function () {
console.log('The conversation has ended.');
reset();
}, function (error) {
console.error('An error occured ending the conversation:', error);
}).then(function () {
reset();
});
}
//-----------------------------------------------------------------------
//UI helper functions
function displayStep(step) {
var nodes = document.querySelectorAll('.step');
for (var i = 0; i < nodes.length; ++i) {
var node = nodes[i];
node.style.display = 'none';
if (i === step) {
node.style.display = 'block';
}
}
}
function registerUIListeners() {
document.querySelector('.step1').onsubmit = getToken;
document.querySelector('.step2').onsubmit = joinAVMeeting;
document.querySelector('.step3').onsubmit = endConversation;
}
function reset() {
window.location = window.location.href;
}
})();
https://github.com/OfficeDev/skype-docs/blob/master/Skype/WebSDK/samples/Meetings/Anonymous%20Online/standalone/index.js

DOMException: Failed to set remote offer sdp: Called in wrong state: STATE_SENTOFFER

I am trying to make a video calling web application using webRTC. I am using angularjs and express.io
I am getting this error:
DOMException: Failed to set remote offer sdp: Called in wrong state: STATE_SENTOFFER
Some of my code is:
// in controller (socket is already defined in controller)
var videolocal = document.getElementById('videolocal');
var videoremote = document.getElementById('videoremote');
var streamlocal = null;
var pc = null;
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
var configuration = {'iceServers': [
// {'url': 'stun:stun.services.mozilla.com'},
{'url': 'stun:stun.l.google.com:19302'}
]};
// run start(true) to initiate a call
$scope.start = function() {
console.log('start');
// get the local stream, show it in the local video element and send it
navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
videolocal.src = URL.createObjectURL(stream);
pc = new RTCPeerConnection(configuration);
pc.addStream(stream);
// once remote stream arrives, show it in the remote video element
pc.onaddstream = function (evt) {
console.log('onaddstream');
videoremote.src = URL.createObjectURL(evt.stream);
};
// send any ice candidates to the other peer
pc.onicecandidate = function (evt) {
console.log('onicecandidate');
if(evt.candidate){
socket.emit('video_call',{user:2, type: 'candidate', candidate: evt.candidate});
}
};
// create an offer
pc.createOffer(function (offer) {
socket.emit('video_call', {user:2, type: "offer", offer: offer});
pc.setLocalDescription(offer);
}, function (error) {
alert("Error when creating an offer");
});
}, function () {alert('error in start')});
}
$scope.start();
socket.on('video_call', function (data) {
console.log(data);
//when somebody sends us an offer
function handleOffer(offer) {
// this line is giving error
pc.setRemoteDescription(new RTCSessionDescription(offer), function(){alert('success')}, function(e){ console.log(e); alert(e)});
//create an answer to an offer
pc.createAnswer(function (answer) {
pc.setLocalDescription(answer);
socket.emit('video_call', {user:2, type: "answer", answer: answer});
}, function (error) {
console.log(error);
alert("Error when creating an answer");
});
};
//when we got an answer from a remote user
function handleAnswer(answer) {
pc.setRemoteDescription(new RTCSessionDescription(answer));
};
//when we got an ice candidate from a remote user
function handleCandidate(candidate) {
pc.addIceCandidate(new RTCIceCandidate(candidate));
};
switch(data['type']) {
case "offer":
handleOffer(data["offer"]);
break;
case "answer":
handleAnswer(data['answer']);
break;
//when a remote peer sends an ice candidate to us
case "candidate":
handleCandidate(data['candidate']);
break;
default:
break;
}
});
On server:
// this function is called on video_call event
video_call: function (data) {
var id = data.user;
// if user is active
// users is dict of users (user_id as key)
if(Object.keys(users).indexOf(id.toString()) > -1){
// for each device of the user
users[id].forEach(function(user_socket){
console.log(data);
user_socket.emit('video_call', data);
});
}
}
Please can anyone tell what is wrong with this code. The local stream is capturing properly. I am using chromium browser.
Data on server:
I think the problem is that in your handleOffer() function you need to create another PeerConnection and call setRemoteDescription() on that pc.
var remote_pc = new RTCPeerConnection(configuration)
remote_pc.setRemoteDescription(new RTCSessionDescription(offer), ...) {
remote_pc.createAnswer()
}
This is what I have in my code.
EDIT: In the official link you can go to chapter 11.7 and check the steps after 15 (when the offer is sent and the other peer receives it).

WebRTC using promises - Remote Video not seen at either end

I had earlier posted some questions on this problem. At that time I had two separate programs for caller and receiver. I was also using old-fashioned callback API. Thanks to help from #jib on that post, I was able to understand the need for some fundamental changes. I rewrote the program to make it an integrated one for both caller and receiver and have used the WebRTC promises API. My problem is that I am not getting remote video from either end. One part I understand but do not know the solution: The receiver does not create SDPs for Video in the first place, only for audio. The caller part does create SDPS for Video and audio but on the receiver end there is no event generated for remote stream.
I have checked, through console logs, that the core functions work. Offer SDP is created, sent out, received, answer SDP created, sent out, received, etc. Candidates get exchanged and added too. But the .onaddstream event handler is never triggered. Local video is shown but that is trivial.
I have spent a LOT of time on this. I simply need to get that exciting feeling of seeing remote video on both ends which has kept me going. ANY HELP WILL BE SINCERELY APPRECIATED.
<script>
$(document).ready(function () {
var iceCandidates = [], countIceCandidates=0;
var socket = io.connect();
socket.on('connect',function() { console.log("Socket connected"); });
var pc = new RTCPeerConnection({"iceServers":[{"url":"stun:stun.l.google.com:19302"}]});
//If remote video stream comes in, display it in DIV vid2
pc.onaddStream = function (event) {
stream = event.stream;
var video = $('#vid2');
video.attr('src', URL.createObjectURL(stream));
video.onloadedmetadata = function(e) { video.play(); }
}
//Display media in both Caller and Receiver
navigator.mediaDevices.getUserMedia({ audio: true, video: true })
.then(function(stream) {
var video = $('#vid1');
video.attr('src', URL.createObjectURL(stream));
video.onloadedmetadata = function(e) { video.play(); };
pc.addStream(stream);
})
.catch(function(err) { console.log(err);});
//INITIATE CALL
$('#call').click(function() {
pc.createOffer({ offerToReceiveVideo: true, offerToReceiveAudio: true })
.then(function(offer) {
localSessionDescription = new RTCSessionDescription(offer);
pc.setLocalDescription(localSessionDescription)
.then (function() { socket.emit('sdpOffer',localSessionDescription); })
.catch(function(err) { console.log("Error in setLocalDescription"); console.log(err); })
.catch(function(err) { console.log("Error in createOffer"); console.log(err); })
});
})
pc.onicecandidate = function (event) {
socket.emit('candidate',event.candidate);
};
socket.on('candidate',function (data) {
if (data != null) {
pc.addIceCandidate(new RTCIceCandidate(data))
.then(function() { console.log("peer candidate added");})
.catch(function(err) {console.log(err); console.log("Error during peer candidate addition");});
}
});
socket.on('disconnect',function() { alert("Disconnected"); });
function error(err) {
console.log("The following error occurred: " + err.name);
}
socket.on('sdpAnswer',function(data) {
sdpAnswer = new RTCSessionDescription(data.sdpAnswer);
pc.setRemoteDescription(sdpAnswer)
.then(function() { console.log("Answer SDP Set:"); console.log(sdpAnswer); })
.catch(function(err) { console.log("Error enountered when setting remote SDP Answer"); console.log(err)});
});
socket.on('sdpOffer', function(data) {
sdpOffer = new RTCSessionDescription(data.sdpOffer);
pc.setRemoteDescription(sdpOffer)
.then(function() { console.log("Remote SDP set in receiver");
pc.createAnswer()
.then(function(sdpAnswer) {
localSessionDescription = new RTCSessionDescription(sdpAnswer);
socket.emit('sdpAnswer',localSessionDescription);
pc.setLocalDescription(localSessionDescription)
.then(function(){
console.log("Local SDP Description set in receiver:");
})
.catch(function(err) { console.log("Error enountered when setting local SDP in receiver"); console.log(err)});
})
.catch(function(err) { console.log("Error enountered when creating answer SDP in receiver"); console.log(err)});
});
});
}); //End of document.ready function
</script>
ON THE SERVER SIDE (RELEVANT CODE ONLY). I have included here just in case there are any datatype related issues - object types, etc. getting changed when sent thru the server.
io.sockets.on('connection', function(socket) {
socket.on('sdpOffer', function(data) {
sdpOffer = data.sdp;
socket.broadcast.emit('sdpOffer',{"sdpOffer":data});
});
socket.on('sdpAnswer', function(data) {
sdpAnswer = data.sdp;
socket.broadcast.emit('sdpAnswer',{"sdpAnswer":data});
});
socket.on('candidate', function(data) {
socket.broadcast.emit('candidate',data);
});
});
Rename pc.onaddStream to pc.onaddstream.

Chrome, recognize open tab

I'm creating an extenstion for google chrome that will perform checking if a stream on twitch.tv is online and will notify the user evey X minutes, I got that covered. What I'm looking for is a JScirpt code that will recognize if user is already on the streamers channel and will stop notifying him.
var username="$user";
setInterval(check,300000);
function check()
{
request("https://api.twitch.tv/kraken/streams/" + username, function() {
var json = JSON.parse(this.response);
if (json.stream == null)
{
chrome.browserAction.setIcon({ path: "offline.png" });
}
else
{
notify();
}
});
return 1;
}
function notify(){
var opt = {type: "basic",title: username + " is streaming!",message: "Click to join!",iconUrl: "start.png"};
chrome.notifications.create("", opt, function(notificationId)
{
setTimeout(function()
{
chrome.notifications.clear(notificationId, function(wasCleared) { console.log(wasCleared); });
}, 3000);
});
chrome.browserAction.setIcon({path:"online.png" });
}
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.create({ url: "http://www.twitch.tv/"+username });
});
function request(url, func, post)
{
var xhr = new XMLHttpRequest();
xhr.onload = func;
xhr.open(post == undefined ? 'GET' : 'POST', url, true);
xhr.send(post || '');
return 1;
}
check();
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
You can read more here.