GithubHelp home page GithubHelp logo

simplewebrtc's Introduction

Deprecated

The open-source version of SimpleWebRTC has been deprecated. This repository will remain as-is but is no longer actively maintained. You can find the old website in the gh-pages branch. Read more about the "new" SimpleWebRTC (which is an entirely different thing) on https://simplewebrtc.com

SimpleWebRTC - World's easiest WebRTC lib

Want to see it in action? Check out the demo: https://simplewebrtc.com/demo.html

Want to run it locally?

  1. Install all dependencies and run the test page
npm install && npm run test-page
  1. open your browser to https://0.0.0.0:8443/test/

It's so easy:

1. Some basic html

<!DOCTYPE html>
<html>
    <head>
        <script src="https://simplewebrtc.com/latest-v2.js"></script>
        <style>
            #remoteVideos video {
                height: 150px;
            }
            #localVideo {
                height: 150px;
            }
        </style>
    </head>
    <body>
        <video id="localVideo"></video>
        <div id="remoteVideos"></div>
    </body>
</html>

Installing through NPM

npm install --save simplewebrtc

# for yarn users
yarn add simplewebrtc

After that simply import simplewebrtc into your project

import SimpleWebRTC from 'simplewebrtc';

2. Create our WebRTC object

var webrtc = new SimpleWebRTC({
    // the id/element dom element that will hold "our" video
    localVideoEl: 'localVideo',
    // the id/element dom element that will hold remote videos
    remoteVideosEl: 'remoteVideos',
    // immediately ask for camera access
    autoRequestMedia: true
});

3. Tell it to join a room when ready

// we have to wait until it's ready
webrtc.on('readyToCall', function () {
    // you can name it anything
    webrtc.joinRoom('your awesome room name');
});

Available options

peerConnectionConfig - Set this to specify your own STUN and TURN servers. By default, SimpleWebRTC uses Google's public STUN server (stun.l.google.com:19302), which is intended for public use according to: https://twitter.com/HenrikJoreteg/status/354105684591251456

Note that you will most likely also need to run your own TURN servers. See http://www.html5rocks.com/en/tutorials/webrtc/infrastructure/ for a basic tutorial.

Filetransfer

Sending files between individual participants is supported. See http://simplewebrtc.com/filetransfer.html for a demo.

Note that this is not file sharing between a group which requires a completely different approach.

It's not always that simple...

Sometimes you need to do more advanced stuff. See http://simplewebrtc.com/notsosimple.html for some examples.

API

Constructor

new SimpleWebRTC(options)

  • object options - options object provided to constructor consisting of:
    • string url - required url for signaling server. Defaults to signaling server URL which can be used for development. You must use your own signaling server for production.
    • object socketio - optional object to be passed as options to the signaling server connection.
    • Connection connection - optional connection object for signaling. See Connection below. Defaults to a new SocketIoConnection
    • bool debug - optional flag to set the instance to debug mode
    • [string|DomElement] localVideoEl - ID or Element to contain the local video element
    • [string|DomElement] remoteVideosEl - ID or Element to contain the remote video elements
    • bool autoRequestMedia - optional(=false) option to automatically request user media. Use true to request automatically, or false to request media later with startLocalVideo
    • bool enableDataChannels optional(=true) option to enable/disable data channels (used for volume levels or direct messaging)
    • bool autoRemoveVideos - optional(=true) option to automatically remove video elements when streams are stopped.
    • bool adjustPeerVolume - optional(=false) option to reduce peer volume when the local participant is speaking
    • number peerVolumeWhenSpeaking - optional(=.0.25) value used in conjunction with adjustPeerVolume. Uses values between 0 and 1.
    • object media - media options to be passed to getUserMedia. Defaults to { video: true, audio: true }. Valid configurations described on MDN with official spec at w3c.
    • object receiveMedia - optional RTCPeerConnection options. Defaults to { offerToReceiveAudio: 1, offerToReceiveVideo: 1 }.
    • object localVideo - optional options for attaching the local video stream to the page. Defaults to
    {
        autoplay: true, // automatically play the video stream on the page
        mirror: true, // flip the local video to mirror mode (for UX)
        muted: true // mute local video stream to prevent echo
    }
    • object logger - optional alternate logger for the instance; any object that implements log, warn, and error methods.
    • object peerConnectionConfig - optional options to specify own your own STUN/TURN servers. By default these options are overridden when the signaling server specifies the STUN/TURN server configuration. Example on how to specify the peerConnectionConfig:
    {
      "iceServers": [{
              "url": "stun3.l.google.com:19302"
          },
          {
              "url": "turn:your.turn.servers.here",
              "username": "your.turn.server.username",
              "credential": "your.turn.server.password"
          }
      ],
      iceTransports: 'relay'
    }

Fields

capabilities - the webrtcSupport object that describes browser capabilities, for convenience

config - the configuration options extended from options passed to the constructor

connection - the socket (or alternate) signaling connection

webrtc - the underlying WebRTC session manager

Events

To set up event listeners, use the SimpleWebRTC instance created with the constructor. Example:

var webrtc = new SimpleWebRTC(options);
webrtc.on('connectionReady', function (sessionId) {
    // ...
})

'connectionReady', sessionId - emitted when the signaling connection emits the connect event, with the unique id for the session.

'createdPeer', peer - emitted three times:

  • when joining a room with existing peers, once for each peer

  • when a new peer joins a joined room

  • when sharing screen, once for each peer

  • peer - the object representing the peer and underlying peer connection

'channelMessage', peer, channelLabel, {messageType, payload} - emitted when a broadcast message to all peers is received via dataChannel by using the method sendDirectlyToAll().

'stunservers', [...args] - emitted when the signaling connection emits the same event

'turnservers', [...args] - emitted when the signaling connection emits the same event

'localScreenAdded', el - emitted after triggering the start of screen sharing

  • el the element that contains the local screen stream

'joinedRoom', roomName - emitted after successfully joining a room with the name roomName

'leftRoom', roomName - emitted after successfully leaving the current room, ending all peers, and stopping the local screen stream

'videoAdded', videoEl, peer - emitted when a peer stream is added

  • videoEl - the video element associated with the stream that was added
  • peer - the peer associated with the stream that was added

'videoRemoved', videoEl, peer - emitted when a peer stream is removed

  • videoEl - the video element associated with the stream that was removed
  • peer - the peer associated with the stream that was removed

Methods

createRoom(name, callback) - emits the create event on the connection with name and (if provided) invokes callback on response

joinRoom(name, callback) - joins the conference in room name. Callback is invoked with callback(err, roomDescription) where roomDescription is yielded by the connection on the join event. See signalmaster for more details.

startLocalVideo() - starts the local media with the media options provided in the config passed to the constructor

testReadiness() - tests that the connection is ready and that (if media is enabled) streams have started

mute() - mutes the local audio stream for all peers (pauses sending audio)

unmute() - unmutes local audio stream for all peers (resumes sending audio)

pauseVideo() - pauses sending video to peers

resumeVideo() - resumes sending video to all peers

pause() - pauses sending audio and video to all peers

resume() - resumes sending audio and video to all peers

sendToAll(messageType, payload) - broadcasts a message to all peers in the room via the signaling channel (websocket)

  • string messageType - the key for the type of message being sent
  • object payload - an arbitrary value or object to send to peers

sendDirectlyToAll(channelLabel, messageType, payload) - broadcasts a message to all peers in the room via a dataChannel

  • string channelLabel - the label for the dataChannel to send on
  • string messageType - the key for the type of message being sent
  • object payload - an arbitrary value or object to send to peers

getPeers(sessionId, type) - returns all peers by sessionId and/or type

shareScreen(callback) - initiates screen capture request to browser, then adds the stream to the conference

getLocalScreen() - returns the local screen stream

stopScreenShare() - stops the screen share stream and removes it from the room

stopLocalVideo() - stops all local media streams

setVolumeForAll(volume) - used to set the volume level for all peers

  • volume - the volume level, between 0 and 1

leaveRoom() - leaves the currently joined room and stops local screen share

disconnect() - calls disconnect on the signaling connection and deletes it

handlePeerStreamAdded(peer) - used internally to attach media stream to the DOM and perform other setup

handlePeerStreamRemoved(peer) - used internally to remove the video container from the DOM and emit videoRemoved

getDomId(peer) - used internally to get the DOM id associated with a peer

getEl(idOrEl) - helper used internally to get an element where idOrEl is either an element, or an id of an element

getLocalVideoContainer() - used internally to get the container that will hold the local video element

getRemoteVideoContainer() - used internally to get the container that holds the remote video elements

Connection

By default, SimpleWebRTC uses a socket.io connection to communicate with the signaling server. However, you can provide an alternate connection object to use. All that your alternate connection need provide are four methods:

  • on(ev, fn) - A method to invoke fn when event ev is triggered
  • emit() - A method to send/emit arbitrary arguments on the connection
  • getSessionId() - A method to get a unique session Id for the connection
  • disconnect() - A method to disconnect the connection

simplewebrtc's People

Contributors

aral avatar daniakash avatar davidbanham avatar fippo avatar gitter-badger avatar henrikjoreteg avatar ike avatar joelseq avatar johnmclear avatar lebovic avatar manubo avatar nghiattran avatar nlf avatar owenthereal avatar paulhovey avatar pdehaan avatar skade avatar sockdrawermoney avatar stpeter avatar tgabi333 avatar xdumaine avatar xenyou avatar zythyr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simplewebrtc's Issues

How to build latest.js?

Hi Henrik,

Thanks for SimpleWebRTC. I've been using the older version, before you split it into several modules. I'm finally trying to upgrade to the current release and things work if I use the latest.js you have checked in to github. I would like to build my own so I can set custom node and stun servers, but I'm having a hard time figuring out how to do that.

I'm far from an expert on browserify, but I've tried everything I can think of to get from your source to a working latest.js without any luck. I know I could just edit the minified latest.js, but I'd prefer to work with the original readable source. Can you help please?

Thanks again. I really appreciate all the work you've done.

Cheers,
--alex

Mute Video and Audio

Am trying to implement the audio and video mute using simplewebrtc. But am not able to get a handle of the localstream in the html to set tracks enable to true or false.
Dont think its a bug, most likely I am doing something wrong. Please guide.

Video Quality

2013-08-17 2 35 33
How to improve the remote video quality, I use the FaceTime HD Camera, the problem is still exists in the remote video, especially when objects quickly move, it happens only on server-side how to improve it?Thanks

using existing socket connection

I am using my own code on server side and therefore I do not need another socket connection inside simplewebrtc.

I could make a pull request but here is my plain code to support socket property in config object:

    if (this.config.socket) {
        connection = this.connection = this.config.socket;
        self.emit('ready', connection.socket.sessionid);
        self.sessionReady = true;
        self.testReadiness();        
    }
    else {
        connection = this.connection = io.connect(this.config.url);
        connection.on('connect', function () {
            self.emit('ready', connection.socket.sessionid);
            self.sessionReady = true;
            self.testReadiness();
        });
    }

Also it might be a better idea to rename all server events and add a prefix just like "WebRTC_join" instead of "join" for example. I am using simplewebrtc as part of a chat application so some event name might be already in use. Maybe that prefix could be set up in config as well.

better dokumentation

There's so little dokumentation on this project. example: "webrtc.joinRoom" is in the dokumentation but not "webrtc.leaveRoom" why is that?

Also, how do you end the local stream after leaving the room?

black screen instead of video

Hi,
I've implemented the simplewebrtc with a small adjustments like joining room without actually starting the audio/video, it looks great quality and speed are nothing less than amazing.

However, there is a problem in some computers/networks i can only see black video instead of the actual video. i made sure that before the stream received there is an offer and answer.
Is this something you noticed in the project or maybe it relates to auto room joining i've added?

BTW, i'm not sure if that is related i'm using my own turn server, but i saw the bug occurs on the google turn server as well.

Thanks in advance,
Tzahi

Video conferencing 5, 10, 15 people?

Hello guys,

Has anyone implemented a solution with multiple participants using simpleWebRTC and what was the experience like? I read it somewhere that if participants are more than 5 then WebRTC will not work and might need a "media server"! No idea what that means.

Any suggestion on implementing a group video chat for up to 10 people?

Thanks

Element type for remoteVideoEl must be <video>

When provided the localVideosEl the element can be a div or a video, and it does the right thing - however the remoteVideosEl can only be the ID of a video element. At least for me (OSX/FF or OSX/Chrome) everything appears to work but I get no video.

Suspect getRemoteVideoContainer should be a little closer in functionality to getLocalVideoContaine but is there something I'm missing? Happy to fix it in a PR if not.

"navigator is not defined"

Hello, I'm trying to launch it with node version 0.10.20 and get the following:

d:\www\hectorayestaran\lab\node.js\node_modules\webrtc\node_modules\webrtcsuppor
t\webrtcsupport.js:5
var ua = navigator.userAgent.toLowerCase();
^
ReferenceError: navigator is not defined
at Object. (d:\www\hectorayestaran\lab\node.js\node_modules\webrt
c\node_modules\webrtcsupport\webrtcsupport.js:5:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (d:\www\hectorayestaran\lab\node.js\node_modules\webrt
c\webrtc.js:1:76)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)

Any ideas?
Thanks so much.

Setup instructions missing video height...

Quick-start instructions on simplewebrtc.com are missing a critical piece in the template:

#remotesVideos video { height: 150px; }

Without this, the call is setup, but you can't see the remote video! ... Above CSS should either be baked into the template, or a height property should be specified by default by the library (in favor of second one).

None / Glitchy audio

I'm using the super simple code shown on simplewebrtc.io, and the audio doesn't work. Most of the time, I can't hear anything (I have 2 browser windows open). I got a few friends to open the same url as me and I could hear them but neither of them could hear me or each other. I also cannot hear myself on the demo webpage.

I'm using the latest chrome at the time of writing. (28.0.1500.95)

Not working with 3+ clients.

Hey,

if there is a 4th user trying to connect, he is not connectet to the conversation but there is an JS error:

"Uncaught Error: SyntaxError: DOM Exception 12
Conversation.handleMessage
(anonymous function)
EventEmitter.emit
SocketNamespace.onPacket
Socket.onPacket
Transport.onPacket
Transport.onData
websocket.onmessage
message.payload
Object
candidate: "a=candidate:2999745851 2 udp 2113937151 192.168.56.1 62137 typ host generation 0
โ†ต"
id: "audio"
label: 0
proto: Object "

Sometimes there is no error but he stucks at:

"setting remote description
answer called "

Private hosting or managed service

Hello,

I am not a developer and dare to ask a simple question. Can I install webrtc on AWS EC2? If yes then is there any documentation avaiable or simple guide?

or can it be hosted and managed by you guys? How much would it cost?

Thanks

Problems with enableDataChannels: true

When I set enableDataChannels to true (default) I can't use SimpleWebRTC in Chrome, and I get not speaking events.
When I set it manually to false, this problems don't occur!

Render videos onload

First of all I would like to thank the developers for creating SimpleWebRTC. It truly is simple.

I have an application which may result in users refreshing the page. In such an event, I would like the videos to be rendered on load (if there are any). Is there any way to currently do this?

Implementing "user is speaking events"

Hey @HenrikJoreteg et al.

I am working on implementing the sending of events between clients to indicate who is speaking. This would allow video switching/indicators like in google hangouts etc.

I have a first cut working (will get code up in a pull request soon), but there's still some work to do.

I have some questions/thoughts:

  • Should we be sending a polling event every n milliseconds when a user is speaking to indicate they are still speaking? Or should we just send an event when they start and another event when they finish? Any naming convention for these events that we prefer?
  • I should be emitting the events to all the peer connections right?
  • The code will need a volume_threshold to determine when a user is actually speaking, and some kind of a timeout to allow for brief pauses in speech without a speaking_finished being emitted. Should these numbers be configurable, or should we be opinionated about it.

Would love any thoughts/opinions :)

Phil

Problems behind firewall/proxy

Hi,

I just stumbled over talky.io, which works good behind our firewall.

I wanted to build a clone, but neither the code nor http://simplewebrtc.com/demo.html does display the video of the partner.

Are they doing someting special what is "missing" in SimpleWebRTC?

Greets, pattyland

Audio feedback from local video due to Chrome update + PATCH

Since the recent Chrome update that removed the default mute for local video SimpleWebRTC has been suffering from feedback.

This looks like it's known about:

We just discovered that http://conversat.io  was made very unhappy by 
a Chrome update that caused a crazy feedback loop. Now fixed!

But the patch has not filtered out into open source, so....

This patch fixes the issue by effectively muting the local stream locally (but not remotely as happens with mute). The net result is that things work as expected. YMMV but it works for me.

--- simplewebrtc.js 2013-06-27 20:31:00.000000000 +1000
+++ simplewebrtc.js.patched 2013-06-28 22:57:15.000000000 +1000
@@ -33,8 +33,9 @@
     getUserMedia = navigator.mozGetUserMedia.bind(navigator);

     // Attach a media stream to an element.
-    attachMediaStream = function(element, stream) {
+    attachMediaStream = function(element, stream, volume) {
         element.mozSrcObject = stream;
+        element.volume = volume;
         element.play();
     };

@@ -62,8 +63,9 @@
     getUserMedia = navigator.webkitGetUserMedia.bind(navigator);

     // Attach a media stream to an element.
-    attachMediaStream = function(element, stream) {
+    attachMediaStream = function(element, stream, volume) {
         element.autoplay = true;
+        element.volume = volume;
         element.src = webkitURL.createObjectURL(stream);
     };

@@ -368,7 +370,7 @@
 WebRTC.prototype.startLocalVideo = function (element) {
     var self = this;
     getUserMedia(this.config.media, function (stream) {
-        attachMediaStream(element || self.getLocalVideoContainer(), stream);
+        attachMediaStream(element || self.getLocalVideoContainer(), stream, 0.0 );
         self.localStream = stream;
         self.testReadiness();
     }, function () {
@@ -484,7 +486,7 @@
         el = document.createElement('video'),
         container = this.parent.getRemoteVideoContainer();
     el.id = this.id;
-    attachMediaStream(el, stream);
+    attachMediaStream(el, stream, 1.0);
     if (container) container.appendChild(el);
     this.emit('videoAdded', el);
 };

Need complete test suite

Will use QUnit. Will involve opening a page (or possibly just other connection on same page) to be the other peer to ensure proper testability.

can i use this without internet connection?

can you use this example on a local network without internet connection? I saw you need to have access to the STUN servers, but what exactly are they doing ... will it still work if i setup my own STUN server? I don't really know allot of this, but i'm looking into using it on a local network.

kind regards,
Daan

When detectSpeakingEvents enabled, reconnecting causes Audio error

To reproduce the issue:

  • have detectSpeakingEvents set to true
  • startLocalVideo then stopLocalVideo
  • startLocalVideo then stopLocalVideo
  • startLocalVideo
  • get error: Uncaught SyntaxError: audio resources unavailable for AudioContext construction

(it might take a different number of starting/stopping I suppose depending on the number of audio resources available for a particular computer).

The problem seems to be that Harker doesn't cleanly disconnect it's sourceNodes I believe. However, there's something else I'm missing because if I just do disconnect() on the nodes it still fails :-/

Thoughts?

NavigatorUserMediaError aborts connection

If the SimpleWebRTC Event "CONSTRAINT_NOT_SATISFIED: NavigatorUserMediaError" happens (e.g. the user has no webcam nor a microphone) no connection is established, although he could see other users in the room!

Add audio call only option

It would be cool to be able to only have audio call, it could be useful eg in cases where bandwidth is too low.

Uncaught ReferenceError: WebRTC is not defined

On the demo site and in my personal code, I get the above error when making the WebRTC object and the call doesn't start.

EDIT: Realized you renamed the class to SimpleWebRTC. You should probably update the demo...

Change STUN server to avoid problems cited in https://bugzilla.mozilla.org/show_bug.cgi?id=888274

The STUN server used by the SimpleWebRTC library is getting hit by the problems cited in https://bugzilla.mozilla.org/show_bug.cgi?id=888274 and the dupes of that bug. This results in call failures to occur for certain network configurations. This is due to the fact that the STUN server used is non-compliant.

The workaround to this problem is to change the STUN server used in this library to use a compliant STUN server. This line:

https://github.com/HenrikJoreteg/SimpleWebRTC/blob/master/simplewebrtc.bundle.js#L675

Needs to be modified to use a compliant STUN server.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.