Kurento
Kurento
Release 6.6.1
kurento.org
I Whats Kurento? 3
II Introducing Kurento 7
1 WebRTC media servers 9
IV Kurento Tutorials 27
7 Hello world 31
i
16 WebRTC incoming data channel 195
ii
Kurento Documentation, Release 6.6.1
Contents 1
Kurento Documentation, Release 6.6.1
2 Contents
Part I
Whats Kurento?
3
Kurento Documentation, Release 6.6.1
Kurento is a WebRTC media server and a set of client APIs making simple the development of advanced video
applications for WWW and smartphone platforms. Kurento features include group communications, transcoding,
recording, mixing, broadcasting and routing of audiovisual flows.
Kurento also provides advanced media processing capabilities involving computer vision, video indexing, augmented
reality and speech analysis. Kurento modular architecture makes simple the integration of third party media processing
algorithms (i.e. speech recognition, sentiment analysis, face recognition, etc.), which can be transparently used by
application developers as the rest of Kurento built-in features.
Kurentos core element is Kurento Media Server, responsible for media transmission, processing, loading and record-
ing. It is implemented in low level technologies based on GStreamer to optimize the resource consumption. It provides
the following features:
Networked streaming protocols, including HTTP, RTP and WebRTC.
Group communications (MCUs and SFUs functionality) supporting both media mixing and media rout-
ing/dispatching.
Generic support for computational vision and augmented reality filters.
Media storage supporting writing operations for WebM and MP4 and playing in all formats supported by
GStreamer.
Automatic media transcodification between any of the codecs supported by GStreamer including VP8, H.264,
H.263, AMR, OPUS, Speex, G.711, etc.
There are available Kurento Client libraries in Java and Javascript to control Kurento Media Server from applications.
If you prefer another programming language, you can use the Kurento Protocol, based on WebSocket and JSON-RPC.
Kurento is open source, released under the terms of Apache 2.0 license. Its source code is hosted on GitHub.
If you want to put your hands on quickly, the best way is installing the Kurento Media Server and take a look to
our tutorials in form of working demo applications. You can choose your favorite technology to build multimedia
applications: Java, Browser JavaScript or Node.js.
If you want to make the most of Kurento, please take a look to the advanced documentation.
5
Kurento Documentation, Release 6.6.1
6
Part II
Introducing Kurento
7
CHAPTER 1
WebRTC is an open source technology that enables web browsers with Real-Time Communications (RTC) capabilities
via JavaScript APIs. It has been conceived as a peer-to-peer technology where browsers can directly communicate
without the mediation of any kind of infrastructure. This model is enough for creating basic applications but features
such as group communications, media stream recording, media broadcasting or media transcoding are difficult to
implement on top of it. For this reason, many applications require using a media server.
Fig. 1.1: Peer-to-peer WebRTC approach vs. WebRTC through a media server
Conceptually, a WebRTC media server is just a kind of multimedia middleware (it is in the middle of the commu-
nicating peers) where media traffic pass through when moving from source to destinations. Media servers are capable
of processing media streams and offering different types including groups communications (distributing the media
stream one peer generates among several receivers, i.e. acting as Multi-Conference Unit, MCU), mixing (transform-
ing several incoming stream into one single composite stream), transcoding (adapting codecs and formats between
incompatible clients), recording (storing in a persistent way the media exchanged among peers), etc.
9
Kurento Documentation, Release 6.6.1
At the heart of the Kurento architecture there is a media server called the Kurento Media Server (KMS). Kurento
Media Server is based on pluggable media processing capabilities meaning that any of its provided features is a
pluggable module that can be activated or deactivated. Moreover, developers can seamlessly create additional modules
extending Kurento Media Server with new functionalities which can be plugged dynamically.
Kurento Media Server provides, out of the box, group communications, mixing, transcoding, recording and playing.
In addition, it also provides advanced modules for media processing including computer vision, augmented reality,
alpha blending and much more.
11
Kurento Documentation, Release 6.6.1
Kurento Media Server capabilities are exposed by the Kurento API to application developers. This API is im-
plemented by means of libraries called Kurento Clients. Kurento offers two clients out of the box for Java and
JavaScript. If you have another favorite language, you can still use Kurento using directly the Kurento Protocol.
This protocol allows to control Kurento Media Server and it is based on Internet standards such as WebSocket and
JSON-RPC. The picture below shows how to use Kurento Clients in three scenarios:
Using the Kurento JavaScript Client directly in a compliant WebRTC browser
Using the Kurento Java Client in a Java EE Application Server
Using the Kurento JavaScript Client in a Node.js server
Complete examples for these three technologies is described in the tutorials section.
Kurento Clients API is based on the concept of Media Element. A Media Element holds a specific media capability.
For example, the media element called WebRtcEndpoint holds the capability of sending and receiving WebRTC media
streams, the media element called RecorderEndpoint has the capability of recording into the file system any media
streams it receives, the FaceOverlayFilter detects faces on the exchanged video streams and adds a specific overlaid
image on top of them, etc. Kurento exposes a rich toolbox of media elements as part of its APIs.
To better understand theses concepts it is recommended to take a look to Kurento API and Kurento Protocol sections.
You can also take a loot to the JavaDoc and JsDoc:
kurento-client-java : JavaDoc of Kurento Java Client.
kurento-client-js : JsDoc of Kurento JavaScript Client.
kurento-utils-js : JsDoc of an utility JavaScript library aimed to simplify the development of WebRTC applica-
tions.
13
Kurento Documentation, Release 6.6.1
Fig. 3.1: Connection of Kurento Clients (Java and JavaScript) to Kuento Media Server
Fig. 3.2: Some Media Elements provided out of the box by Kurento
15
Kurento Documentation, Release 6.6.1
From the application developer perspective, Media Elements are like Lego pieces: you just need to take the elements
needed for an application and connect them following the desired topology. In Kurento jargon, a graph of connected
media elements is called a Media Pipeline. Hence, when creating a pipeline, developers need to determine the capa-
bilities they want to use (the media elements) and the topology determining which media elements provide media to
which other media elements (the connectivity). The connectivity is controlled through the connect primitive, exposed
on all Kurento Client APIs. This primitive is always invoked in the element acting as source and takes as argument the
sink element following this scheme:
sourceMediaElement.connect(sinkMediaElement)
For example, if you want to create an application recording WebRTC streams into the file system, youll need two
media elements: WebRtcEndpoint and RecorderEndpoint. When a client connects to the application, you will need to
instantiate these media elements making the stream received by the WebRtcEndpoint (which is capable of receiving
WebRTC streams) to be feed to the RecorderEndpoint (which is capable of recording media streams into the file
system). Finally you will need to connect them so that the stream received by the former is fed into the later:
WebRtcEndpoint.connect(RecorderEndpoint)
To simplify the handling of WebRTC streams in the client-side, Kurento provides an utility called WebRtcPeer. Nev-
ertheless, the standard WebRTC API (getUserMedia, RTCPeerConnection, and so on) can also be used to connect to
WebRtcEndpoints. For further information please visit the tutorials section.
17
Kurento Documentation, Release 6.6.1
19
Kurento Documentation, Release 6.6.1
Kurento Media Server (KMS) has to be installed on Ubuntu 14.04 LTS (64 bits).
In order to install the latest stable Kurento Media Server version (6.6.1) you have to type the following commands,
one at a time and in the same order as listed here. When asked for any kind of confirmation, reply affirmatively:
Now, Kurento Media Server has been installed. Use the following commands to start and stop it respectively:
21
Kurento Documentation, Release 6.6.1
22
CHAPTER 5
The current stable version of Kurento Media Server uses the Trickle ICE protocol for WebRTC connections. Trickle
ICE is the name given to the extension to the Interactive Connectivity Establishment (ICE) protocol that allows ICE
agents (in this case Kurento Media Server and Kurento Client) to send and receive candidates incrementally rather
than exchanging complete lists. In short, Trickle ICE allows to begin WebRTC connectivity much more faster.
This feature makes the Kurento Media Server 6 incompatible with the former versions. If you are using Kurento
Media Server 5.1 or lower, it is strongly recommended to upgrade your KMS. To do that, first you need to uninstall
KMS as follows:
Finally, the references to the Kurento Media Server in the APT sources should be removed:
After that, install Kurento Media Server 6 as depicted at the top of this page.
23
Kurento Documentation, Release 6.6.1
If Kurento Media Server is located behind a NAT you need to use a STUN or TURN in order to achieve NAT traversal.
In most of cases, a STUN server will do the trick. A TURN server is only necessary when the NAT is symmetric.
In order to setup a STUN server you should uncomment the following lines in the Kurento Media Server configuration
file located on at /etc/kurento/modules/kurento/WebRtcEndpoint.conf.ini:
stunServerAddress=<stun_ip_address>
stunServerPort=<stun_port>
Note: Be careful since comments inline (with ;) are not allowed for parameter such as stunServerAddress.
Thus, the following configuration is not correct:
stunServerAddress=<stun_ip_address> ; Only IP address are supported
The parameter stunServerAddress should be an IP address (not domain name). There is plenty of public STUN
servers available, for example:
173.194.66.127:19302
173.194.71.127:19302
74.125.200.127:19302
74.125.204.127:19302
173.194.72.127:19302
74.125.23.127:3478
77.72.174.163:3478
77.72.174.165:3478
77.72.174.167:3478
77.72.174.161:3478
208.97.25.20:3478
62.71.2.168:3478
25
Kurento Documentation, Release 6.6.1
212.227.67.194:3478
212.227.67.195:3478
107.23.150.92:3478
77.72.169.155:3478
77.72.169.156:3478
77.72.169.164:3478
77.72.169.166:3478
77.72.174.162:3478
77.72.174.164:3478
77.72.174.166:3478
77.72.174.160:3478
54.172.47.69:3478
In order to setup a TURN server you should uncomment the following lines in the Kurento Media Server configuration
file located on at /etc/kurento/modules/kurento/WebRtcEndpoint.conf.ini:
turnURL=user:password@address:port;
As before, TURN address should be an IP address (not domain name). See some examples of TURN configuration
below:
turnURL=kurento:[email protected]:3478;
turnURL=user:[email protected]:3478;
An open source implementation of a TURN server is coturn. In the FAQ section there is description about how to
install a coturn server.
Kurento Tutorials
27
Kurento Documentation, Release 6.6.1
This section contains tutorials showing how to use Kurento framework to build different types of WebRTC and multi-
media applications. Tutorials come in three flavors:
Java: These show applications where clients interact with Spring-Boot based application, that host the logic
orchestrating the communication among clients and controlling Kurento Media Server capabilities.
Browser JavaScript: These show applications executing at the browser and communicating directly with the
Kurento Media Server. In these tutorial all logic is directly hosted by browser. Hence, no application server is
necessary.
Node.js: These show applications where clients interact with an application server based on Node.js technol-
ogy. The application server holds the logic orchestrating the communication among the clients and controlling
Kurento Media Server capabilities for them.
Note: The tutorials have been created with learning objectives. They are not intended to be used in production
environments where different unmanaged error conditions may emerge. Use at your own risk!
Note: These tutorials require https in order to use WebRTC. Following instructions will provided further information
about how to enable application security.
29
Kurento Documentation, Release 6.6.1
30
CHAPTER 7
Hello world
This is one of the simplest WebRTC applications you can create with Kurento. It implements a WebRTC loopback (a
WebRTC media stream going from client to Kurento and back to the client)
This web application has been designed to introduce the principles of programming with Kurento for Java developers.
It consists on a WebRTC video communication in mirror (loopback). This tutorial assumes you have basic knowledge
of JavaScript, HTML and WebRTC. We also recommend reading the Introducing Kurento section before starting this
tutorial.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
You need to have installed the Kurento Media Server before running this example. Read the installation guide for
further information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
31
Kurento Documentation, Release 6.6.1
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
Kurento provides developers a Kurento Java Client to control the Kurento Media Server. This client library can be
used in any kind of Java application: Server Side Web, Desktop, Android, etc. It is compatible with any framework
like Java EE, Spring, Play, Vert.x, Swing and JavaFX.
This hello world demo is one of the simplest web applications you can create with Kurento. The following picture
shows a screenshot of this demo running:
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one showing the local
stream (as captured by the device webcam) and the other showing the remote stream sent by the media server back to
the client.
The logic of the application is quite simple: the local stream is sent to the Kurento Media Server, which sends it back
to the client without modifications. To implement this behavior, we need to create a Media Pipeline composed by a
single Media Element, i.e. a WebRtcEndpoint, which holds the capability of exchanging full-duplex (bidirectional)
WebRTC media flows. This media element is connected to itself so that the media it receives (from browser) is sent
back (to browser). This media pipeline is illustrated in the following picture:
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side, we use a Spring-Boot based server application consuming the Kurento
Java Client API, to control Kurento Media Server capabilities. All in all, the high level architecture of this demo
is three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client
and application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the
communication between the Kurento Java Client and the Kurento Media Server. This communication takes place
using the Kurento Protocol. For further information on it, please see this page of the documentation.
The diagram below shows a complete sequence diagram, of the interactions with the application interface to: i)
JavaScript logic; ii) Application server logic (which uses the Kurento Java Client); iii) Kurento Media Server.
The following sections analyze in depth the server (Java) and client-side (JavaScript) code of this application. The
complete source code can be found in GitHub.
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vert.x, etc. Here we chose Spring Boot for convenience.
In the following, figure you can see a class diagram of the server side code:
The main class of this demo is HelloWorldApp. As you can see, the KurentoClient is instantiated in this class as a
Spring Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities to the
application. In this instantiation we see that we need to specify to the client library the location of the Kurento Media
Server. In this example, we assume it is located at localhost, listening in port 8888. If you reproduce this example,
youll need to insert the specific location of your Kurento Media Server instance there.
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server and
controlling its multimedia capabilities.
@EnableWebSocket
@SpringBootApplication
public class HelloWorldApp implements WebSocketConfigurer {
@Bean
public HelloWorldHandler handler() {
return new HelloWorldHandler();
}
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler(), "/helloworld");
}
}
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with application server by means of requests and responses. Specifically, the main app class implements the
interface WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path
/helloworld.
HelloWorldHandler class implements TextWebSocketHandler to handle text WebSocket requests. The central
piece of this class is the method handleTextMessage. This method implements the actions for requests, returning
responses through the WebSocket. In other words, it implements the server part of the signaling protocol depicted in
the previous sequence diagram.
public class HelloWorldHandler extends TextWebSocketHandler {
@Autowired
private KurentoClient kurento;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
switch (jsonMessage.get("id").getAsString()) {
case "start":
start(session, jsonMessage);
break;
case "stop": {
UserSession user = users.remove(session.getId());
if (user != null) {
user.release();
}
break;
}
case "onIceCandidate": {
JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject();
jsonCandidate.get("sdpMid").getAsString(), jsonCandidate.get(
"sdpMLineIndex").getAsInt());
user.addCandidate(candidate);
}
break;
}
default:
sendError(session, "Invalid message with id " + jsonMessage.get("id").
getAsString());
break;
}
}
// 3. SDP negotiation
String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.
getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
});
webRtcEndpoint.gatherCandidates();
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
response.addProperty("message", message);
session.sendMessage(new TextMessage(response.toString()));
} catch (IOException e) {
log.error("Exception sending message", e);
}
}
}
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we can see
the creation of the WebSocket (variable ws) in the path /helloworld. Then, the onmessage listener of the Web-
Socket is used to implement the JSON signaling protocol in the client-side. Notice that there are three incoming mes-
sages to client: startResponse, error, and iceCandidate. Convenient actions are taken to implement each
step in the communication. For example, in functions start the function WebRtcPeer.WebRtcPeerSendrecv
of kurento-utils.js is used to start a WebRTC communication.
var ws = new WebSocket('ws://' + location.host + '/helloworld');
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'error':
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
function start() {
console.log('Starting video call ...');
var options = {
localVideo : videoInput,
remoteVideo : videoOutput,
onicecandidate : onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function(error) {
if (error)
return console.error(error);
webRtcPeer.generateOffer(onOffer);
});
}
function onIceCandidate(candidate) {
console.log('Local candidate' + JSON.stringify(candidate));
var message = {
id : 'onIceCandidate',
candidate : candidate
};
sendMessage(message);
}
function startResponse(message) {
setState(I_CAN_STOP);
console.log('SDP answer received from server. Processing ...');
webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
if (error)
return console.error(error);
});
}
function stop() {
console.log('Stopping video call ...');
setState(I_CAN_START);
if (webRtcPeer) {
webRtcPeer.dispose();
webRtcPeer = null;
var message = {
id : 'stop'
}
sendMessage(message);
}
hideSpinner(videoInput, videoOutput);
}
function sendMessage(message) {
var jsonMessage = JSON.stringify(message);
console.log('Senging message: ' + jsonMessage);
ws.send(jsonMessage);
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This web application has been designed to introduce the principles of programming with Kurento for JavaScript
developers. It consists on a WebRTC video communication in mirror (loopback). This tutorial assumes you have basic
knowledge of JavaScript, HTML and WebRTC. We also recommend reading the Introducing Kurento section before
starting this tutorial.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
Youll need to install Kurento Media Server before running this example. Read installation guide for further informa-
tion.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
Due to Same-origin policy, this demo has to be served by a HTTP server. A very simple way of doing this is by means
of an HTTP Node.js server which can be installed using npm :
You also need the source code of this demo. You can clone it from GitHub. Then start the HTTP server:
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the parameter ws_uri to the
URL, as follows:
https://localhost:8443/index.html?ws_uri=wss://kms_host:kms_port/kurento
Notice that the Kurento Media Server must connected using a Secure WebSocket (i.e., the KMS URI starts with
wss:// ). For this reason, the support for secure WebSocket must be enabled in the Kurento Media Server you are using
to run this tutorial. For further information about securing applications, please visit the following page.
Kurento provides developers a Kurento JavaScript Client to control Kurento Media Server. This client library can
be used in any kind of JavaScript application including desktop and mobile browsers.
This hello world demo is one of the simplest web applications you can create with Kurento. The following picture
shows an screenshot of this demo running:
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one showing the local
stream (as captured by the device webcam) and the other showing the remote stream sent by the media server back to
the client.
The logic of the application is quite simple: the local stream is sent to the Kurento Media Server, which sends it back
to the client without modifications. To implement this behavior, we need to create a Media Pipeline composed by a
single Media Element, i.e. a WebRtcEndpoint, which holds the capability of exchanging full-duplex (bidirectional)
WebRTC media flows. This media element is connected to itself so that the media it receives (from browser) is send
back (to browser). This media pipeline is illustrated in the following picture:
This is a web application, and therefore it follows a client-server architecture. Nevertheless, due to the fact that we
are using the Kurento JavaScript client, there is not need to use an application server since all the application logic is
held by the browser. The Kurento JavaScript Client is used directly to control Kurento Media Server by means of a
WebSocket bidirectional connection:
The following sections analyze in deep the client-side (JavaScript) code of this application, the dependencies, and how
to run the demo. The complete source code can be found in GitHub.
JavaScript Logic
The Kurento hello-world demo follows a Single Page Application architecture (SPA). The interface is the following
HTML page: index.html. This web page links two Kurento JavaScript libraries:
startButton.addEventListener("click", function() {
var options = {
localVideo: videoInput,
remoteVideo: videoOutput
};
[...]
}
The function WebRtcPeer.WebRtcPeerSendrecv abstracts the WebRTC internal details (i.e. PeerConnection and ge-
tUserStream) and makes possible to start a full-duplex WebRTC communication, using the HTML video tag with id
videoInput to show the video camera (local stream) and the video tag videoOutput to show the remote stream provided
by the Kurento Media Server.
Inside this function, a call to generateOffer is performed. This function accepts a callback in which the SDP offer is
received. In this callback we create an instance of the KurentoClient class that will manage communications with the
Kurento Media Server. So, we need to provide the URI of its WebSocket endpoint. In this example, we assume its
listening in port 8888 at the same host than the HTTP serving the application.
[...]
[...]
If everything works correctly, we will have an instance of a media pipeline (variable _pipeline in this example).
With it, we are able to create Media Elements. In this example we just need a single WebRtcEndpoint.
In WebRTC, SDP is used for negotiating media exchanges between applications. Such negotiation happens based on
the SDP offer and answer exchange mechanism by gathering the ICE candidates as follows:
pipeline = _pipeline;
webRtcPeer.processAnswer(sdpAnswer, onError);
});
webRtc.gatherCandidates(onError);
[...]
});
webRtc.connect(webRtc, function(error){
if(error) return onError(error);
console.log("Loopback established");
});
Note: The TURN and STUN servers to be used can be configured simple adding the parameter ice_servers to
the application URL, as follows:
https://localhost:8443/index.html?ice_servers=[{"urls":"stun:stun1.example.net"},{
"urls":"stun:stun2.example.net"}]
https://localhost:8443/index.html?ice_servers=[{"urls":"turn:turn.example.org",
"username":"user","credential":"myPassword"}]
Dependencies
All dependencies of this demo can to be obtained using Bower. The list of these dependencies are defined in the
bower.json file, as follows:
"dependencies": {
"kurento-client": "6.6.0",
"kurento-utils": "6.6.2"
}
bower install
Note: We are in active development. You can find the latest version of Kurento JavaScript Client at Bower.
This web application has been designed to introduce the principles of programming with Kurento for Node.js devel-
opers. It consists on a WebRTC video communication in mirror (loopback). This tutorial assumes you have basic
knowledge of JavaScript, Node.js, HTML and WebRTC. We also recommend reading the Introducing Kurento section
before starting this tutorial.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
You need to have installed the Kurento Media Server before running this example. Read the installation guide for
further information.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
To launch the application, you need to clone the GitHub project where this demo is hosted, install it and run it:
If you have problems installing any of the dependencies, please remove them and clean the npm cache, and try to
install them again:
rm -r node_modules
npm cache clean
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the argument ws_uri to the
npm execution command, as follows:
In this case you need to use npm version 2. To update it you can use this command:
Kurento provides developers a Kurento JavaScript Client to control Kurento Media Server. This client library can
be used from compatible JavaScript engines including browsers and Node.js.
This hello world demo is one of the simplest web application you can create with Kurento. The following picture
shows an screenshot of this demo running:
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one showing the local
stream (as captured by the device webcam) and the other showing the remote stream sent by the media server back to
the client.
The logic of the application is quite simple: the local stream is sent to the Kurento Media Server, which returns it back
to the client without modifications. To implement this behavior we need to create a Media Pipeline composed by a
single Media Element, i.e. a WebRtcEndpoint, which holds the capability of exchanging full-duplex (bidirectional)
WebRTC media flows. This media element is connected to itself so that the media it receives (from browser) is send
back (to browser). This media pipeline is illustrated in the following picture:
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side we use a Node.js application server consuming the Kurento JavaScript
Client API to control Kurento Media Server capabilities. All in all, the high level architecture of this demo is
three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client and
application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the com-
munication between the Kurento Java Client and the Kurento Media Server. This communication takes place using
the Kurento Protocol. For further information on it, please see this page of the documentation.
The diagram below shows an complete sequence diagram from the interactions with the application interface to: i)
JavaScript logic; ii) Application server logic (which uses the Kurento JavaScript Client); iii) Kurento Media Server.
The following sections analyze in deep the server and client-side code of this application. The complete source code
can be found in GitHub.
This demo has been developed using the express framework for Node.js, but express is not a requirement for Kurento.
The main script of this demo is server.js.
In order to communicate the JavaScript client and the Node application server a WebSocket is used. The incoming
messages to this WebSocket (variable ws in the code) are conveniently handled to implemented the signaling protocol
depicted in the figure before (i.e. messages start, stop, onIceCandidate).
var ws = require('ws');
[...]
/*
* Management of WebSocket messages
*/
wss.on('connection', function(ws) {
ws.on('error', function(error) {
console.log('Connection ' + sessionId + ' error');
stop(sessionId);
});
ws.on('close', function() {
console.log('Connection ' + sessionId + ' closed');
stop(sessionId);
});
ws.on('message', function(_message) {
var message = JSON.parse(_message);
console.log('Connection ' + sessionId + ' received message ', message);
switch (message.id) {
case 'start':
sessionId = request.session.id;
start(sessionId, ws, message.sdpOffer, function(error, sdpAnswer) {
if (error) {
return ws.send(JSON.stringify({
id : 'error',
message : error
}));
}
ws.send(JSON.stringify({
id : 'startResponse',
sdpAnswer : sdpAnswer
}));
});
break;
case 'stop':
stop(sessionId);
break;
case 'onIceCandidate':
onIceCandidate(sessionId, message.candidate);
break;
default:
ws.send(JSON.stringify({
id : 'error',
message : 'Invalid message ' + message
}));
break;
}
});
});
In order to control the media capabilities provided by the Kurento Media Server, we need an instance of the Kuren-
toClient in the Node application server. In order to create this instance, we need to specify to the client library the
location of the Kurento Media Server. In this example, we assume its located at localhost listening in port 8888.
[...]
function getKurentoClient(callback) {
if (kurentoClient !== null) {
return callback(null, kurentoClient);
}
kurentoClient = _kurentoClient;
callback(null, kurentoClient);
});
}
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server. Our first
operation is to create a Media Pipeline, then we need to create the Media Elements and connect them. In this example,
we just need a single WebRtcEndpoint connected to itself (i.e. in loopback). These functions are called in the start
function, which is fired when the start message is received:
getKurentoClient(function(error, kurentoClient) {
if (error) {
return callback(error);
}
if (candidatesQueue[sessionId]) {
while(candidatesQueue[sessionId].length) {
var candidate = candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
connectMediaElements(webRtcEndpoint, function(error) {
if (error) {
pipeline.release();
return callback(error);
}
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.
candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
sessions[sessionId] = {
'pipeline' : pipeline,
'webRtcEndpoint' : webRtcEndpoint
}
return callback(null, sdpAnswer);
});
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
return callback(error);
}
});
});
});
});
});
}
As of Kurento Media Server 6.0, the WebRTC negotiation is done by exchanging ICE candidates between the WebRTC
peers. To implement this protocol, the webRtcEndpoint receives candidates from the client in OnIceCandidate
function. These candidates are stored in a queue when the webRtcEndpoint is not available yet. Then these
candidates are added to the media element by calling to the addIceCandidate method.
[...]
if (sessions[sessionId]) {
console.info('Sending candidate');
var webRtcEndpoint = sessions[sessionId].webRtcEndpoint;
webRtcEndpoint.addIceCandidate(candidate);
}
else {
console.info('Queueing candidate');
if (!candidatesQueue[sessionId]) {
candidatesQueue[sessionId] = [];
}
candidatesQueue[sessionId].push(candidate);
}
}
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js to
simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript WebRTC
utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this appli-
cation. These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet
we can see the creation of the WebSocket (variable ws) in the path /helloworld. Then, the onmessage listener
of the WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there are three
incoming messages to client: startResponse, error, and iceCandidate. Convenient actions are taken to
implement each step in the communication.
const I_CAN_START = 0;
const I_CAN_STOP = 1;
const I_AM_STARTING = 2;
[...]
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'error':
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Error message from server: ' + parsedMessage.message);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate)
break;
default:
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Unrecognized message', parsedMessage);
}
}
In the function start the method WebRtcPeer.WebRtcPeerSendrecv of kurento-utils.js is used to create the
webRtcPeer object, which is used to handle the WebRTC communication.
videoInput = document.getElementById('videoInput');
videoOutput = document.getElementById('videoOutput');
[...]
function start() {
console.log('Starting video call ...')
var options = {
localVideo: videoInput,
remoteVideo: videoOutput,
onicecandidate : onIceCandidate
}
function onIceCandidate(candidate) {
console.log('Local candidate' + JSON.stringify(candidate));
var message = {
id : 'onIceCandidate',
candidate : candidate
};
sendMessage(message);
}
Dependencies
Server-side dependencies of this demo are managed using npm. Our main dependency is the Kurento Client JavaScript
(kurento-client). The relevant part of the package.json file for managing this dependency is:
"dependencies": {
[...]
"kurento-client" : "6.6.0"
}
At the client side, dependencies are managed using Bower. Take a look to the bower.json file and pay attention to the
following section:
"dependencies": {
[...]
"kurento-utils" : "6.6.2"
}
Note: We are in active development. You can find the latest version of Kurento JavaScript Client at npm and Bower.
This web application consists on a WebRTC video communication in loopback, adding a funny hat over detected faces.
This is an example of a computer vision and augmented reality filter.
This web application extends the Hello World Tutorial, adding media processing to the basic WebRTC loopback.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
The web application starts on port 8443 in the localhost by default. Therefore, open the URL https://localhost:8443/
in a WebRTC compliant browser (Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
59
Kurento Documentation, Release 6.6.1
This application uses computer vision and augmented reality techniques to add a funny hat on top of faces. The
following picture shows a screenshot of the demo running in a web browser:
Fig. 8.1: Kurento Magic Mirror Screenshot: WebRTC with filter in loopback
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
WebRtcEndpoint: Provides full-duplex (bidirectional) WebRTC capabilities.
FaceOverlay filter: Computer vision filter that detects faces in the video stream and puts an image on top of
them. In this demo the filter is configured to put a Super Mario hat).
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is im-
plemented in JavaScript. At the client-side, the logic is implemented in JavaScript. At the server-side, we use a
Spring-Boot based server application consuming the Kurento Java Client API, to control Kurento Media Server
capabilities. All in all, the high level architecture of this demo is three-tier. To communicate these entities, two Web-
Sockets are used. First, a WebSocket is created between client and application server to implement a custom signaling
protocol. Second, another WebSocket is used to perform the communication between the Kurento Java Client and the
Kurento Media Server. This communication takes place using the Kurento Protocol. For further information on it,
please see this page of the documentation.
To communicate the client with the Java EE application server we have designed a simple signaling protocol based on
JSON messages over WebSocket s. The normal sequence between client and server is as follows: i) Client starts the
Magic Mirror. ii) Client stops the Magic Mirror.
If any exception happens, server sends an error message to the client. The detailed message sequence between client
and application server is depicted in the following picture:
As you can see in the diagram, an SDP and ICE candidates needs to be exchanged between client and server to
establish the WebRTC session between the Kurento client and server. Specifically, the SDP negotiation connects the
WebRtcPeer at the browser with the WebRtcEndpoint at the server. The complete source code of this demo can be
found in GitHub.
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vert.x, etc. Here we chose Spring Boot for convenience.
In the following figure you can see a class diagram of the server side code:
The main class of this demo is named MagicMirrorApp. As you can see, the KurentoClient is instantiated in this class
as a Spring Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities to
your applications. In this instantiation we see that we need to specify to the client library the location of the Kurento
Media Server. In this example, we assume it is located at localhost, listening in port 8888. If you reproduce this
tutorial, youll need to insert the specific location of your Kurento Media Server instance there.
@EnableWebSocket
@SpringBootApplication
public class MagicMirrorApp implements WebSocketConfigurer {
@Bean
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler(), "/magicmirror");
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with application server by means of requests and responses. Specifically, the main app class implements the
interface WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path
/magicmirror.
MagicMirrorHandler class implements TextWebSocketHandler to handle text WebSocket requests. The central
piece of this class is the method handleTextMessage. This method implements the actions for requests, returning
responses through the WebSocket. In other words, it implements the server part of the signaling protocol depicted in
the previous sequence diagram.
In the designed protocol there are three different kinds of incoming messages to the Server : start, stop and
onIceCandidates. These messages are treated in the switch clause, taking the proper steps in each case.
@Autowired
private KurentoClient kurento;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
switch (jsonMessage.get("id").getAsString()) {
case "start":
start(session, jsonMessage);
break;
case "stop": {
UserSession user = users.remove(session.getId());
if (user != null) {
user.release();
}
break;
}
case "onIceCandidate": {
JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject();
jsonCandidate.get("sdpMid").getAsString(), jsonCandidate.get(
"sdpMLineIndex").getAsInt());
user.addCandidate(candidate);
}
break;
}
default:
sendError(session, "Invalid message with id " + jsonMessage.get("id").
getAsString());
break;
}
}
In the following snippet, we can see the start method. It handles the ICE candidates gathering, creates a Media
Pipeline, creates the Media Elements (WebRtcEndpoint and FaceOverlayFilter) and make the connections
among them. A startResponse message is sent back to the client with the SDP answer.
// ICE candidates
webRtcEndpoint.addIceCandidateFoundListener(new EventListener
<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
// Media logic
FaceOverlayFilter faceOverlayFilter = new FaceOverlayFilter.Builder(pipeline).
build();
webRtcEndpoint.connect(faceOverlayFilter);
faceOverlayFilter.connect(webRtcEndpoint);
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
webRtcEndpoint.gatherCandidates();
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
Note: Notice the hat URL is provided by the application server and consumed by the KMS. This logic is assuming
that the application server is hosted in local (localhost), and by the default the hat URL is https://localhost:8443/img/
mario-wings.png. If your application server is hosted in a different host, it can be easily changed by means of the
configuration parameter app.server.url, for example:
The sendError method is quite simple: it sends an error message to the client when an exception is caught in the
server-side.
Client-Side
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we can see
the creation of the WebSocket (variable ws) in the path /magicmirror. Then, the onmessage listener of the Web-
Socket is used to implement the JSON signaling protocol in the client-side. Notice that there are three incoming mes-
sages to client: startResponse, error, and iceCandidate. Convenient actions are taken to implement each
step in the communication. For example, in functions start the function WebRtcPeer.WebRtcPeerSendrecv
of kurento-utils.js is used to start a WebRTC communication.
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'error':
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError("Error message from server: " + parsedMessage.message);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {
if (error) {
console.error("Error adding candidate: " + error);
return;
}
});
break;
default:
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Unrecognized message', parsedMessage);
}
}
function start() {
console.log("Starting video call ...")
// Disable start button
setState(I_AM_STARTING);
showSpinner(videoInput, videoOutput);
var options = {
localVideo: videoInput,
remoteVideo: videoOutput,
onicecandidate: onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function (error) {
if (error) {
return console.error(error);
}
webRtcPeer.generateOffer(onOffer);
});
}
function onOffer(offerSdp) {
console.info('Invoking SDP offer callback function ' + location.host);
var message = {
id : 'start',
sdpOffer : offerSdp
}
sendMessage(message);
}
function onIceCandidate(candidate) {
console.log("Local candidate" + JSON.stringify(candidate));
var message = {
id: 'onIceCandidate',
candidate: candidate
};
sendMessage(message);
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This web application extends the Hello World Tutorial, adding media processing to the basic WebRTC loopback.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
Youll need to install Kurento Media Server before running this example. Read installation guide for further informa-
tion.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
Due to Same-origin policy, this demo has to be served by an HTTP server. A very simple way of doing this is by
means of an HTTP Node.js server which can be installed using npm :
You also need the source code of this demo. You can clone it from GitHub. Then start the HTTP server:
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
Kurento Media Server must use WebSockets over SSL/TLS (WSS), so make sure you check this too. It is possible to
locate the KMS in other machine simple adding the parameter ws_uri to the URL:
https://localhost:8443/index.html?ws_uri=wss://kms_host:kms_port/kurento
Notice that the Kurento Media Server must connected using a Secure WebSocket (i.e., the KMS URI starts with
wss:// ). For this reason, the support for secure WebSocket must be enabled in the Kurento Media Server you are using
to run this tutorial. For further information about securing applications, please visit the following page.
This application uses computer vision and augmented reality techniques to add a funny hat on top of detected faces.
The following picture shows a screenshot of the demo running in a web browser:
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to the Kurento Media Server, processed and then is returned to the client as a remote stream.
Fig. 8.5: Kurento Magic Mirror Screenshot: WebRTC with filter in loopback
To implement this, we need to create a Media Pipeline composed by the following Media Element s:
WebRtcEndpoint: Provides full-duplex (bidirectional) WebRTC capabilities.
FaceOverlay filter: Computer vision filter that detects faces in the video stream and puts an image on top of
them. In this demo the filter is configured to put a Super Mario hat).
The media pipeline implemented is illustrated in the following picture:
JavaScript Logic
This demo follows a Single Page Application architecture (SPA). The interface is the following HTML page: in-
dex.html. This web page links two Kurento JavaScript libraries:
kurento-client.js : Implementation of the Kurento JavaScript Client.
kurento-utils.js : Kurento utility library aimed to simplify the WebRTC management in the browser.
In addition, these two JavaScript libraries are also required:
Bootstrap : Web framework for developing responsive web sites.
jquery.js : Cross-platform JavaScript library designed to simplify the client-side scripting of HTML.
adapter.js : WebRTC JavaScript utility library maintained by Google that abstracts away browser differences.
ekko-lightbox : Module for Bootstrap to open modal images, videos, and galleries.
demo-console : Custom JavaScript console.
The specific logic of this demo is coded in the following JavaScript page: index.js. In this file, there is a function
which is called when the green button labeled as Start in the GUI is clicked.
var startButton = document.getElementById("start");
startButton.addEventListener("click", function() {
var options = {
localVideo: videoInput,
remoteVideo: videoOutput
};
[...]
}
The function WebRtcPeer.WebRtcPeerSendrecv abstracts the WebRTC internal details (i.e. PeerConnection and ge-
tUserStream) and makes possible to start a full-duplex WebRTC communication, using the HTML video tag with id
videoInput to show the video camera (local stream) and the video tag videoOutput to show the remote stream provided
by the Kurento Media Server.
Inside this function, a call to generateOffer is performed. This function accepts a callback in which the SDP offer is
received. In this callback we create an instance of the KurentoClient class that will manage communications with the
Kurento Media Server. So, we need to provide the URI of its WebSocket endpoint. In this example, we assume its
listening in port 8888 at the same host than the HTTP serving the application.
[...]
[...]
Once we have an instance of kurentoClient, the following step is to create a Media Pipeline, as follows:
client.create("MediaPipeline", function(error, _pipeline){
[...]
});
If everything works correctly, we have an instance of a media pipeline (variable pipeline in this example). With
this instance, we are able to create Media Elements. In this example we just need a WebRtcEndpoint and a FaceOver-
layFilter. Then, these media elements are interconnected:
pipeline.create('WebRtcEndpoint', function(error, webRtcEp) {
if (error) return onError(error);
webRtcPeer.processAnswer(sdpAnswer, onError);
});
webRtcEp.gatherCandidates(onError);
});
Note: The TURN and STUN servers to be used can be configured simple adding the parameter ice_servers to
the application URL, as follows:
https://localhost:8443/index.html?ice_servers=[{"urls":"stun:stun1.example.net"},{
"urls":"stun:stun2.example.net"}]
https://localhost:8443/index.html?ice_servers=[{"urls":"turn:turn.example.org",
"username":"user","credential":"myPassword"}]
Dependencies
The dependencies of this demo has to be obtained using Bower. The definition of these dependencies are defined in
the bower.json file, as follows:
"dependencies": {
"kurento-client": "6.6.0",
"kurento-utils": "6.6.2"
}
Note: We are in active development. You can find the latest version of Kurento JavaScript Client at Bower.
This web application extends the Hello World Tutorial, adding media processing to the basic WebRTC loopback.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
curl -sL https://deb.nodesource.com/setup_4.x | sudo bash -
sudo apt-get install -y nodejs
sudo npm install -g bower
To launch the application, you need to clone the GitHub project where this demo is hosted, install it and run it:
If you have problems installing any of the dependencies, please remove them and clean the npm cache, and try to
install them again:
rm -r node_modules
npm cache clean
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the argument ws_uri to the
npm execution command, as follows:
In this case you need to use npm version 2. To update it you can use this command:
This application uses computer vision and augmented reality techniques to add a funny hat on top of faces. The
following picture shows a screenshot of the demo running in a web browser:
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
WebRtcEndpoint: Provides full-duplex (bidirectional) WebRTC capabilities.
FaceOverlay filter: Computer vision filter that detects faces in the video stream and puts an image on top of
them. In this demo the filter is configured to put a Super Mario hat).
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side we use a Node.js application server consuming the Kurento JavaScript
Client API to control Kurento Media Server capabilities. All in all, the high level architecture of this demo is
three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client and
application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the com-
munication between the Kurento JavaScript Client and the Kurento Media Server. This communication takes place
using the Kurento Protocol. For further information on it, please see this page of the documentation.
To communicate the client with the Node.js application server we have designed a simple signaling protocol based on
JSON messages over WebSocket s. The normal sequence between client and server is as follows: i) Client starts the
Magic Mirror. ii) Client stops the Magic Mirror.
If any exception happens, server sends an error message to the client. The detailed message sequence between client
and application server is depicted in the following picture:
Fig. 8.7: Kurento Magic Mirror Screenshot: WebRTC with filter in loopback
As you can see in the diagram, an SDP and ICE candidates needs to be exchanged between client and server to
establish the WebRTC session between the Kurento client and server. Specifically, the SDP negotiation connects the
WebRtcPeer at the browser with the WebRtcEndpoint at the server. The complete source code of this demo can be
found in GitHub.
This demo has been developed using the express framework for Node.js, but express is not a requirement for Kurento.
The main script of this demo is server.js.
In order to communicate the JavaScript client and the Node application server a WebSocket is used. The incoming
messages to this WebSocket (variable ws in the code) are conveniently handled to implemented the signaling protocol
depicted in the figure before (i.e. messages start, stop, onIceCandidate).
var ws = require('ws');
[...]
/*
* Management of WebSocket messages
*/
wss.on('connection', function(ws) {
var sessionId = null;
var request = ws.upgradeReq;
var response = {
writeHead : {}
};
ws.on('error', function(error) {
console.log('Connection ' + sessionId + ' error');
stop(sessionId);
});
ws.on('close', function() {
console.log('Connection ' + sessionId + ' closed');
stop(sessionId);
});
ws.on('message', function(_message) {
var message = JSON.parse(_message);
console.log('Connection ' + sessionId + ' received message ', message);
switch (message.id) {
case 'start':
sessionId = request.session.id;
start(sessionId, ws, message.sdpOffer, function(error, sdpAnswer) {
if (error) {
return ws.send(JSON.stringify({
id : 'error',
message : error
}));
}
ws.send(JSON.stringify({
id : 'startResponse',
sdpAnswer : sdpAnswer
}));
});
break;
case 'stop':
stop(sessionId);
break;
case 'onIceCandidate':
onIceCandidate(sessionId, message.candidate);
break;
default:
ws.send(JSON.stringify({
id : 'error',
message : 'Invalid message ' + message
}));
break;
}
});
});
In order to control the media capabilities provided by the Kurento Media Server, we need an instance of the Kuren-
toClient in the Node application server. In order to create this instance, we need to specify to the client library the
location of the Kurento Media Server. In this example, we assume its located at localhost listening in port 8888.
var kurento = require('kurento-client');
[...]
function getKurentoClient(callback) {
if (kurentoClient !== null) {
return callback(null, kurentoClient);
}
kurentoClient = _kurentoClient;
callback(null, kurentoClient);
});
}
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server. Our
first operation is to create a Media Pipeline, then we need to create the Media Elements and connect them. In this
example, we need a WebRtcEndpoint connected to a FaceOverlayFilter, which is connected to the sink of the same
WebRtcEndpoint. These functions are called in the start function, which is fired when the start message is
received:
function start(sessionId, ws, sdpOffer, callback) {
if (!sessionId) {
return callback('Cannot use undefined sessionId');
}
getKurentoClient(function(error, kurentoClient) {
if (error) {
return callback(error);
}
if (candidatesQueue[sessionId]) {
while(candidatesQueue[sessionId].length) {
var candidate = candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
connectMediaElements(webRtcEndpoint, faceOverlayFilter,
function(error) {
if (error) {
pipeline.release();
return callback(error);
}
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.
candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
if (error) {
pipeline.release();
return callback(error);
}
sessions[sessionId] = {
'pipeline' : pipeline,
'webRtcEndpoint' : webRtcEndpoint
}
return callback(null, sdpAnswer);
});
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
return callback(error);
}
});
});
});
});
});
}
faceOverlayFilter.connect(webRtcEndpoint, function(error) {
if (error) {
return callback(error);
}
return callback(null);
});
});
}
As of Kurento Media Server 6.0, the WebRTC negotiation is done by exchanging ICE candidates between the WebRTC
peers. To implement this protocol, the webRtcEndpoint receives candidates from the client in OnIceCandidate
function. These candidates are stored in a queue when the webRtcEndpoint is not available yet. Then these
candidates are added to the media element by calling to the addIceCandidate method.
var candidatesQueue = {};
[...]
if (sessions[sessionId]) {
console.info('Sending candidate');
var webRtcEndpoint = sessions[sessionId].webRtcEndpoint;
webRtcEndpoint.addIceCandidate(candidate);
}
else {
console.info('Queueing candidate');
if (!candidatesQueue[sessionId]) {
candidatesQueue[sessionId] = [];
}
candidatesQueue[sessionId].push(candidate);
}
}
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js to
simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript WebRTC
utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this applica-
tion. These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we
can see the creation of the WebSocket (variable ws) in the path /magicmirror. Then, the onmessage listener
of the WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there are three
incoming messages to client: startResponse, error, and iceCandidate. Convenient actions are taken to
implement each step in the communication.
var ws = new WebSocket('ws://' + location.host + '/magicmirror');
var webRtcPeer;
const I_CAN_START = 0;
const I_CAN_STOP = 1;
const I_AM_STARTING = 2;
[...]
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'error':
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Error message from server: ' + parsedMessage.message);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate)
break;
default:
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Unrecognized message', parsedMessage);
}
}
In the function start the method WebRtcPeer.WebRtcPeerSendrecv of kurento-utils.js is used to create the
webRtcPeer object, which is used to handle the WebRTC communication.
videoInput = document.getElementById('videoInput');
videoOutput = document.getElementById('videoOutput');
[...]
function start() {
console.log('Starting video call ...')
var options = {
localVideo: videoInput,
remoteVideo: videoOutput,
onicecandidate : onIceCandidate
}
function onIceCandidate(candidate) {
console.log('Local candidate' + JSON.stringify(candidate));
var message = {
id : 'onIceCandidate',
candidate : candidate
};
sendMessage(message);
}
Dependencies
Server-side dependencies of this demo are managed using npm. Our main dependency is the Kurento Client JavaScript
(kurento-client). The relevant part of the package.json file for managing this dependency is:
"dependencies": {
[...]
"kurento-client" : "6.6.0"
}
At the client side, dependencies are managed using Bower. Take a look to the bower.json file and pay attention to the
following section:
"dependencies": {
[...]
"kurento-utils" : "6.6.2"
}
Note: We are in active development. You can find the latest version of Kurento JavaScript Client at npm and Bower.
Video broadcasting for WebRTC. One peer transmits a video stream and N peers receive it.
This web application consists on a one-to-many video call using WebRTC technology. In other words, it is an imple-
mentation of a video broadcasting web application.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
The web application starts on port 8443 in the localhost by default. Therefore, open the URL https://localhost:8443/
in a WebRTC compliant browser (Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
85
Kurento Documentation, Release 6.6.1
There will be two types of users in this application: 1 peer sending media (lets call it Presenter) and N peers receiving
the media from the Presenter (lets call them Viewers). Thus, the Media Pipeline is composed by 1+N interconnected
WebRtcEndpoints. The following picture shows an screenshot of the Presenters web GUI:
To implement this behavior we have to create a Media Pipeline composed by 1+N WebRtcEndpoints. The Presenter
peer sends its stream to the rest of the Viewers. Viewers are configured in receive-only mode. The implemented media
pipeline is illustrated in the following picture:
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side, we use a Spring-Boot based server application consuming the Kurento
Java Client API, to control Kurento Media Server capabilities. All in all, the high level architecture of this demo is
three-tier. To communicate these entities two WebSockets are used. First, a WebSocket is created between client and
server-side to implement a custom signaling protocol. Second, another WebSocket is used to perform the communi-
cation between the Kurento Java Client and the Kurento Media Server. This communication is implemented by the
Kurento Protocol. For further information, please see this page.
Client and application server communicate using a signaling protocol based on JSON messages over WebSocket s.
The normal sequence between client and server is as follows:
1. A Presenter enters in the system. There must be one and only one Presenter at any time. For that, if a Presenter
has already present, an error message is sent if another user tries to become Presenter.
2. N Viewers connect to the presenter. If no Presenter is present, then an error is sent to the corresponding Viewer.
3. Viewers can leave the communication at any time.
4. When the Presenter finishes the session each connected Viewer receives an stopCommunication message and also
terminates its session.
We can draw the following sequence diagram with detailed messages between clients and server:
As you can see in the diagram, SDP and ICE candidates need to be exchanged between client and server to establish the
WebRTC connection between the Kurento client and server. Specifically, the SDP negotiation connects the WebRtcPeer
in the browser with the WebRtcEndpoint in the server. The complete source code of this demo can be found in GitHub.
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vertex, etc. We chose Spring Boot for convenience.
In the following, figure you can see a class diagram of the server side code:
The main class of this demo is named One2ManyCallApp. As you can see, the KurentoClient is instantiated in this
class as a Spring Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities
to your applications. In this instantiation we see that a WebSocket is used to connect with Kurento Media Server, by
default in the localhost and listening in the port 8888.
@EnableWebSocket
@SpringBootApplication
public class One2ManyCallApp implements WebSocketConfigurer {
@Bean
public CallHandler callHandler() {
return new CallHandler();
}
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with server by means of requests and responses. Specifically, the main app class implements the interface
WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path /call.
CallHandler class implements TextWebSocketHandler to handle text WebSocket requests. The central piece
of this class is the method handleTextMessage. This method implements the actions for requests, returning
responses through the WebSocket. In other words, it implements the server part of the signaling protocol depicted in
the previous sequence diagram.
In the designed protocol there are three different kind of incoming messages to the Server : presenter, viewer,
stop, and onIceCandidate. These messages are treated in the switch clause, taking the proper steps in each case.
@Autowired
private KurentoClient kurento;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
switch (jsonMessage.get("id").getAsString()) {
case "presenter":
try {
presenter(session, jsonMessage);
} catch (Throwable t) {
handleErrorResponse(t, session, "presenterResponse");
}
break;
case "viewer":
try {
viewer(session, jsonMessage);
} catch (Throwable t) {
handleErrorResponse(t, session, "viewerResponse");
}
break;
case "onIceCandidate": {
JsonObject candidate = jsonMessage.get("candidate").getAsJsonObject();
candidate.get("sdpMid").getAsString(), candidate.get("sdpMLineIndex
").getAsInt());
user.addCandidate(cand);
}
break;
}
case "stop":
stop(session);
break;
default:
break;
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
throws Exception {
stop(session);
}
In the following snippet, we can see the presenter method. It creates a Media Pipeline and the WebRtcEndpoint
for presenter:
private synchronized void presenter(final WebSocketSession session, JsonObject
jsonMessage) throws IOException {
if (presenterUserSession == null) {
presenterUserSession = new UserSession(session);
pipeline = kurento.createMediaPipeline();
presenterUserSession.setWebRtcEndpoint(new WebRtcEndpoint.Builder(pipeline).
build());
presenterWebRtc.addIceCandidateFoundListener(new EventListener
<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
synchronized (session) {
presenterUserSession.sendMessage(response);
}
presenterWebRtc.gatherCandidates();
} else {
JsonObject response = new JsonObject();
response.addProperty("id", "presenterResponse");
response.addProperty("response", "rejected");
response.addProperty("message", "Another user is currently acting as sender.
Try again later ...");
session.sendMessage(new TextMessage(response.toString()));
}
}
The viewer method is similar, but not he Presenter WebRtcEndpoint is connected to each of the viewers WebRt-
cEndpoints, otherwise an error is sent back to the client.
private synchronized void viewer(final WebSocketSession session, JsonObject
jsonMessage) throws IOException {
session.sendMessage(new TextMessage(response.toString()));
} else {
if (viewers.containsKey(session.getId())) {
JsonObject response = new JsonObject();
response.addProperty("id", "viewerResponse");
response.addProperty("response", "rejected");
response.addProperty("message",
"You are already viewing in this session. Use a different browser to
add additional viewers.");
session.sendMessage(new TextMessage(response.toString()));
return;
}
UserSession viewer = new UserSession(session);
viewers.put(session.getId(), viewer);
nextWebRtc.addIceCandidateFoundListener(new EventListener
<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
viewer.setWebRtcEndpoint(nextWebRtc);
presenterUserSession.getWebRtcEndpoint().connect(nextWebRtc);
String sdpAnswer = nextWebRtc.processOffer(sdpOffer);
synchronized (session) {
viewer.sendMessage(response);
}
nextWebRtc.gatherCandidates();
}
}
Finally, the stop message finishes the communication. If this message is sent by the Presenter, a
stopCommunication message is sent to each connected Viewer:
private synchronized void stop(WebSocketSession session) throws IOException {
String sessionId = session.getId();
if (presenterUserSession != null && presenterUserSession.getSession().getId().
equals(sessionId)) {
pipeline.release();
}
pipeline = null;
presenterUserSession = null;
} else if (viewers.containsKey(sessionId)) {
if (viewers.get(sessionId).getWebRtcEndpoint() != null) {
viewers.get(sessionId).getWebRtcEndpoint().release();
}
viewers.remove(sessionId);
}
}
Client-Side
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we
can see the creation of the WebSocket (variable ws) in the path /call. Then, the onmessage listener of the
WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there are four incoming
messages to client: presenterResponse, viewerResponse, iceCandidate, and stopCommunication.
Convenient actions are taken to implement each step in the communication. For example, in the function presenter
the function WebRtcPeer.WebRtcPeerSendonly of kurento-utils.js is used to start a WebRTC communication.
Then, WebRtcPeer.WebRtcPeerRecvonly is used in the viewer function.
var ws = new WebSocket('ws://' + location.host + '/call');
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'presenterResponse':
presenterResponse(parsedMessage);
break;
case 'viewerResponse':
viewerResponse(parsedMessage);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {
if (!error) return;
console.error("Error adding candidate: " + error);
});
break;
case 'stopCommunication':
dispose();
break;
default:
console.error('Unrecognized message', parsedMessage);
}
}
function presenter() {
if (!webRtcPeer) {
showSpinner(video);
var options = {
localVideo: video,
onicecandidate: onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options,
function (error) {
if(error) {
return console.error(error);
}
webRtcPeer.generateOffer(onOfferPresenter);
});
}
}
function viewer() {
if (!webRtcPeer) {
showSpinner(video);
var options = {
remoteVideo: video,
onicecandidate: onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options,
function (error) {
if(error) {
return console.error(error);
}
this.generateOffer(onOfferViewer);
});
}
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This web application consists on one-to-many video call using WebRTC technology. In other words, it is an imple-
mentation of a video broadcasting web application.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
To launch the application, you need to clone the GitHub project where this demo is hosted, install it and run it:
If you have problems installing any of the dependencies, please remove them and clean the npm cache, and try to
install them again:
rm -r node_modules
npm cache clean
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the argument ws_uri to the
npm execution command, as follows:
In this case you need to use npm version 2. To update it you can use this command:
There will be two types of users in this application: 1 peer sending media (lets call it Presenter) and N peers receiving
the media from the Presenter (lets call them Viewers). Thus, the Media Pipeline is composed by 1+N interconnected
WebRtcEndpoints. The following picture shows an screenshot of the Presenters web GUI:
To implement this behavior we have to create a Media Pipeline composed by 1+N WebRtcEndpoints. The Presenter
peer sends its stream to the rest of the Viewers. Viewers are configured in receive-only mode. The implemented media
pipeline is illustrated in the following picture:
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side we use the Kurento JavaScript Client in order to reach the Kurento Media
Server. All in all, the high level architecture of this demo is three-tier. To communicate these entities two WebSockets
are used. The first is created between the client browser and a Node.js application server to transport signaling mes-
sages. The second is used to communicate the Kurento JavaScript Client executing at Node.js and the Kurento Media
Server. This communication is implemented by the Kurento Protocol. For further information, please see this page.
Client and application server communicate using a signaling protocol based on JSON messages over WebSocket s.
The normal sequence between client and server is as follows:
1. A Presenter enters in the system. There must be one and only one Presenter at any time. For that, if a Presenter
has already present, an error message is sent if another user tries to become Presenter.
2. N Viewers connect to the presenter. If no Presenter is present, then an error is sent to the corresponding Viewer.
3. Viewers can leave the communication at any time.
4. When the Presenter finishes the session each connected Viewer receives an stopCommunication message and also
terminates its session.
We can draw the following sequence diagram with detailed messages between clients and server:
As you can see in the diagram, SDP and ICE candidates need to be exchanged between client and server to establish the
WebRTC connection between the Kurento client and server. Specifically, the SDP negotiation connects the WebRtcPeer
in the browser with the WebRtcEndpoint in the server. The complete source code of this demo can be found in GitHub.
This demo has been developed using the express framework for Node.js, but express is not a requirement for Kurento.
The main script of this demo is server.js.
In order to communicate the JavaScript client and the Node application server a WebSocket is used. The incoming
messages to this WebSocket (variable ws in the code) are conveniently handled to implemented the signaling protocol
depicted in the figure before (i.e. messages presenter, viewer, stop, and onIceCandidate).
var ws = require('ws');
[...]
/*
* Management of WebSocket messages
*/
wss.on('connection', function(ws) {
ws.on('error', function(error) {
console.log('Connection ' + sessionId + ' error');
stop(sessionId);
});
ws.on('close', function() {
console.log('Connection ' + sessionId + ' closed');
stop(sessionId);
});
ws.on('message', function(_message) {
var message = JSON.parse(_message);
console.log('Connection ' + sessionId + ' received message ', message);
switch (message.id) {
case 'presenter':
startPresenter(sessionId, ws, message.sdpOffer, function(error, sdpAnswer) {
if (error) {
return ws.send(JSON.stringify({
id : 'presenterResponse',
response : 'rejected',
message : error
}));
}
ws.send(JSON.stringify({
id : 'presenterResponse',
response : 'accepted',
sdpAnswer : sdpAnswer
}));
});
break;
case 'viewer':
startViewer(sessionId, ws, message.sdpOffer, function(error, sdpAnswer) {
if (error) {
return ws.send(JSON.stringify({
id : 'viewerResponse',
response : 'rejected',
message : error
}));
}
ws.send(JSON.stringify({
id : 'viewerResponse',
response : 'accepted',
sdpAnswer : sdpAnswer
}));
});
break;
case 'stop':
stop(sessionId);
break;
case 'onIceCandidate':
onIceCandidate(sessionId, message.candidate);
break;
default:
ws.send(JSON.stringify({
id : 'error',
message : 'Invalid message ' + message
}));
break;
}
});
});
In order to control the media capabilities provided by the Kurento Media Server, we need an instance of the Kuren-
toClient in the Node application server. In order to create this instance, we need to specify to the client library the
location of the Kurento Media Server. In this example, we assume its located at localhost listening in port 8888.
var kurento = require('kurento-client');
[...]
function getKurentoClient(callback) {
if (kurentoClient !== null) {
return callback(null, kurentoClient);
}
kurentoClient = _kurentoClient;
callback(null, kurentoClient);
});
}
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server. Our first
operation is to create a Media Pipeline, then we need to create the Media Elements and connect them. In this example,
we need a WebRtcEndpoint (in send-only mode) for the presenter connected to N WebRtcEndpoint (in receive-only
mode) for the viewers. These functions are called in the startPresenter and startViewer function, which is
fired when the presenter and viewer message are received respectively:
function startPresenter(sessionId, ws, sdpOffer, callback) {
clearCandidatesQueue(sessionId);
presenter = {
id : sessionId,
pipeline : null,
webRtcEndpoint : null
}
getKurentoClient(function(error, kurentoClient) {
if (error) {
stop(sessionId);
return callback(error);
}
presenter.pipeline = pipeline;
pipeline.create('WebRtcEndpoint', function(error, webRtcEndpoint) {
if (error) {
stop(sessionId);
return callback(error);
}
presenter.webRtcEndpoint = webRtcEndpoint;
if (candidatesQueue[sessionId]) {
while(candidatesQueue[sessionId].length) {
var candidate = candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.
candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
callback(null, sdpAnswer);
});
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
stop(sessionId);
return callback(error);
}
});
});
});
});
}
clearCandidatesQueue(sessionId);
if (candidatesQueue[sessionId]) {
while(candidatesQueue[sessionId].length) {
var candidate = candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
presenter.webRtcEndpoint.connect(webRtcEndpoint, function(error) {
if (error) {
stop(sessionId);
return callback(error);
}
if (presenter === null) {
stop(sessionId);
return callback(noPresenterMessage);
}
callback(null, sdpAnswer);
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
stop(sessionId);
return callback(error);
}
});
});
});
});
}
As of Kurento Media Server 6.0, the WebRTC negotiation is done by exchanging ICE candidates between the WebRTC
peers. To implement this protocol, the webRtcEndpoint receives candidates from the client in OnIceCandidate
function. These candidates are stored in a queue when the webRtcEndpoint is not available yet. Then these
candidates are added to the media element by calling to the addIceCandidate method.
[...]
function clearCandidatesQueue(sessionId) {
if (candidatesQueue[sessionId]) {
delete candidatesQueue[sessionId];
}
}
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js to
simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript WebRTC
utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this applica-
tion. These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we
can see the creation of the WebSocket (variable ws) in the path /one2many. Then, the onmessage listener of the
WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there are three incoming
const I_CAN_START = 0;
const I_CAN_STOP = 1;
const I_AM_STARTING = 2;
[...]
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'presenterResponse':
presenterResponse(parsedMessage);
break;
case 'viewerResponse':
viewerResponse(parsedMessage);
break;
case 'stopCommunication':
dispose();
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate)
break;
default:
console.error('Unrecognized message', parsedMessage);
}
}
function presenterResponse(message) {
if (message.response != 'accepted') {
var errorMsg = message.message ? message.message : 'Unknow error';
console.warn('Call not accepted for the following reason: ' + errorMsg);
dispose();
} else {
webRtcPeer.processAnswer(message.sdpAnswer);
}
}
function viewerResponse(message) {
if (message.response != 'accepted') {
var errorMsg = message.message ? message.message : 'Unknow error';
console.warn('Call not accepted for the following reason: ' + errorMsg);
dispose();
} else {
webRtcPeer.processAnswer(message.sdpAnswer);
}
}
On the one hand, the function presenter uses the method WebRtcPeer.WebRtcPeerSendonly of kurento-
utils.js to start a WebRTC communication in send-only mode. On the other hand, the function viewer uses the
method WebRtcPeer.WebRtcPeerRecvonly of kurento-utils.js to start a WebRTC communication in receive-
only mode.
function presenter() {
if (!webRtcPeer) {
showSpinner(video);
var options = {
localVideo: video,
onicecandidate : onIceCandidate
}
webRtcPeer = kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options,
function(error) {
if(error) return onError(error);
this.generateOffer(onOfferPresenter);
});
}
}
var message = {
id : 'presenter',
sdpOffer : offerSdp
};
sendMessage(message);
}
function viewer() {
if (!webRtcPeer) {
showSpinner(video);
var options = {
remoteVideo: video,
onicecandidate : onIceCandidate
}
webRtcPeer = kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options,
function(error) {
if(error) return onError(error);
this.generateOffer(onOfferViewer);
});
}
}
var message = {
id : 'viewer',
sdpOffer : offerSdp
}
sendMessage(message);
}
Dependencies
Server-side dependencies of this demo are managed using npm. Our main dependency is the Kurento Client JavaScript
(kurento-client). The relevant part of the package.json file for managing this dependency is:
"dependencies": {
[...]
"kurento-client" : "6.6.0"
}
At the client side, dependencies are managed using Bower. Take a look to the bower.json file and pay attention to the
following section:
"dependencies": {
[...]
"kurento-utils" : "6.6.2"
}
Note: We are in active development. You can find the latest version of Kurento JavaScript Client at npm and Bower.
This web application consists on a one-to-one video call using WebRTC technology. In other words, this application
provides a simple video softphone.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
The web application starts on port 8443 in the localhost by default. Therefore, open the URL https://localhost:8443/
in a WebRTC compliant browser (Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
109
Kurento Documentation, Release 6.6.1
The following picture shows an screenshot of this demo running in a web browser:
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the local stream
and other for the remote peer stream). If two users, A and B, are using the application, the media flow goes this way:
The video camera stream of user A is sent to the Kurento Media Server, which sends it to user B. In the same way, B
sends to Kurento Media Server, which forwards it to A. This means that KMS is providing a B2B (back-to-back) call
service.
To implement this behavior, create sa Media Pipeline composed by two WebRtC endpoints connected in B2B. The
implemented media pipeline is illustrated in the following picture:
The client and the server communicate through a signaling protocol based on JSON messages over WebSocket s. The
normal sequence between client and server would be as follows:
1. User A is registered in the server with his name
2. User B is registered in the server with her name
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vertex, etc. We have choose Spring Boot for convenience.
In the following figure you can see a class diagram of the server side code:
The main class of this demo is named One2OneCallApp. As you can see, the KurentoClient is instantiated in this
class as a Spring Bean.
@EnableWebSocket
@SpringBootApplication
public class One2OneCallApp implements WebSocketConfigurer {
@Bean
public CallHandler callHandler() {
return new CallHandler();
}
@Bean
public UserRegistry registry() {
return new UserRegistry();
}
@Bean
Fig. 10.4: Server-side class diagram of the one to one video call app
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with server by means of requests and responses. Specifically, the main app class implements the interface
WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path /call.
CallHandler class implements TextWebSocketHandler to handle text WebSocket requests. The central piece
of this class is the method handleTextMessage. This method implements the actions for requests, returning
responses through the WebSocket. In other words, it implements the server part of the signaling protocol depicted in
the previous sequence diagram.
In the designed protocol there are five different kind of incoming messages to the application server: register,
call, incomingCallResponse, onIceCandidate and stop. These messages are treated in the switch
clause, taking the proper steps in each case.
@Autowired
private KurentoClient kurento;
@Autowired
private UserRegistry registry;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
if (user != null) {
log.debug("Incoming message from user '{}': {}", user.getName(),
jsonMessage);
} else {
log.debug("Incoming message from new user: {}", jsonMessage);
}
switch (jsonMessage.get("id").getAsString()) {
case "register":
try {
register(session, jsonMessage);
} catch (Throwable t) {
handleErrorResponse(t, session, "registerResponse");
}
break;
case "call":
try {
call(user, jsonMessage);
} catch (Throwable t) {
handleErrorResponse(t, session, "callResponse");
}
break;
case "incomingCallResponse":
incomingCallResponse(user, jsonMessage);
break;
case "onIceCandidate": {
JsonObject candidate = jsonMessage.get("candidate").getAsJsonObject();
if (user != null) {
IceCandidate cand = new IceCandidate(candidate.get("candidate").
getAsString(),
candidate.get("sdpMid").getAsString(), candidate.get("sdpMLineIndex
").getAsInt());
user.addCandidate(cand);
}
break;
}
case "stop":
stop(session);
break;
default:
break;
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
throws Exception {
stop(session);
registry.removeBySession(session);
}
In the following snippet, we can see the register method. Basically, it obtains the name attribute from register
message and check if there are a registered user with that name. If not, the new user is registered and an acceptance
message is sent to it.
private void register(WebSocketSession session, JsonObject jsonMessage) throws
IOException {
response.addProperty("id", "resgisterResponse");
response.addProperty("response", responseMsg);
caller.sendMessage(response);
}
In the call method, the server checks if there is a registered user with the name specified in to message attribute,
and sends an incomingCall message. If there is no user with that name, a callResponse message is sent to
caller rejecting the call.
private void call(UserSession caller, JsonObject jsonMessage) throws IOException {
String to = jsonMessage.get("to").getAsString();
String from = jsonMessage.get("from").getAsString();
JsonObject response = new JsonObject();
if (registry.exists(to)) {
UserSession callee = registry.getByName(to);
caller.setSdpOffer(jsonMessage.getAsJsonPrimitive("sdpOffer").getAsString());
caller.setCallingTo(to);
response.addProperty("id", "incomingCall");
response.addProperty("from", from);
callee.sendMessage(response);
callee.setCallingFrom(from);
} else {
response.addProperty("id", "callResponse");
response.addProperty("response", "rejected: user '" + to + "' is not registered
");
caller.sendMessage(response);
}
}
The stop method ends the video call. It can be called both by caller and callee in the communication. The result is
that both peers release the Media Pipeline and ends the video communication:
public void stop(WebSocketSession session) throws IOException {
String sessionId = session.getId();
if (pipelines.containsKey(sessionId)) {
pipelines.get(sessionId).release();
CallMediaPipeline pipeline = pipelines.remove(sessionId);
pipeline.release();
if (stoppedUser != null) {
JsonObject message = new JsonObject();
message.addProperty("id", "stopCommunication");
stoppedUser.sendMessage(message);
stoppedUser.clear();
}
stopperUser.clear();
}
}
}
In the incomingCallResponse method, if the callee user accepts the call, it is established and the me-
dia elements are created to connect the caller with the callee in a B2B manner. Basically, the server creates a
CallMediaPipeline object, to encapsulate the media pipeline creation and management. Then, this object is
used to negotiate media interchange with users browsers.
The negotiation between WebRTC peer in the browser and WebRtcEndpoint in Kurento Media Server is made
by means of SDP generation at the client (offer) and SDP generation at the server (answer). The SDP an-
swers are generated with the Kurento Java Client inside the class CallMediaPipeline (as we see in a mo-
ment). The methods used to generate SDP are generateSdpAnswerForCallee(calleeSdpOffer) and
generateSdpAnswerForCaller(callerSdpOffer):
private void incomingCallResponse(final UserSession callee, JsonObject jsonMessage)
throws IOException {
if ("accept".equals(callResponse)) {
log.debug("Accepted call from '{}' to '{}'", from, to);
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.
getCandidate()));
try {
synchronized (callee.getSession()) {
callee.getSession().sendMessage(new TextMessage(response.
toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
pipeline.getCallerWebRtcEP().addIceCandidateFoundListener(new EventListener
<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.
getCandidate()));
try {
synchronized (calleer.getSession()) {
calleer.getSession().sendMessage(new TextMessage(response.
toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
synchronized (callee) {
callee.sendMessage(startCommunication);
}
pipeline.getCalleeWebRtcEP().gatherCandidates();
synchronized (calleer) {
calleer.sendMessage(response);
}
pipeline.getCallerWebRtcEP().gatherCandidates();
} catch (Throwable t) {
log.error(t.getMessage(), t);
if (pipeline != null) {
pipeline.release();
}
pipelines.remove(calleer.getSessionId());
pipelines.remove(callee.getSessionId());
} else {
JsonObject response = new JsonObject();
response.addProperty("id", "callResponse");
response.addProperty("response", "rejected");
calleer.sendMessage(response);
}
}
The media logic in this demo is implemented in the class CallMediaPipeline. As you can see, the media pipeline
of this demo is quite simple: two WebRtcEndpoint elements directly interconnected. Please take note that the
WebRtcEndpoints need to be connected twice, one for each media direction.
public class CallMediaPipeline {
this.callerWebRtcEP.connect(this.calleeWebRtcEP);
this.calleeWebRtcEP.connect(this.callerWebRtcEP);
} catch (Throwable t) {
if (this.pipeline != null) {
pipeline.release();
}
}
}
Client-Side
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js.
In the following snippet we can see the creation of the WebSocket (variable ws) in the path /call. Then, the
onmessage listener of the WebSocket is used to implement the JSON signaling protocol in the client-side. No-
tice that there are five incoming messages to client: resgisterResponse, callResponse, incomingCall,
iceCandidate and startCommunication. Convenient actions are taken to implement each step in the com-
munication. For example, in functions call and incomingCall (for caller and callee respectively), the function
WebRtcPeer.WebRtcPeerSendrecv of kurento-utils.js is used to start a WebRTC communication.
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'resgisterResponse':
resgisterResponse(parsedMessage);
break;
case 'callResponse':
callResponse(parsedMessage);
break;
case 'incomingCall':
incomingCall(parsedMessage);
break;
case 'startCommunication':
startCommunication(parsedMessage);
break;
case 'stopCommunication':
console.info("Communication ended by remote peer");
stop(true);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {
if (!error) return;
console.error("Error adding candidate: " + error);
});
break;
default:
console.error('Unrecognized message', parsedMessage);
}
}
function incomingCall(message) {
//If bussy just reject without disturbing user
if (callState != NO_CALL) {
var response = {
id : 'incomingCallResponse',
from : message.from,
callResponse : 'reject',
message : 'bussy'
};
return sendMessage(response);
}
setCallState(PROCESSING_CALL);
if (confirm('User ' + message.from
+ ' is calling you. Do you accept the call?')) {
showSpinner(videoInput, videoOutput);
from = message.from;
var options = {
localVideo: videoInput,
remoteVideo: videoOutput,
onicecandidate: onIceCandidate,
onerror: onError
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function (error) {
if(error) {
return console.error(error);
}
webRtcPeer.generateOffer (onOfferIncomingCall);
});
} else {
var response = {
id : 'incomingCallResponse',
from : message.from,
callResponse : 'reject',
message : 'user declined'
};
sendMessage(response);
stop();
}
}
function call() {
if (document.getElementById('peer').value == '') {
window.alert("You must specify the peer name");
return;
}
setCallState(PROCESSING_CALL);
showSpinner(videoInput, videoOutput);
var options = {
localVideo: videoInput,
remoteVideo: videoOutput,
onicecandidate: onIceCandidate,
onerror: onError
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function (error) {
if(error) {
return console.error(error);
}
webRtcPeer.generateOffer (onOfferCall);
});
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>draggabilly</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This web application consists on a one-to-one video call using WebRTC technology. In other words, this application
provides a simple video softphone.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
To launch the application, you need to clone the GitHub project where this demo is hosted, install it and run it:
If you have problems installing any of the dependencies, please remove them and clean the npm cache, and try to
install them again:
rm -r node_modules
npm cache clean
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the argument ws_uri to the
npm execution command, as follows:
In this case you need to use npm version 2. To update it you can use this command:
The following picture shows an screenshot of this demo running in a web browser:
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the local stream
and other for the remote peer stream). If two users, A and B, are using the application, the media flow goes this way:
The video camera stream of user A is sent to the Kurento Media Server, which sends it to user B. In the same way, B
sends to Kurento Media Server, which forwards it to A. This means that KMS is providing a B2B (back-to-back) call
service.
To implement this behavior create a Media Pipeline composed by two WebRtC endpoints connected in B2B. The
implemented media pipeline is illustrated in the following picture:
The client and the server communicate through a signaling protocol based on JSON messages over WebSocket s. The
normal sequence between client and application server logic is as follows:
1. User A is registered in the application server with his name
2. User B is registered in the application server with her name
3. User A issues a call to User B
4. User B accepts the incoming call
5. The communication is established and media flows between User A and User B
6. One of the users finishes the video communication
The detailed message flow in a call are shown in the picture below:
As you can see in the diagram, SDP and ICE candidates need to be exchanged between client and server to establish the
WebRTC connection between the Kurento client and server. Specifically, the SDP negotiation connects the WebRtcPeer
in the browser with the WebRtcEndpoint in the server. The complete source code of this demo can be found in GitHub.
This demo has been developed using the express framework for Node.js, but express is not a requirement for Kurento.
The main script of this demo is server.js.
In order to communicate the JavaScript client and the Node application server a WebSocket is used. The incom-
ing messages to this WebSocket (variable ws in the code) are conveniently handled to implemented the signaling
protocol depicted in the figure before (i.e. messages register, call, incomingCallResponse, stop, and
onIceCandidate).
var ws = require('ws');
[...]
wss.on('connection', function(ws) {
var sessionId = nextUniqueId();
console.log('Connection received with sessionId ' + sessionId);
ws.on('error', function(error) {
console.log('Connection ' + sessionId + ' error');
stop(sessionId);
});
ws.on('close', function() {
console.log('Connection ' + sessionId + ' closed');
stop(sessionId);
userRegistry.unregister(sessionId);
});
ws.on('message', function(_message) {
var message = JSON.parse(_message);
console.log('Connection ' + sessionId + ' received message ', message);
switch (message.id) {
case 'register':
register(sessionId, message.name, ws);
break;
case 'call':
call(sessionId, message.to, message.from, message.sdpOffer);
break;
case 'incomingCallResponse':
incomingCallResponse(sessionId, message.from, message.callResponse,
message.sdpOffer, ws);
break;
case 'stop':
stop(sessionId);
break;
case 'onIceCandidate':
onIceCandidate(sessionId, message.candidate);
break;
default:
ws.send(JSON.stringify({
id : 'error',
message : 'Invalid message ' + message
}));
break;
}
});
});
In order to perform a call, each user (the caller and the callee) must be register in the system. For this reason, in the
server-side there is a class named UserRegistry to store and locate users. Then, the register message fires the
execution of the following function:
// Represents registrar of users
function UserRegistry() {
this.usersById = {};
this.usersByName = {};
}
UserRegistry.prototype.register = function(user) {
this.usersById[user.id] = user;
this.usersByName[user.name] = user;
UserRegistry.prototype.unregister = function(id) {
var user = this.getById(id);
if (user) delete this.usersById[id]
if (user && this.getByName(user.name)) delete this.usersByName[user.name];
}
UserRegistry.prototype.getById = function(id) {
return this.usersById[id];
}
UserRegistry.prototype.getByName = function(name) {
return this.usersByName[name];
}
UserRegistry.prototype.removeById = function(id) {
var userSession = this.usersById[id];
if (!userSession) return;
delete this.usersById[id];
delete this.usersByName[userSession.name];
}
if (!name) {
return onError("empty user name");
}
if (userRegistry.getByName(name)) {
return onError("User " + name + " is already registered");
}
In order to control the media capabilities provided by the Kurento Media Server, we need an instance of the Kuren-
toClient in the Node application server. In order to create this instance, we need to specify to the client library the
location of the Kurento Media Server. In this example, we assume its located at localhost listening in port 8888.
var kurento = require('kurento-client');
});
[...]
function getKurentoClient(callback) {
if (kurentoClient !== null) {
return callback(null, kurentoClient);
}
kurentoClient = _kurentoClient;
callback(null, kurentoClient);
});
}
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server. Our first
operation is to create a Media Pipeline, then we need to create the Media Elements and connect them. In this example,
we need two WebRtcEndpoints, i.e. one peer caller and other one for the callee. This media logic is implemented in
the class CallMediaPipeline. Note that the WebRtcEndpoints need to be connected twice, one for each media
direction. This object is created in the function incomingCallResponse which is fired in the callee peer, after
the caller executes the function call:
clearCandidatesQueue(calleeId);
var calleeMessage = {
id: 'stopCommunication'
};
if (calleeReason) calleeMessage.message = calleeReason;
callee.sendMessage(calleeMessage);
}
var message = {
id: 'startCommunication',
sdpAnswer: calleeSdpAnswer
};
callee.sendMessage(message);
message = {
id: 'callResponse',
response : 'accepted',
sdpAnswer: callerSdpAnswer
};
caller.sendMessage(message);
});
});
});
} else {
var decline = {
id: 'callResponse',
response: 'rejected',
message: 'user declined'
};
caller.sendMessage(decline);
}
}
As of Kurento Media Server 6.0, the WebRTC negotiation is done by exchanging ICE candidates between the WebRTC
peers. To implement this protocol, the webRtcEndpoint receives candidates from the client in OnIceCandidate
function. These candidates are stored in a queue when the webRtcEndpoint is not available yet. Then these
candidates are added to the media element by calling to the addIceCandidate method.
var candidatesQueue = {};
[...]
function clearCandidatesQueue(sessionId) {
if (candidatesQueue[sessionId]) {
delete candidatesQueue[sessionId];
}
}
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application. These libraries are linked in the index.html web page, and are used in the index.js. In the following
snippet we can see the creation of the WebSocket (variable ws) in the path /one2one. Then, the onmessage
listener of the WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there
are three incoming messages to client: startResponse, error, and iceCandidate. Convenient actions are
taken to implement each step in the communication. For example, in functions start the function WebRtcPeer.
WebRtcPeerSendrecv of kurento-utils.js is used to start a WebRTC communication.
[...]
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'registerResponse':
resgisterResponse(parsedMessage);
break;
case 'callResponse':
callResponse(parsedMessage);
break;
case 'incomingCall':
incomingCall(parsedMessage);
break;
case 'startCommunication':
startCommunication(parsedMessage);
break;
case 'stopCommunication':
console.info("Communication ended by remote peer");
stop(true);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate)
break;
default:
console.error('Unrecognized message', parsedMessage);
}
}
On the one hand, the function call is executed in the caller client-side, using the method WebRtcPeer.
WebRtcPeerSendrecv of kurento-utils.js to start a WebRTC communication in duplex mode. On the
other hand, the function incomingCall in the callee client-side uses also the method WebRtcPeer.
WebRtcPeerSendrecv of kurento-utils.js to complete the WebRTC call.
function call() {
if (document.getElementById('peer').value == '') {
window.alert("You must specify the peer name");
return;
}
setCallState(PROCESSING_CALL);
showSpinner(videoInput, videoOutput);
var options = {
localVideo : videoInput,
remoteVideo : videoOutput,
onicecandidate : onIceCandidate
}
this.generateOffer(function(error, offerSdp) {
if (error) {
console.error(error);
setCallState(NO_CALL);
}
var message = {
id : 'call',
from : document.getElementById('name').value,
to : document.getElementById('peer').value,
sdpOffer : offerSdp
};
sendMessage(message);
});
});
}
function incomingCall(message) {
// If bussy just reject without disturbing user
if (callState != NO_CALL) {
var response = {
id : 'incomingCallResponse',
from : message.from,
callResponse : 'reject',
message : 'bussy'
};
return sendMessage(response);
}
setCallState(PROCESSING_CALL);
if (confirm('User ' + message.from
+ ' is calling you. Do you accept the call?')) {
showSpinner(videoInput, videoOutput);
var options = {
localVideo : videoInput,
remoteVideo : videoOutput,
onicecandidate : onIceCandidate
}
webRtcPeer = kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function(error) {
if (error) {
console.error(error);
setCallState(NO_CALL);
}
this.generateOffer(function(error, offerSdp) {
if (error) {
console.error(error);
setCallState(NO_CALL);
}
var response = {
id : 'incomingCallResponse',
from : message.from,
callResponse : 'accept',
sdpOffer : offerSdp
};
sendMessage(response);
});
});
} else {
var response = {
id : 'incomingCallResponse',
from : message.from,
callResponse : 'reject',
message : 'user declined'
};
sendMessage(response);
stop(true);
}
}
Dependencies
Server-side dependencies of this demo are managed using npm. Our main dependency is the Kurento Client JavaScript
(kurento-client). The relevant part of the package.json file for managing this dependency is:
"dependencies": {
[...]
"kurento-client" : "6.6.0"
}
At the client side, dependencies are managed using Bower. Take a look to the bower.json file and pay attention to the
following section:
"dependencies": {
[...]
"kurento-utils" : "6.6.2"
}
Note: We are in active development. You can find the latest version of Kurento JavaScript Client at npm and Bower.
This is an enhanced version of the the one-to-one application with video recording and augmented reality.
This web application consists on an advanced one to one video call using WebRTC technology. It is an improved
version of the one 2 one call tutorial).
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
The web application starts on port 8443 in the localhost by default. Therefore, open the URL https://localhost:8443/
in a WebRTC compliant browser (Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
135
Kurento Documentation, Release 6.6.1
This application incorporates the recording capability provided by the Kurento Media Server in a one to one video
communication. In addition, a filter element (FaceOverlayFilter) is placed between the WebRtcEndpoints of the Media
Pipeline. The following picture shows an screenshot of this demo running in a web browser:
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the local video
camera stream (the caller stream, the smaller video in the picture) and other for the remote peer in the call (the callee
stream, the bigger video in the picture). If two users, A and B, are using the application, the media flow goes this way:
The video camera stream of user A is sent to the Kurento Media Server and sent again to the user B. On the other
hand, user B sends its video camera stream to Kurento and then it is sent to user A.
This application is implemented by means of two Media Pipeline s. First, the rich real-time WebRTC communication
is performed two WebRtcEndpoints interconnected, and with a FaceOverlayFilter in between them. In addition and a
RecorderEndpoint is used to store both streams in the file system of the Kurento Media Server. This media pipeline is
illustrated in the following picture:
136 Chapter 11. WebRTC one-to-one video call with recording and filtering
Kurento Documentation, Release 6.6.1
Fig. 11.2: Advanced one to one video call media pipeline (1)
A second media pipeline is needed to play the previously recorded media. This pipeline is composed by a Play-
erEndpoint which reads the files stored in the Kurento Media Server. This media element injects the media in a
WebRtcEndpoint which is charge to transport the media to the HTML5 video tag in the browser:
Fig. 11.3: Advanced one to one video call media pipeline (2)
Note: The playback of a static file can be done in several ways. In addition to this media pipeline (PlayerEndpoint
-> WebRtcEndpoint) the recorded file could be served directly by an HTTP server.
To communicate the client with the server to manage calls we have designed a signaling protocol based on JSON
messages over WebSocket s. The normal sequence between client and server would be as follows:
1. User A is registered in the server with his name
2. User B is registered in the server with her name
3. User A wants to call to User B
4. User B accepts the incoming call
5. The communication is established and media is flowing between User A and User B
6. One of the users finishes the video communication
7. One of the users play the recorded media
This is very simple protocol designed to show a simple one to one call application implemented with Kurento. In
a professional application it can be improved, for example implementing seeking user, ordered finish, among other
functions.
Assuming that User A is using Client A and User B is using Client B, we can draw the following sequence diagram with
detailed messages between clients and server. The following diagram shows the two parts of the signaling protocol:
first the enhanced real-time communication is performed, and then the playback of the recorded file is carried out.
As you can see in the diagram, SDP and ICE candidates need to be interchanged between client and server to estab-
lish the WebRTC connection between the Kurento client and server. Specifically, the SDP negotiation connects the
WebRtcPeer in the browser with the WebRtcEndpoint in the server.
The following sections describe in detail the server-side, the client-side, and how to run the demo. The complete
source code of this demo can be found in GitHub.
As in the Magic Mirror tutorial, this demo has been developed using Java and Spring Boot.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vertex, etc. We have choose Spring Boot for convenience.
In the following figure you can see a class diagram of the server side code:
The main class of this demo is named One2OneCallAdvApp. As you can see, the KurentoClient is instantiated
in this class as a Spring Bean.
@EnableWebSocket
@SpringBootApplication
public class One2OneCallAdvApp implements WebSocketConfigurer {
@Bean
public CallHandler callHandler() {
return new CallHandler();
}
@Bean
public UserRegistry registry() {
return new UserRegistry();
}
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with server by means of requests and responses. Specifically, the main app class implements the interface
138 Chapter 11. WebRTC one-to-one video call with recording and filtering
Kurento Documentation, Release 6.6.1
Fig. 11.5: Server-side class diagram of the advanced one to one video call app
@Autowired
private KurentoClient kurento;
@Autowired
private UserRegistry registry;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {
JsonObject jsonMessage = gson.fromJson(message.getPayload(),
JsonObject.class);
UserSession user = registry.getBySession(session);
140 Chapter 11. WebRTC one-to-one video call with recording and filtering
Kurento Documentation, Release 6.6.1
if (user != null) {
log.debug("Incoming message from user '{}': {}", user.getName(),
jsonMessage);
} else {
log.debug("Incoming message from new user: {}", jsonMessage);
}
switch (jsonMessage.get("id").getAsString()) {
case "register":
register(session, jsonMessage);
break;
case "call":
call(user, jsonMessage);
break;
case "incomingCallResponse":
incomingCallResponse(user, jsonMessage);
break;
case "play":
play(user, jsonMessage);
break;
case "onIceCandidate": {
JsonObject candidate = jsonMessage.get("candidate")
.getAsJsonObject();
if (user != null) {
IceCandidate cand = new IceCandidate(candidate.get("candidate")
.getAsString(), candidate.get("sdpMid").getAsString(),
candidate.get("sdpMLineIndex").getAsInt());
user.addCandidate(cand);
}
break;
}
case "stop":
stop(session);
releasePipeline(user);
case "stopPlay":
releasePipeline(user);
default:
break;
}
}
...
}
@Override
public void afterConnectionClosed(WebSocketSession session,
CloseStatus status) throws Exception {
stop(session);
registry.removeBySession(session);
}
In the following snippet, we can see the register method. Basically, it obtains the name attribute from register
message and check if there are a registered user with that name. If not, the new user is registered and an acceptance
message is sent to it.
private void register(WebSocketSession session, JsonObject jsonMessage)
throws IOException {
String name = jsonMessage.getAsJsonPrimitive("name").getAsString();
In the call method, the server checks if there are a registered user with the name specified in to message attribute
and send an incomingCall message to it. Or, if there isnt any user with that name, a callResponse message
is sent to caller rejecting the call.
private void call(UserSession caller, JsonObject jsonMessage)
throws IOException {
String to = jsonMessage.get("to").getAsString();
String from = jsonMessage.get("from").getAsString();
JsonObject response = new JsonObject();
if (registry.exists(to)) {
UserSession callee = registry.getByName(to);
caller.setSdpOffer(jsonMessage.getAsJsonPrimitive("sdpOffer")
142 Chapter 11. WebRTC one-to-one video call with recording and filtering
Kurento Documentation, Release 6.6.1
.getAsString());
caller.setCallingTo(to);
response.addProperty("id", "incomingCall");
response.addProperty("from", from);
callee.sendMessage(response);
callee.setCallingFrom(from);
} else {
response.addProperty("id", "callResponse");
response.addProperty("response", "rejected");
response.addProperty("message", "user '" + to
+ "' is not registered");
caller.sendMessage(response);
}
}
In the incomingCallResponse method, if the callee user accepts the call, it is established and the media elements
are created to connect the caller with the callee. Basically, the server creates a CallMediaPipeline object, to
encapsulate the media pipeline creation and management. Then, this object is used to negotiate media interchange
with users browsers.
As explained in the Magic Mirror tutorial, the negotiation between WebRTC peer in the browser and WebRtcEndpoint
in Kurento Server is made by means of SDP generation at the client (offer) and SDP generation at the server (answer).
The SDP answers are generated with the Kurento Java Client inside the class CallMediaPipeline (as we see in a
moment). The methods used to generate SDP are generateSdpAnswerForCallee(calleeSdpOffer) and
generateSdpAnswerForCaller(callerSdpOffer):
private void incomingCallResponse(final UserSession callee,
JsonObject jsonMessage) throws IOException {
String callResponse = jsonMessage.get("callResponse").getAsString();
String from = jsonMessage.get("from").getAsString();
final UserSession calleer = registry.getByName(from);
String to = calleer.getCallingTo();
if ("accept".equals(callResponse)) {
log.debug("Accepted call from '{}' to '{}'", from, to);
callee.setWebRtcEndpoint(callMediaPipeline.getCalleeWebRtcEP());
callMediaPipeline.getCalleeWebRtcEP().addIceCandidateFoundListener(
new EventListener<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils
.toJsonObject(event.getCandidate()));
try {
synchronized (callee.getSession()) {
callee.getSession()
.sendMessage(
new TextMessage(response
.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
synchronized (callee) {
callee.sendMessage(startCommunication);
}
callMediaPipeline.getCalleeWebRtcEP().gatherCandidates();
calleer.setWebRtcEndpoint(callMediaPipeline.getCallerWebRtcEP());
callMediaPipeline.getCallerWebRtcEP().addIceCandidateFoundListener(
new EventListener<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils
.toJsonObject(event.getCandidate()));
try {
synchronized (calleer.getSession()) {
calleer.getSession()
.sendMessage(
new TextMessage(response
.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
144 Chapter 11. WebRTC one-to-one video call with recording and filtering
Kurento Documentation, Release 6.6.1
synchronized (calleer) {
calleer.sendMessage(response);
}
callMediaPipeline.getCallerWebRtcEP().gatherCandidates();
callMediaPipeline.record();
} else {
JsonObject response = new JsonObject();
response.addProperty("id", "callResponse");
response.addProperty("response", "rejected");
calleer.sendMessage(response);
}
}
Finally, the play method instantiates a PlayMediaPipeline object, which is used to create Media Pipeline in
charge of the playback of the recorded streams in the Kurento Media Server.
private void play(final UserSession session, JsonObject jsonMessage)
throws IOException {
String user = jsonMessage.get("user").getAsString();
log.debug("Playing recorded call of user '{}'", user);
if (registry.getByName(user) != null
&& registry.getBySession(session.getSession()) != null) {
final PlayMediaPipeline playMediaPipeline = new PlayMediaPipeline(
kurento, user, session.getSession());
String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
session.setPlayingWebRtcEndpoint(playMediaPipeline.getWebRtc());
playMediaPipeline.getPlayer().addEndOfStreamListener(
new EventListener<EndOfStreamEvent>() {
@Override
public void onEvent(EndOfStreamEvent event) {
UserSession user = registry
.getBySession(session.getSession());
releasePipeline(user);
playMediaPipeline.sendPlayEnd(session.getSession());
}
});
playMediaPipeline.getWebRtc().addIceCandidateFoundListener(
new EventListener<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils
.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.getSession()
.sendMessage(
new TextMessage(response
.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
response.addProperty("response", "accepted");
response.addProperty("sdpAnswer", sdpAnswer);
playMediaPipeline.play();
pipelines.put(session.getSessionId(),
playMediaPipeline.getPipeline());
synchronized (session.getSession()) {
session.sendMessage(response);
}
playMediaPipeline.getWebRtc().gatherCandidates();
} else {
response.addProperty("response", "rejected");
response.addProperty("error", "No recording for user '" + user
+ "'. Please type a correct user in the 'Peer' field.");
session.getSession().sendMessage(
new TextMessage(response.toString()));
}
}
The media logic in this demo is implemented in the classes CallMediaPipeline and PlayMediaPipeline. The first media
pipeline consists on two WebRtcEndpoint elements interconnected with a FaceOverlayFilter in between,
and also with and RecorderEndpoint to carry out the recording of the WebRTC communication. Please take
note that the WebRtc endpoints needs to be connected twice, one for each media direction. In this class we can see
the implementation of methods generateSdpAnswerForCaller and generateSdpAnswerForCallee.
These methods delegate to WebRtc endpoints to create the appropriate answer.
146 Chapter 11. WebRTC one-to-one video call with recording and filtering
Kurento Documentation, Release 6.6.1
// Media pipeline
pipeline = kurento.createMediaPipeline();
// Connections
webRtcCaller.connect(faceOverlayFilterCaller);
faceOverlayFilterCaller.connect(webRtcCallee);
faceOverlayFilterCaller.connect(recorderCaller);
webRtcCallee.connect(faceOverlayFilterCallee);
faceOverlayFilterCallee.connect(webRtcCaller);
faceOverlayFilterCallee.connect(recorderCallee);
}
Note: Notice the hat URLs are provided by the application server and consumed by the KMS. This logic is assuming
that the application server is hosted in local (localhost), and by the default the hat URLs are https://localhost:8443/
img/mario-wings.png and https://localhost:8443/img/Hat.png. If your application server is hosted in a different host,
it can be easily changed by means of the configuration parameter app.server.url, for example:
// Connection
player.connect(webRtc);
// Player listeners
player.addErrorListener(new EventListener<ErrorEvent>() {
@Override
public void onEvent(ErrorEvent event) {
log.info("ErrorEvent: {}", event.getDescription());
sendPlayEnd(session);
}
});
}
148 Chapter 11. WebRTC one-to-one video call with recording and filtering
Kurento Documentation, Release 6.6.1
player.play();
}
Client-Side
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js.
In the following snippet we can see the creation of the WebSocket (variable ws) in the path /call. Then, the
onmessage listener of the WebSocket is used to implement the JSON signaling protocol in the client-side. No-
tice that there are six incoming messages to client: resgisterResponse, callResponse, incomingCall,
startCommunication, iceCandidate and play. Convenient actions are taken to implement each step in
the communication. On the one hand, in functions call and incomingCall (for caller and callee respectively),
the function WebRtcPeer.WebRtcPeerSendrecv of kurento-utils.js is used to start a WebRTC communication.
On the other hand in the function play, the function WebRtcPeer.WebRtcPeerRecvonly is called since the
WebRtcEndpoint is used in receive-only.
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'resgisterResponse':
resgisterResponse(parsedMessage);
break;
case 'callResponse':
callResponse(parsedMessage);
break;
case 'incomingCall':
incomingCall(parsedMessage);
break;
case 'startCommunication':
startCommunication(parsedMessage);
break;
case 'stopCommunication':
console.info("Communication ended by remote peer");
stop(true);
break;
case 'playResponse':
playResponse(parsedMessage);
break;
case 'playEnd':
playEnd();
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {
if (!error) return;
console.error("Error adding candidate: " + error);
});
break;
default:
console.error('Unrecognized message', parsedMessage);
}
}
function incomingCall(message) {
// If bussy just reject without disturbing user
if (callState != NO_CALL && callState != POST_CALL) {
var response = {
id : 'incomingCallResponse',
from : message.from,
callResponse : 'reject',
message : 'bussy'
};
return sendMessage(response);
}
setCallState(DISABLED);
if (confirm('User ' + message.from
+ ' is calling you. Do you accept the call?')) {
showSpinner(videoInput, videoOutput);
from = message.from;
var options = {
localVideo: videoInput,
remoteVideo: videoOutput,
onicecandidate: onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function (error) {
if(error) {
return console.error(error);
}
this.generateOffer (onOfferIncomingCall);
});
} else {
var response = {
id : 'incomingCallResponse',
from : message.from,
150 Chapter 11. WebRTC one-to-one video call with recording and filtering
Kurento Documentation, Release 6.6.1
callResponse : 'reject',
message : 'user declined'
};
sendMessage(response);
stop();
}
}
function call() {
if (document.getElementById('peer').value == '') {
document.getElementById('peer').focus();
window.alert("You must specify the peer name");
return;
}
setCallState(DISABLED);
showSpinner(videoInput, videoOutput);
var options = {
localVideo: videoInput,
remoteVideo: videoOutput,
onicecandidate: onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function (error) {
if(error) {
return console.error(error);
}
this.generateOffer (onOfferCall);
});
}
function play() {
var peer = document.getElementById('peer').value;
if (peer == '') {
window.alert("You must insert the name of the user recording to be played
(field 'Peer')");
document.getElementById('peer').focus();
return;
}
document.getElementById('videoSmall').style.display = 'none';
setCallState(DISABLED);
showSpinner(videoOutput);
var options = {
remoteVideo: videoOutput,
onicecandidate: onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options,
function (error) {
if(error) {
return console.error(error);
}
this.generateOffer (onOfferPlay);
});
}
function stop(message) {
if (!message) {
var message = {
id : stopMessageId
}
sendMessage(message);
}
}
hideSpinner(videoInput, videoOutput);
document.getElementById('videoSmall').style.display = 'block';
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>draggabilly</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
152 Chapter 11. WebRTC one-to-one video call with recording and filtering
Kurento Documentation, Release 6.6.1
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
154 Chapter 11. WebRTC one-to-one video call with recording and filtering
CHAPTER 12
This tutorial connects several participants to the same video conference. A group call will ocnsist, in the media server
side, in N*N WebRTC endpoints, where N is the number of clients connected to that conference.
This tutorial shows how to work wih the concept of rooms, allowing to connect several clients between them using
WebRTC technology, creating a multiconference.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
You need to have installed the Kurento Media Server before running this example. Read the installation guide for
further information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
155
Kurento Documentation, Release 6.6.1
This tutorial shows how to work with the concept of rooms. Each room will create its own pipeline, being isolated
from the other rooms. Clients connecting to a certain room, will only be able to exchange media with clients in the
same room.
Each client will send its own media, and in turn will receive the media from all the other participants. This means that
there will be a total of n*n webrtc endpoints in each room, where n is the number of clients.
When a new client enters the room, a new webrtc will be created and negotiated receive the media on the server. On
the other hand, all participant will be informed that a new user has connected. Then, all participants will request the
server to receive the new participants media.
The newcomer, in turn, gets a list of all connected participants, and requests the server to receive the media from all
the present clients in the room.
When a client leaves the room, all clients are informed by the server. Then, the client-side code requests the server to
cancel all media elements related to the client that left.
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side, we use a Spring-Boot based server application consuming the Kurento
Java Client API, to control Kurento Media Server capabilities. All in all, the high level architecture of this demo
is three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client
and application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the
communication between the Kurento Java Client and the Kurento Media Server. This communication takes place
using the Kurento Protocol. For further information on it, please see this page of the documentation.
The following sections analyze in depth the server (Java) and client-side (JavaScript) code of this application. The
complete source code can be found in GitHub.
This demo has been developed using Java in the server-side with Spring Boot framework. This technology can be
used to embed the Tomcat web server in the application and thus simplify the development process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vert.x, etc. Here we chose Spring Boot for convenience.
The main class of this demo is GroupCalldApp. As you can see, the KurentoClient is instantiated in this class as a
Spring Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities to the
application. In this instantiation we see that we need to specify to the client library the location of the Kurento Media
Server. In this example, we assume it is located at localhost listening in port 8888. If you reproduce this example
youll need to insert the specific location of your Kurento Media Server instance there.
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server and
controlling its multimedia capabilities.
@EnableWebSocket
@SpringBootApplication
public class GroupCallApp implements WebSocketConfigurer {
@Bean
public UserRegistry registry() {
return new UserRegistry();
}
@Bean
public RoomManager roomManager() {
return new RoomManager();
}
@Bean
public CallHandler groupCallHandler() {
return new CallHandler();
}
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(groupCallHandler(), "/groupcall");
}
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with application server by means of requests and responses. Specifically, the main app class implements the
interface WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path
/groupcall.
CallHandler class implements TextWebSocketHandler to handle text WebSocket requests. The central piece
of this class is the method handleTextMessage. This method implements the actions for requests, returning
responses through the WebSocket. In other words, it implements the server part of the signaling protocol depicted in
the previous sequence diagram.
In the designed protocol there are five different kind of incoming messages to the application server: joinRoom,
receiveVideoFrom, leaveRoom and onIceCandidate. These messages are treated in the switch clause,
taking the proper steps in each case.
public class CallHandler extends TextWebSocketHandler {
@Autowired
private RoomManager roomManager;
@Autowired
private UserRegistry registry;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws
Exception {
if (user != null) {
log.debug("Incoming message from user '{}': {}", user.getName(), jsonMessage);
} else {
log.debug("Incoming message from new user: {}", jsonMessage);
}
switch (jsonMessage.get("id").getAsString()) {
case "joinRoom":
joinRoom(jsonMessage, session);
break;
case "receiveVideoFrom":
final String senderName = jsonMessage.get("sender").getAsString();
final UserSession sender = registry.getByName(senderName);
final String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
user.receiveVideoFrom(sender, sdpOffer);
break;
case "leaveRoom":
leaveRoom(user);
break;
case "onIceCandidate":
JsonObject candidate = jsonMessage.get("candidate").getAsJsonObject();
if (user != null) {
IceCandidate cand = new IceCandidate(candidate.get("candidate").
getAsString(),
candidate.get("sdpMid").getAsString(), candidate.get("sdpMLineIndex").
getAsInt());
user.addCandidate(cand, jsonMessage.get("name").getAsString());
}
break;
default:
break;
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
throws Exception {
...
}
In the following snippet, we can see the afterConnectionClosed method. Basically, it removes the
userSession from registry and throws out the user from the room.
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
throws Exception {
In the joinRoom method, the server checks if there are a registered room with the name specified, add the user into
this room and registries the user.
private void joinRoom(JsonObject params, WebSocketSession session) throws IOException
{
The leaveRoom method finish the video call from one user.
private void leaveRoom(UserSession user) throws IOException {
final Room room = roomManager.getRoom(user.getRoomName());
room.leave(user);
if (room.getParticipants().isEmpty()) {
roomManager.removeRoom(room);
}
}
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the conferenceroom.js. In the following snippet
we can see the creation of the WebSocket (variable ws) in the path /groupcall. Then, the onmessage listener
of the WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there are three
incoming messages to client: existingParticipants, newParticipantArrived, participantLeft,
receiveVideoAnswer and iceCandidate. Convenient actions are taken to implement each step in the commu-
nication. For example, in functions start the function WebRtcPeer.WebRtcPeerSendrecv of kurento-utils.js
is used to start a WebRTC communication.
var ws = new WebSocket('wss://' + location.host + '/groupcall');
var participants = {};
var name;
window.onbeforeunload = function() {
ws.close();
};
ws.onmessage = function(message) {
switch (parsedMessage.id) {
case 'existingParticipants':
onExistingParticipants(parsedMessage);
break;
case 'newParticipantArrived':
onNewParticipant(parsedMessage);
break;
case 'participantLeft':
onParticipantLeft(parsedMessage);
break;
case 'receiveVideoAnswer':
receiveVideoResponse(parsedMessage);
break;
case 'iceCandidate':
participants[parsedMessage.name].rtcPeer.addIceCandidate(parsedMessage.
candidate, function (error) {
if (error) {
console.error("Error adding candidate: " + error);
return;
}
});
break;
default:
console.error('Unrecognized message', parsedMessage);
}
}
function register() {
name = document.getElementById('name').value;
var room = document.getElementById('roomName').value;
var message = {
id : 'joinRoom',
name : name,
room : room,
}
sendMessage(message);
}
function onNewParticipant(request) {
receiveVideo(request.name);
}
function receiveVideoResponse(result) {
participants[result.name].rtcPeer.processAnswer (result.sdpAnswer, function
(error) {
function callResponse(message) {
if (message.response != 'accepted') {
console.info('Call not accepted by peer. Closing call');
stop();
} else {
webRtcPeer.processAnswer(message.sdpAnswer, function (error) {
if (error) return console.error (error);
});
}
}
function onExistingParticipants(msg) {
var constraints = {
audio : true,
video : {
mandatory : {
maxWidth : 320,
maxFrameRate : 15,
minFrameRate : 15
}
}
};
console.log(name + " registered in room " + room);
var participant = new Participant(name);
participants[name] = participant;
var video = participant.getVideoElement();
var options = {
localVideo: video,
mediaConstraints: constraints,
onicecandidate: participant.onIceCandidate.bind(participant)
}
participant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options,
function (error) {
if(error) {
return console.error(error);
}
this.generateOffer (participant.offerToReceiveVideo.bind(participant));
});
msg.data.forEach(receiveVideo);
}
function leaveRoom() {
sendMessage({
id : 'leaveRoom'
});
document.getElementById('join').style.display = 'block';
document.getElementById('room').style.display = 'none';
ws.close();
}
function receiveVideo(sender) {
var options = {
remoteVideo: video,
onicecandidate: participant.onIceCandidate.bind(participant)
}
function onParticipantLeft(request) {
console.log('Participant ' + request.name + ' left');
var participant = participants[request.name];
participant.dispose();
delete participants[request.name];
}
function sendMessage(message) {
var jsonMessage = JSON.stringify(message);
console.log('Senging message: ' + jsonMessage);
ws.send(jsonMessage);
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This tutorial detects and draws faces present in the webcam video. It connects filters: KmsDetectFaces and the
KmsShowFaces.
Java - Metadata
This tutorial detects and draws faces into the webcam video. The demo connects two filters, the KmsDetectFaces and
the KmsShowFaces.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
You need to have installed the Kurento Media Server before running this example. Read the installation guide for
further information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
165
Kurento Documentation, Release 6.6.1
Note: This demo needs the kms-datachannelexample module installed in the media server. That module is available
in the Kurento repositories, so it is possible to install it with:
sudo apt-get install kms-datachannelexample
To implement this behavior we have to create a Media Pipeline composed by one WebRtcEndpoint and two filters
KmsDetectFaces and KmsShowFaces. The first one detects faces into the image and it puts the info about the face
(position and dimensions) into the buffer metadata. The second one reads the buffer metadata to find info about
detected faces. If there is info about faces, the filter draws the faces into the image.
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side, we use a Spring-Boot based server application consuming the Kurento
Java Client API, to control Kurento Media Server capabilities. All in all, the high level architecture of this demo
is three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client
and application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the
communication between the Kurento Java Client and the Kurento Media Server. This communication takes place
using the Kurento Protocol. For further information on it, please see this page of the documentation.
The following sections analyze in depth the server (Java) and client-side (JavaScript) code of this application. The
complete source code can be found in GitHub.
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vert.x, etc. Here we chose Spring Boot for convenience.
The main class of this demo is MetadataApp. As you can see, the KurentoClient is instantiated in this class as a
Spring Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities to the
application. In this instantiation we see that we need to specify to the client library the location of the Kurento Media
Server. In this example, we assume it is located at localhost, listening in port 8888. If you reproduce this example,
youll need to insert the specific location of your Kurento Media Server instance there.
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server and
controlling its multimedia capabilities.
@EnableWebSocket
@SpringBootApplication
public class MetadataApp implements WebSocketConfigurer {
@Bean
public MetadataHandler handler() {
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler(), "/metadata");
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with application server by means of requests and responses. Specifically, the main app class implements the
interface WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path
/metadata.
MetadataHandler class implements TextWebSocketHandler to handle text WebSocket requests. The central
piece of this class is the method handleTextMessage. This method implements the actions for requests, returning
responses through the WebSocket. In other words, it implements the server part of the signaling protocol depicted in
the previous sequence diagram.
In the designed protocol there are three different kinds of incoming messages to the Server : start, stop and
onIceCandidates. These messages are treated in the switch clause, taking the proper steps in each case.
@Autowired
private KurentoClient kurento;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws
Exception {
switch (jsonMessage.get("id").getAsString()) {
case "start":
start(session, jsonMessage);
break;
case "stop": {
UserSession user = users.remove(session.getId());
if (user != null) {
user.release();
}
break;
}
case "onIceCandidate": {
JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject();
jsonCandidate.get("sdpMid").getAsString(),
jsonCandidate.get("sdpMLineIndex").getAsInt());
user.addCandidate(candidate);
}
break;
}
default:
sendError(session, "Invalid message with id " + jsonMessage.get("id").
getAsString());
break;
}
}
In the following snippet, we can see the start method. It handles the ICE candidates gathering, creates a Media
Pipeline, creates the Media Elements (WebRtcEndpoint, KmsShowFaces and KmsDetectFaces) and make
the connections among them. A startResponse message is sent back to the client with the SDP answer.
private void start(final WebSocketSession session, JsonObject jsonMessage) {
try {
// User session
UserSession user = new UserSession();
MediaPipeline pipeline = kurento.createMediaPipeline();
user.setMediaPipeline(pipeline);
WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
user.setWebRtcEndpoint(webRtcEndpoint);
users.put(session.getId(), user);
// ICE candidates
webRtcEndpoint.addIceCandidateFoundListener(new EventListener
<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
// Media logic
KmsShowFaces showFaces = new KmsShowFaces.Builder(pipeline).build();
KmsDetectFaces detectFaces = new KmsDetectFaces.Builder(pipeline).build();
webRtcEndpoint.connect(detectFaces);
detectFaces.connect(showFaces);
showFaces.connect(webRtcEndpoint);
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
webRtcEndpoint.gatherCandidates();
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
The sendError method is quite simple: it sends an error message to the client when an exception is caught in the
server-side.
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we can see
the creation of the WebSocket (variable ws) in the path /metadata. Then, the onmessage listener of the Web-
Socket is used to implement the JSON signaling protocol in the client-side. Notice that there are three incoming mes-
sages to client: startResponse, error, and iceCandidate. Convenient actions are taken to implement each
step in the communication. For example, in functions start the function WebRtcPeer.WebRtcPeerSendrecv
of kurento-utils.js is used to start a WebRTC communication.
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'error':
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError("Error message from server: " + parsedMessage.message);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function(error) {
if (error) {
console.error("Error adding candidate: " + error);
return;
}
});
break;
default:
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Unrecognized message', parsedMessage);
}
}
function start() {
console.log("Starting video call ...")
// Disable start button
setState(I_AM_STARTING);
showSpinner(videoInput, videoOutput);
var options = {
localVideo : videoInput,
remoteVideo : videoOutput,
onicecandidate : onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function(error) {
if (error) {
return console.error(error);
}
webRtcPeer.generateOffer(onOffer);
});
}
function onError(error) {
console.error(error);
}
function onIceCandidate(candidate) {
console.log("Local candidate" + JSON.stringify(candidate));
var message = {
id : 'onIceCandidate',
candidate : candidate
};
sendMessage(message);
}
function startResponse(message) {
setState(I_CAN_STOP);
console.log("SDP answer received from server. Processing ...");
webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
if (error)
return console.error(error);
});
}
function stop() {
console.log("Stopping video call ...");
setState(I_CAN_START);
if (webRtcPeer) {
webRtcPeer.dispose();
webRtcPeer = null;
var message = {
id : 'stop'
}
sendMessage(message);
}
hideSpinner(videoInput, videoOutput);
}
function sendMessage(message) {
var jsonMessage = JSON.stringify(message);
console.log('Senging message: ' + jsonMessage);
ws.send(jsonMessage);
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This tutorial reads a file from disk and plays the video to WebRTC.
Java - Player
This tutorial opens a URL and plays its content to WebRTC where it is possible to choose if it plays video and audio,
only video or only audio.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
You need to have installed the Kurento Media Server before running this example. Read the installation guide for
further information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
173
Kurento Documentation, Release 6.6.1
To implement this behavior we have to create a Media Pipeline composed by one PlayerEndpoint and one WebRt-
cEndpoint. The PlayerEnpdoint plays a video and WebRtcEndpoint shows it.
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side, we use a Spring-Boot based server application consuming the Kurento
Java Client API, to control Kurento Media Server capabilities. All in all, the high level architecture of this demo
is three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client
and application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the
communication between the Kurento Java Client and the Kurento Media Server. This communication takes place
using the Kurento Protocol. For further information on it, please see this page of the documentation.
The following sections analyze in depth the server (Java) and client-side (JavaScript) code of this application. The
complete source code can be found in GitHub.
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vert.x, etc. Here we chose Spring Boot for convenience.
The main class of this demo is PlayerApp. As you can see, the KurentoClient is instantiated in this class as a Spring
Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities to the applica-
tion. In this instantiation we see that we need to specify to the client library the location of the Kurento Media Server.
In this example, we assume its located at localhost listening in port 8888. If you reproduce this example youll need
to insert the specific location of your Kurento Media Server instance there.
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server and
controlling its multimedia capabilities.
@EnableWebSocket
@SpringBootApplication
public class PlayerApp implements WebSocketConfigurer {
@Bean
public PlayerHandler handler() {
return new PlayerHandler();
}
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create(System.getProperty(KMS_WS_URI_PROP, KMS_WS_URI_
DEFAULT));
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler(), "/player");
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with application server by means of requests and responses. Specifically, the main app class implements the
interface WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path
/player.
PlayerHandler class implements TextWebSocketHandler to handle text WebSocket requests. The central piece
of this class is the method handleTextMessage. This method implements the actions for requests, returning
responses through the WebSocket. In other words, it implements the server part of the signaling protocol depicted in
the previous sequence diagram.
In the designed protocol, there are seven different kinds of incoming messages to the Server : start, stop, pause,
resume, doSeek, getPosition and onIceCandidates. These messages are treated in the switch clause,
taking the proper steps in each case.
@Autowired
private KurentoClient kurento;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws
Exception {
try {
switch (jsonMessage.get("id").getAsString()) {
case "start":
start(session, jsonMessage);
break;
case "stop":
stop(sessionId);
break;
case "pause":
pause(sessionId);
break;
case "resume":
resume(session);
break;
case "doSeek":
doSeek(session, jsonMessage);
break;
case "getPosition":
getPosition(session);
break;
case "onIceCandidate":
onIceCandidate(sessionId, jsonMessage);
break;
default:
sendError(session, "Invalid message with id " + jsonMessage.get("id").
getAsString());
break;
}
} catch (Throwable t) {
log.error("Exception handling message {} in sessionId {}", jsonMessage,
sessionId, t);
sendError(session, t.getMessage());
}
}
In the following snippet, we can see the start method. It handles the ICE candidates gathering, creates a Media
Pipeline, creates the Media Elements (WebRtcEndpoint and PlayerEndpoint) and makes the connections
between them and plays the video. A startResponse message is sent back to the client with the SDP answer.
When the MediaConnected event is received, info about the video is retrieved and sent back to the client in a
videoInfo message.
private void start(final WebSocketSession session, JsonObject jsonMessage) {
final UserSession user = new UserSession(); MediaPipeline pipeline =
kurento.createMediaPipeline(); user.setMediaPipeline(pipeline);
playerEndpoint.connect(webRtcEndpoint);
webRtcEndpoint.addMediaStateChangedListener(new
EventListener<MediaStateChangedEvent>() {
@Override public void onEvent(MediaStateChangedEvent event) {
if (event.getNewState() == MediaState.CONNECTED) {
VideoInfo videoInfo = playerEndpoint.getVideoInfo();
webRtcEndpoint.gatherCandidates();
// 3. PlayEndpoint playerEndpoint.addErrorListener(new
EventListener<ErrorEvent>() {
@Override public void onEvent(ErrorEvent event) {
log.info("ErrorEvent: {}", event.getDescription());
sendPlayEnd(session);
}
});
playerEndpoint.addEndOfStreamListener(new
EventListener<EndOfStreamEvent>() {
@Override public void onEvent(EndOfStreamEvent event) {
log.info("EndOfStreamEvent: {}", event.getTimestamp());
sendPlayEnd(session);
}
});
playerEndpoint.play();
}
The pause method retrieves the user associated to the current session, and invokes the pause method on the
PlayerEndpoint.
private void pause(String sessionId) {
UserSession user = users.get(sessionId);
if (user != null) {
user.getPlayerEndpoint().pause();
}
}
The resume method starts the PlayerEndpoint of the current user, sending back the information about the video,
so the client side can refresh the stats.
private void resume(String sessionId) {
UserSession user = users.get(session.getId());
if (user != null) {
user.getPlayerEndpoint().play(); VideoInfo videoInfo =
user.getPlayerEndpoint().getVideoInfo();
The doSeek method gets the user by sessionId, and calls the method setPosition of the PlayerEndpoint with the
new playing position. A seek message is sent back to the client if the seek fails.
private void doSeek(final WebSocketSession session, JsonObject jsonMessage) {
UserSession user = users.get(session.getId());
if (user != null) {
try {
user.getPlayerEndpoint().setPosition(jsonMessage.get("position").getAsLong());
} catch (KurentoException e) {
log.debug("The seek cannot be performed"); JsonObject response =
new JsonObject(); response.addProperty("id", "seek");
response.addProperty("message", "Seek failed"); sendMessage(session,
response.toString());
}
}
}
The getPosition calls the method getPosition of the PlayerEndpoint of the current user. A position
message is sent back to the client with the actual position of the video.
if (user != null) {
long position = user.getPlayerEndpoint().getPosition();
The stop method is quite simple: it searches the user by sessionId and stops the PlayerEndpoint. Finally, it
releases the media elements and removes the user from the list of active users.
if (user != null) {
user.release();
}
}
The sendError method is quite simple: it sends an error message to the client when an exception is caught in the
server-side.
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we can see
the creation of the WebSocket (variable ws) in the path /player. Then, the onmessage listener of the WebSocket
is used to implement the JSON signaling protocol in the client-side. Notice that there are seven incoming messages to
client: startResponse, playEnd, error, videoInfo, seek, position and iceCandidate. Convenient
actions are taken to implement each step in the communication. For example, in functions start the function
WebRtcPeer.WebRtcPeerSendrecv of kurento-utils.js is used to start a WebRTC communication.
var ws = new WebSocket('wss://' + location.host + '/player');
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'error':
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Error message from server: ' + parsedMessage.message);
break;
case 'playEnd':
playEnd();
break;
break;
case 'videoInfo':
showVideoData(parsedMessage);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function(error) {
if (error)
return console.error('Error adding candidate: ' + error);
});
break;
case 'seek':
console.log (parsedMessage.message);
break;
case 'position':
document.getElementById("videoPosition").value = parsedMessage.position;
break;
default:
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Unrecognized message', parsedMessage);
}
}
function start() {
// Disable start button
setState(I_AM_STARTING);
showSpinner(video);
video : true
}
if (mode == 'video-only') {
userMediaConstraints.audio = false;
} else if (mode == 'audio-only') {
userMediaConstraints.video = false;
}
var options = {
remoteVideo : video,
mediaConstraints : userMediaConstraints,
onicecandidate : onIceCandidate
}
var message = {
id : 'start',
sdpOffer : offerSdp,
videourl : document.getElementById('videourl').value
}
sendMessage(message);
}
function onError(error) {
console.error(error);
}
function onIceCandidate(candidate) {
console.log('Local candidate' + JSON.stringify(candidate));
var message = {
id : 'onIceCandidate',
candidate : candidate
}
sendMessage(message);
}
function startResponse(message) {
setState(I_CAN_STOP);
console.log('SDP answer received from server. Processing ...');
webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
if (error)
return console.error(error);
});
}
function pause() {
togglePause()
console.log('Pausing video ...');
var message = {
id : 'pause'
}
sendMessage(message);
}
function resume() {
togglePause()
console.log('Resuming video ...');
var message = {
id : 'resume'
}
sendMessage(message);
}
function stop() {
console.log('Stopping video ...');
setState(I_CAN_START);
if (webRtcPeer) {
webRtcPeer.dispose();
webRtcPeer = null;
var message = {
id : 'stop'
}
sendMessage(message);
}
hideSpinner(video);
}
function playEnd() {
setState(I_CAN_START);
hideSpinner(video);
}
function doSeek() {
var message = {
id : 'doSeek',
position: document.getElementById("seekPosition").value
}
sendMessage(message);
}
function getPosition() {
var message = {
id : 'getPosition'
}
sendMessage(message);
}
function showVideoData(parsedMessage) {
document.getElementById('initSeek').value = parsedMessage.initSeekable;
document.getElementById('endSeek').value = parsedMessage.endSeekable;
document.getElementById('duration').value = parsedMessage.videoDuration;
enableButton('#getPosition', 'getPosition()');
}
function sendMessage(message) {
var jsonMessage = JSON.stringify(message);
console.log('Senging message: ' + jsonMessage);
ws.send(jsonMessage);
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This tutorial injects video to a QR filter and then sends the stream to WebRTC. QR detection events are delivered by
means of WebRTC data channels, to be displayed in browser.
This tutorial connects a player with a QR code detection filter and sends output to WebRTC. Code detection events are
sent to browser using WebRTC datachannels.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
You need to have installed the Kurento Media Server before running this example. Read the installation guide for
further information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
185
Kurento Documentation, Release 6.6.1
Note: This demo needs the kms-datachannelexample module installed in the media server. That module is available
in the Kurento repositories, so it is possible to install it with:
sudo apt-get install kms-datachannelexample
To implement this behavior we have to create a Media Pipeline composed by one PlayerEndpoint, one KmsSendData
and one WebRtcEndpoint. The PlayerEnpdoint plays a video and it detects QR codes into the images. The info
about detected codes is sent through data channels (KmsSendData) from the Kurento media server to the browser
(WebRtcEndpoint). The browser shows the info in a text form.
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side, we use a Spring-Boot based server application consuming the Kurento
Java Client API, to control Kurento Media Server capabilities. All in all, the high level architecture of this demo
is three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client
and application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the
communication between the Kurento Java Client and the Kurento Media Server. This communication takes place
using the Kurento Protocol. For further information on it, please see this page of the documentation.
The following sections analyze in depth the server (Java) and client-side (JavaScript) code of this application. The
complete source code can be found in GitHub.
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vert.x, etc. Here we chose Spring Boot for convenience.
The main class of this demo is SendDataChannelApp. As you can see, the KurentoClient is instantiated in this class as
a Spring Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities to the
application. In this instantiation we see that we need to specify to the client library the location of the Kurento Media
Server. In this example, we assume it is located at localhost listening in port 8888. If you reproduce this example
youll need to insert the specific location of your Kurento Media Server instance there.
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server and
controlling its multimedia capabilities.
@EnableWebSocket
@SpringBootApplication
public class SendDataChannelApp implements WebSocketConfigurer {
@Bean
public SendDataChannelHandler handler() {
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler(), "/senddatachannel");
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with application server by means of requests and responses. Specifically, the main app class implements the
interface WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path
/senddatachannel.
SendDataChannelHandler class implements TextWebSocketHandler to handle text WebSocket requests. The
central piece of this class is the method handleTextMessage. This method implements the actions for requests,
returning responses through the WebSocket. In other words, it implements the server part of the signaling protocol
depicted in the previous sequence diagram.
In the designed protocol there are three different kinds of incoming messages to the Server : start, stop and
onIceCandidates. These messages are treated in the switch clause, taking the proper steps in each case.
@Autowired
private KurentoClient kurento;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws
Exception {
switch (jsonMessage.get("id").getAsString()) {
case "start":
start(session, jsonMessage);
break;
case "stop": {
UserSession user = users.remove(session.getId());
if (user != null) {
user.release();
}
break;
}
case "onIceCandidate": {
JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject();
jsonCandidate.get("sdpMid").getAsString(),
jsonCandidate.get("sdpMLineIndex").getAsInt());
user.addCandidate(candidate);
}
break;
}
default:
sendError(session, "Invalid message with id " + jsonMessage.get("id").
getAsString());
break;
}
}
In the following snippet, we can see the start method. It handles the ICE candidates gathering, creates a Media
Pipeline, creates the Media Elements (WebRtcEndpoint, KmsSendData and PlayerEndpoint) and make the
connections among them. A startResponse message is sent back to the client with the SDP answer.
private void start(final WebSocketSession session, JsonObject jsonMessage) {
try {
// User session
UserSession user = new UserSession();
MediaPipeline pipeline = kurento.createMediaPipeline();
user.setMediaPipeline(pipeline);
WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).
useDataChannels()
.build();
user.setWebRtcEndpoint(webRtcEndpoint);
PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline,
"http://files.kurento.org/video/filter/barcodes.webm").build();
user.setPlayer(player);
users.put(session.getId(), user);
// ICE candidates
webRtcEndpoint.addIceCandidateFoundListener(new EventListener
<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
// Media logic
KmsSendData kmsSendData = new KmsSendData.Builder(pipeline).build();
player.connect(kmsSendData);
kmsSendData.connect(webRtcEndpoint);
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
webRtcEndpoint.gatherCandidates();
player.play();
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
The sendError method is quite simple: it sends an error message to the client when an exception is caught in the
server-side.
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we
can see the creation of the WebSocket (variable ws) in the path /senddatachannel. Then, the onmessage
listener of the WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there
are three incoming messages to client: startResponse, error, and iceCandidate. Convenient actions are
taken to implement each step in the communication. For example, in functions start the function WebRtcPeer.
WebRtcPeerSendrecv of kurento-utils.js is used to start a WebRTC communication.
var ws = new WebSocket('wss://' + location.host + '/senddatachannel');
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'error':
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError("Error message from server: " + parsedMessage.message);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function(error) {
if (error) {
console.error("Error adding candidate: " + error);
return;
}
});
break;
default:
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Unrecognized message', parsedMessage);
}
}
function start() {
console.log("Starting video call ...")
// Disable start button
setState(I_AM_STARTING);
showSpinner(videoOutput);
console.log("Creating channel");
var dataConstraints = null;
channel.onmessage = onMessage;
var options = {
peerConnection: peerConnection,
remoteVideo : videoOutput,
onicecandidate : onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options,
function(error) {
if (error) {
return console.error(error);
}
webRtcPeer.generateOffer(onOffer);
});
}
function closeChannels(){
if(channel){
channel.close();
$('#dataChannelSend').disabled = true;
$('#send').attr('disabled', true);
channel = null;
}
}
function onError(error) {
console.error(error);
}
function onIceCandidate(candidate) {
console.log("Local candidate" + JSON.stringify(candidate));
var message = {
id : 'onIceCandidate',
candidate : candidate
};
sendMessage(message);
}
function startResponse(message) {
setState(I_CAN_STOP);
console.log("SDP answer received from server. Processing ...");
webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
if (error)
return console.error(error);
});
}
function stop() {
console.log("Stopping video call ...");
setState(I_CAN_START);
if (webRtcPeer) {
closeChannels();
webRtcPeer.dispose();
webRtcPeer = null;
var message = {
id : 'stop'
}
sendMessage(message);
}
hideSpinner(videoOutput);
}
function sendMessage(message) {
var jsonMessage = JSON.stringify(message);
console.log('Senging message: ' + jsonMessage);
ws.send(jsonMessage);
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This tutorial shows how text messages sent from browser can be delivered by data channels, to be displayed together
with loopback video.
This demo allows sending text from browser to the media server through data channels. That text will be shown in the
loopback video.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
You need to have installed the Kurento Media Server before running this example. Read the installation guide for
further information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
195
Kurento Documentation, Release 6.6.1
Note: This demo needs the kms-datachannelexample module installed in the media server. That module is available
in the Kurento repositories, so it is possible to install it with:
sudo apt-get install kms-datachannelexample
This tutorial creates a Media Pipeline consisting of media elements: WebRtcEndpoint and KmsSendData. Any text
inserted in the textbox is sent from Kurento Media Server (KmsSendData) back to browser (WebRtcEndpoint) and
shown with loopback video.
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side, we use a Spring-Boot based server application consuming the Kurento
Java Client API, to control Kurento Media Server capabilities. All in all, the high level architecture of this demo
is three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client
and application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the
communication between the Kurento Java Client and the Kurento Media Server. This communication takes place
using the Kurento Protocol. For further information on it, please see this page of the documentation.
The following sections analyze in depth the server (Java) and client-side (JavaScript) code of this application. The
complete source code can be found in GitHub.
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vert.x, etc. Here we chose Spring Boot for convenience.
The main class of this demo is ShowDataChannelApp. As you can see, the KurentoClient is instantiated in this class as
a Spring Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities to the
application. In this instantiation we see that we need to specify to the client library the location of the Kurento Media
Server. In this example, we assume its located at localhost listening in port 8888. If you reproduce this example
youll need to insert the specific location of your Kurento Media Server instance there.
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server and
controlling its multimedia capabilities.
@EnableWebSocket
@SpringBootApplication
public class ShowDataChannelApp implements WebSocketConfigurer {
@Bean
public ShowDataChannelHandler handler() {
return new ShowDataChannelHandler();
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler(), "/showdatachannel");
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with application server by means of requests and responses. Specifically, the main app class implements the
interface WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path
/showdatachannel.
ShowDataChannelHandler class implements TextWebSocketHandler to handle text WebSocket requests. The
central piece of this class is the method handleTextMessage. This method implements the actions for requests,
returning responses through the WebSocket. In other words, it implements the server part of the signaling protocol
depicted in the previous sequence diagram.
In the designed protocol there are three different kinds of incoming messages to the Server : start, stop and
onIceCandidates. These messages are treated in the switch clause, taking the proper steps in each case.
@Autowired
private KurentoClient kurento;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws
Exception {
switch (jsonMessage.get("id").getAsString()) {
case "start":
start(session, jsonMessage);
break;
case "stop": {
UserSession user = users.remove(session.getId());
if (user != null) {
user.release();
}
break;
}
case "onIceCandidate": {
JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject();
jsonCandidate.get("sdpMid").getAsString(),
jsonCandidate.get("sdpMLineIndex").getAsInt());
user.addCandidate(candidate);
}
break;
}
default:
sendError(session, "Invalid message with id " + jsonMessage.get("id").
getAsString());
break;
}
}
Following snippet shows method start, where ICE candidates are gathered and Media Pipeline and Media Elements
(WebRtcEndpoint and KmsSendData) are created and connected. Message startResponse is sent back to
client carrying the SDP answer.
private void start(final WebSocketSession session, JsonObject jsonMessage) {
try {
// User session
UserSession user = new UserSession();
MediaPipeline pipeline = kurento.createMediaPipeline();
user.setMediaPipeline(pipeline);
WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).
useDataChannels()
.build();
user.setWebRtcEndpoint(webRtcEndpoint);
users.put(session.getId(), user);
// ICE candidates
webRtcEndpoint.addIceCandidateFoundListener(new EventListener
<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
// Media logic
KmsShowData kmsShowData = new KmsShowData.Builder(pipeline).build();
webRtcEndpoint.connect(kmsShowData);
kmsShowData.connect(webRtcEndpoint);
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
webRtcEndpoint.gatherCandidates();
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
The sendError method is quite simple: it sends an error message to the client when an exception is caught in the
server-side.
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we
can see the creation of the WebSocket (variable ws) in the path /showdatachannel. Then, the onmessage
listener of the WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there
are three incoming messages to client: startResponse, error, and iceCandidate. Convenient actions are
taken to implement each step in the communication. For example, in functions start the function WebRtcPeer.
WebRtcPeerSendrecv of kurento-utils.js is used to start a WebRTC communication.
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'error':
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError("Error message from server: " + parsedMessage.message);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function(error) {
if (error) {
console.error("Error adding candidate: " + error);
return;
}
});
break;
default:
if (state == I_AM_STARTING) {
setState(I_CAN_START);
}
onError('Unrecognized message', parsedMessage);
}
}
function start() {
console.log("Starting video call ...")
// Disable start button
setState(I_AM_STARTING);
showSpinner(videoInput, videoOutput);
console.log("Creating channel");
var dataConstraints = null;
channel.onopen = onSendChannelStateChange;
channel.onclose = onSendChannelStateChange;
function onSendChannelStateChange(){
if(!channel) return;
var readyState = channel.readyState;
console.log("sencChannel state changed to " + readyState);
if(readyState == 'open'){
dataChannelSend.disabled = false;
dataChannelSend.focus();
$('#send').attr('disabled', false);
} else {
dataChannelSend.disabled = true;
$('#send').attr('disabled', true);
}
}
sendButton.addEventListener("click", function(){
var data = dataChannelSend.value;
console.log("Send button pressed. Sending data " + data);
channel.send(data);
dataChannelSend.value = "";
});
var options = {
peerConnection: peerConnection,
localVideo : videoInput,
remoteVideo : videoOutput,
onicecandidate : onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function(error) {
if (error) {
return console.error(error);
}
webRtcPeer.generateOffer(onOffer);
});
}
function closeChannels(){
if(channel){
channel.close();
$('#dataChannelSend').disabled = true;
$('#send').attr('disabled', true);
channel = null;
}
}
function onError(error) {
console.error(error);
}
function onIceCandidate(candidate) {
console.log("Local candidate" + JSON.stringify(candidate));
var message = {
id : 'onIceCandidate',
candidate : candidate
};
sendMessage(message);
}
function startResponse(message) {
setState(I_CAN_STOP);
console.log("SDP answer received from server. Processing ...");
webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
if (error)
return console.error(error);
});
}
function stop() {
console.log("Stopping video call ...");
setState(I_CAN_START);
if (webRtcPeer) {
closeChannels();
webRtcPeer.dispose();
webRtcPeer = null;
var message = {
id : 'stop'
}
sendMessage(message);
}
hideSpinner(videoInput, videoOutput);
}
function sendMessage(message) {
var jsonMessage = JSON.stringify(message);
console.log('Senging message: ' + jsonMessage);
ws.send(jsonMessage);
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This web application extends the Hello World Tutorial, adding media processing to the basic WebRTC loopback and
allowing send text from browser to the media server through data channels.
Youll need to install Kurento Media Server before running this example. Read installation guide for further informa-
tion.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
Due to Same-origin policy, this demo has to be served by an HTTP server. A very simple way of doing this is by
means of an HTTP Node.js server which can be installed using npm :
You also need the source code of this demo. You can clone it from GitHub. Then start the HTTP server:
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the parameter ws_uri to the
URL, as follows:
https://localhost:8443/index.html?ws_uri=wss://kms_host:kms_port/kurento
Notice that the Kurento Media Server must connected using a Secure WebSocket (i.e., the KMS URI starts with
wss:// ). For this reason, the support for secure WebSocket must be enabled in the Kurento Media Server you are using
to run this tutorial. For further information about securing applications, please visit the following page.
Note: This demo needs the kms-datachannelexample module installed in the media server. That module is available
in the Kurento repositories, so it is possible to install it with:
The logic of the application is quite simple: the local stream is sent to Kurento Media Server, which returns it back to
the client without modifications. To implement this behavior we need to create a Media Pipeline with a single Media
Element, i.e. of type WebRtcEndpoint, which holds the capability of exchanging full-duplex (bidirectional) WebRTC
media flows. It is important to set value of property useDataChannels to true during WebRtcEndpoint creation. This
media element is connected to itself in order to deliver back received Media.
The application creates a channel between PeerConnection and WebRtcEndpoint used for message delivery.
Complete source code of this demo can be found in GitHub.
JavaScript Logic
This demo follows a Single Page Application architecture (SPA). The interface is the following HTML page: in-
dex.html. This web page links two Kurento JavaScript libraries:
startButton.addEventListener("click", function() {
var options = {
peerConnection: peerConnection,
localVideo: videoInput,
remoteVideo: videoOutput
};
[...]
}
The function WebRtcPeer.WebRtcPeerSendrecv abstracts the WebRTC internal details (i.e. PeerConnection and ge-
tUserStream) and makes possible to start a full-duplex WebRTC communication, using the HTML video tag with id
videoInput to show the video camera (local stream) and the video tag videoOutput to show the remote stream provided
by the Kurento Media Server.
Inside this function, a call to generateOffer is performed. This function accepts a callback in which the SDP offer is
received. In this callback we create an instance of the KurentoClient class that will manage communications with the
Kurento Media Server. So, we need to provide the URI of its WebSocket endpoint. In this example, we assume its
listening in port 8433 at the same host than the HTTP serving the application.
[...]
[...]
[...]
};
Once we have an instance of kurentoClient, the following step is to create a Media Pipeline, as follows:
If everything works correctly, we have an instance of a media pipeline (variable pipeline in this example).
With this instance, we are able to create Media Elements. In this example we just need a WebRtcEndpoint with
useDataChannels property as true. Then, this media elements is connected itself:
webRtc.gatherCandidates(onError);
webRtcPeer.processAnswer(sdpAnswer, onError);
});
webRtc.connect(webRtc, function(error){
if(error) return onError(error);
console.log("Loopback established");
});
});
In the following snippet, we can see how to create the channel and the send method of one channel.
sendButton.addEventListener("click", function(){
...
channel.send(data);
...
});
Note: The TURN and STUN servers to be used can be configured simple adding the parameter ice_servers to
the application URL, as follows:
https://localhost:8443/index.html?ice_servers=[{"urls":"stun:stun1.example.net"},{
"urls":"stun:stun2.example.net"}]
https://localhost:8443/index.html?ice_servers=[{"urls":"turn:turn.example.org",
"username":"user","credential":"myPassword"}]
Dependencies
Demo dependencies are defined in file bower.json. They are managed using Bower.
"dependencies": {
"kurento-client": "6.6.0",
"kurento-utils": "6.6.2"
}
Note: We are in active development. You can find the latest version of Kurento JavaScript Client at Bower.
WebRTC recording
This tutorial has two parts. First, it implements a WebRTC loopback and records the stream to disk. Second, it plays
back the recorded stream. Users can choose which type of media to send and record: audio, video or both.
Java - Recorder
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
You need to have installed the Kurento Media Server before running this example. Read the installation guide for
further information.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
209
Kurento Documentation, Release 6.6.1
In the first part of this tutorial, the local stream is sent to the media server, which in turn sends it back to the client,
while recording it at the same time. In order to implement this behavior, we need to create a Media Pipeline consisting
on a WebRtcEndpoint and a RecorderEnpoint.
The second part of this demo shows how to play recorded media. To achieve this, we need to create a Media Pipeline
composed by a WebRtcEndpoint and a PlayerEndpoint. The uri property of the player is the uri of the recorded file.
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side, we use a Spring-Boot based server application consuming the Kurento
Java Client API, to control Kurento Media Server capabilities. All in all, the high level architecture of this demo
is three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client
and application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the
communication between the Kurento Java Client and the Kurento Media Server. This communication takes place
using the Kurento Protocol. For further information on it, please see this page of the documentation.
The following sections analyze in depth the server (Java) and client-side (JavaScript) code of this application. The
complete source code can be found in GitHub.
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vert.x, etc. Here we chose Spring Boot for convenience.
The main class of this demo is HelloWorldRecApp. As you can see, the KurentoClient is instantiated in this class as a
Spring Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities to the
application. In this instantiation we see that we need to specify to the client library the location of the Kurento Media
Server. In this example, we assume it is located at localhost listening in port 8888. If you reproduce this example
youll need to insert the specific location of your Kurento Media Server instance there.
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server and
controlling its multimedia capabilities.
@SpringBootApplication
@EnableWebSocket
public class HelloWorldRecApp implements WebSocketConfigurer {
@Bean
public HelloWorldRecHandler handler() {
return new HelloWorldRecHandler();
}
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler(), "/recording");
}
@Bean
public UserRegistry registry() {
return new UserRegistry();
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with application server by means of requests and responses. Specifically, the main app class implements the
interface WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path
/recording.
HelloWorldRecHandler class implements TextWebSocketHandler to handle text WebSocket requests. The cen-
tral piece of this class is the method handleTextMessage. This method implements the actions for requests,
returning responses through the WebSocket. In other words, it implements the server part of the signaling protocol
depicted in the previous sequence diagram.
In the designed protocol there are three different kinds of incoming messages to the Server : start, stop , play
and onIceCandidates. These messages are treated in the switch clause, taking the proper steps in each case.
@Autowired
private UserRegistry registry;
@Autowired
private KurentoClient kurento;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws
Exception {
switch (jsonMessage.get("id").getAsString()) {
case "start":
start(session, jsonMessage);
break;
case "stop":
case "stopPlay":
if (user != null) {
user.release();
}
break;
case "play":
play(user, session, jsonMessage);
break;
case "onIceCandidate": {
JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject();
if (user != null) {
IceCandidate candidate = new IceCandidate(jsonCandidate.get("candidate").
getAsString(),
jsonCandidate.get("sdpMid").getAsString(),
jsonCandidate.get("sdpMLineIndex").getAsInt());
user.addCandidate(candidate);
}
break;
}
default:
sendError(session, "Invalid message with id " + jsonMessage.get("id").
getAsString());
break;
}
}
In the following snippet, we can see the start method. It handles the ICE candidates gathering, creates a Media
Pipeline, creates the Media Elements (WebRtcEndpoint and RecorderEndpoint) and make the connections
among them. A startResponse message is sent back to the client with the SDP answer.
private void start(final WebSocketSession session, JsonObject jsonMessage) {
try {
// 3. SDP negotiation
String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
});
synchronized (user) {
session.sendMessage(new TextMessage(response.toString()));
}
webRtcEndpoint.gatherCandidates();
recorder.record();
} catch (Throwable t) {
log.error("Start error", t);
sendError(session, t.getMessage());
}
}
The play method, creates a Media Pipeline with the Media Elements (WebRtcEndpoint and PlayerEndpoint)
and make the connections among them. It will then send the recorded media to the client.
private void play(UserSession user, final WebSocketSession session, JsonObject
jsonMessage) {
try {
// 1. Media logic
final MediaPipeline pipeline = kurento.createMediaPipeline();
WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, RECORDER_FILE_
PATH).build();
player.connect(webRtcEndpoint);
// Player listeners
player.addErrorListener(new EventListener<ErrorEvent>() {
@Override
public void onEvent(ErrorEvent event) {
log.info("ErrorEvent for session '{}': {}", session.getId(), event.
getDescription());
sendPlayEnd(session, pipeline);
}
});
player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
@Override
public void onEvent(EndOfStreamEvent event) {
log.info("EndOfStreamEvent for session '{}'", session.getId());
sendPlayEnd(session, pipeline);
}
});
// 3. SDP negotiation
String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
});
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
webRtcEndpoint.gatherCandidates();
} catch (Throwable t) {
log.error("Play error", t);
sendError(session, t.getMessage());
}
}
The sendError method is quite simple: it sends an error message to the client when an exception is caught in the
server-side.
private void sendError(WebSocketSession session, String message) {
try {
JsonObject response = new JsonObject();
response.addProperty("id", "error");
response.addProperty("message", message);
session.sendMessage(new TextMessage(response.toString()));
} catch (IOException e) {
log.error("Exception sending message", e);
}
}
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we can
see the creation of the WebSocket (variable ws) in the path /recording. Then, the onmessage listener of the
WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there are three incoming
messages to client: startResponse, playResponse, playEnd,error, and iceCandidate. Convenient
actions are taken to implement each step in the communication. For example, in functions start the function
WebRtcPeer.WebRtcPeerSendrecv of kurento-utils.js is used to start a WebRTC communication.
var ws = new WebSocket('wss://' + location.host + '/recording');
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'playResponse':
playResponse(parsedMessage);
break;
case 'playEnd':
playEnd();
break;
case 'error':
setState(NO_CALL);
onError('Error message from server: ' + parsedMessage.message);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function(error) {
if (error)
return console.error('Error adding candidate: ' + error);
});
break;
default:
setState(NO_CALL);
onError('Unrecognized message', parsedMessage);
}
}
function start() {
console.log('Starting video call ...');
var options = {
localVideo : videoInput,
remoteVideo : videoOutput,
mediaConstraints : getConstraints(),
onicecandidate : onIceCandidate
}
function onError(error) {
console.error(error);
}
function onIceCandidate(candidate) {
console.log('Local candidate' + JSON.stringify(candidate));
var message = {
id : 'onIceCandidate',
candidate : candidate
};
sendMessage(message);
}
function startResponse(message) {
setState(IN_CALL);
console.log('SDP answer received from server. Processing ...');
webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
if (error)
return console.error(error);
});
}
function stop() {
var stopMessageId = (state == IN_CALL) ? 'stop' : 'stopPlay';
console.log('Stopping video while in ' + state + '...');
setState(POST_CALL);
if (webRtcPeer) {
webRtcPeer.dispose();
webRtcPeer = null;
var message = {
id : stopMessageId
}
sendMessage(message);
}
hideSpinner(videoInput, videoOutput);
}
function play() {
console.log("Starting to play recorded video...");
var options = {
remoteVideo : videoOutput,
mediaConstraints : getConstraints(),
onicecandidate : onIceCandidate
}
if (error)
return console.error('Error generating the offer');
console.info('Invoking SDP offer callback function ' + location.host);
var message = {
id : 'play',
sdpOffer : offerSdp
}
sendMessage(message);
}
function getConstraints() {
var mode = $('input[name="mode"]:checked').val();
var constraints = {
audio : true,
video : true
}
if (mode == 'video-only') {
constraints.audio = false;
} else if (mode == 'audio-only') {
constraints.video = false;
}
return constraints;
}
function playResponse(message) {
setState(IN_PLAY);
webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
if (error)
return console.error(error);
});
}
function playEnd() {
setState(POST_CALL);
hideSpinner(videoInput, videoOutput);
}
function sendMessage(message) {
var jsonMessage = JSON.stringify(message);
console.log('Senging message: ' + jsonMessage);
ws.send(jsonMessage);
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
JavaScript - Recorder
This web application extends the Hello World Tutorial, adding recording capabilities.
Youll need to install Kurento Media Server before running this example. Read installation guide for further informa-
tion.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
Due to Same-origin policy, this demo has to be served by an HTTP server. A very simple way of doing this is by
means of an HTTP Node.js server which can be installed using npm :
You will need to download the source code form GitHub. There are two implementations of this tutorial, but they are
functionally the same. Its just the internal implementation that changes. After checking out the code, you can start
the web server.
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the parameter ws_uri to the
URL, as follows:
https://localhost:8443/index.html?ws_uri=wss://kms_host:kms_port/kurento
Notice that the Kurento Media Server must connected using a Secure WebSocket (i.e., the KMS URI starts with
wss:// ). For this reason, the support for secure WebSocket must be enabled in the Kurento Media Server you are using
to run this tutorial. For further information about securing applications, please visit the following page.
In the first part of this demo, the local stream is sent to Kurento Media Server, which returns it back to the client and
records to the same time. In order to implement this behavior we need to create aMedia Pipeline:term: consisting of
a WebRtcEndpoint and a RecorderEnpoint.
The second part of this demo shows how to play recorded media. To achieve this, we need to create a Media Pipeline
composed by a WebRtcEndpoint and a PlayerEndpoint. The uri property of the player is the uri of the recorded file.
There are two implementations for this demo to be found in github:
Using callbacks.
Using yield.
JavaScript Logic
This demo follows a Single Page Application architecture (SPA). The interface is the following HTML page: in-
dex.html. This web page links two Kurento JavaScript libraries:
kurento-client.js : Implementation of the Kurento JavaScript Client.
kurento-utils.js : Kurento utility library aimed to simplify the WebRTC management in the browser.
In addition, these two JavaScript libraries are also required:
Bootstrap : Web framework for developing responsive web sites.
jquery.js : Cross-platform JavaScript library designed to simplify the client-side scripting of HTML.
adapter.js : WebRTC JavaScript utility library maintained by Google that abstracts away browser differences.
ekko-lightbox : Module for Bootstrap to open modal images, videos, and galleries.
demo-console : Custom JavaScript console.
The specific logic of this demo is coded in the following JavaScript page: index.js. In this file, there is a function
which is called when the green button, labeled as Start in the GUI, is clicked.
startRecordButton.addEventListener("click", startRecording);
function startRecording() {
var options = {
localVideo: videoInput,
remoteVideo: videoOutput
};
[...]
}
The function WebRtcPeer.WebRtcPeerSendrecv abstracts the WebRTC internal details (i.e. PeerConnection and ge-
tUserStream) and makes possible to start a full-duplex WebRTC communication, using the HTML video tag with id
videoInput to show the video camera (local stream) and the video tag videoOutput to show the remote stream provided
by the Kurento Media Server.
Inside this function, a call to generateOffer is performed. This function accepts a callback in which the SDP offer is
received. In this callback we create an instance of the KurentoClient class that will manage communications with the
Kurento Media Server. So, we need to provide the URI of its WebSocket endpoint. In this example, we assume its
listening in port 8433 at the same host than the HTTP serving the application.
[...]
default:
{
ws_uri: 'wss://' + location.hostname + ':8433/kurento',
file_uri: 'file:///tmp/recorder_demo.webm', // file to be stored in media server
ice_servers: undefined
}
});
[...]
Once we have an instance of kurentoClient, the following step is to create a Media Pipeline, as follows:
client.create("MediaPipeline", function(error, _pipeline){
[...]
});
If everything works correctly, we have an instance of a media pipeline (variable pipeline in this example). With this
instance, we are able to create Media Elements. In this example we just need a WebRtcEndpoint and a RecorderEnd-
point. Then, these media elements are interconnected:
var elements =
[
{type: 'RecorderEndpoint', params: {uri : args.file_uri}},
{type: 'WebRtcEndpoint', params: {}}
]
console.log("offer");
webRtc.gatherCandidates(onError);
webRtcPeer.processAnswer(answer);
});
console.log("Connected");
recorder.record(function(error) {
if (error) return onError(error);
console.log("record");
});
});
});
When stop button is clicked, the recoder element stops to record, and all elements are released.
stopRecordButton.addEventListener("click", function(event){
recorder.stop();
pipeline.release();
webRtcPeer.dispose();
videoInput.src = "";
videoOutput.src = "";
hideSpinner(videoInput, videoOutput);
In the second part, after play button is clicked, we have an instance of a media pipeline (variable pipeline in this
example). With this instance, we are able to create Media Elements. In this example we just need a WebRtcEndpoint
and a PlayerEndpoint with uri option like path where the media was recorded. Then, these media elements are
interconnected:
player.on('EndOfStream', function(event){
pipeline.release();
videoPlayer.src = "";
hideSpinner(videoPlayer);
});
player.connect(webRtc, function(error) {
if (error) return onError(error);
player.play(function(error) {
if (error) return onError(error);
console.log("Playing ...");
});
});
});
Note: The TURN and STUN servers to be used can be configured simple adding the parameter ice_servers to
the application URL, as follows:
https://localhost:8443/index.html?ice_servers=[{"urls":"stun:stun1.example.net"},{
"urls":"stun:stun2.example.net"}]
https://localhost:8443/index.html?ice_servers=[{"urls":"turn:turn.example.org",
"username":"user","credential":"myPassword"}]
Dependencies
Demo dependencies are located in file bower.json. Bower is used to collect them.
"dependencies": {
"kurento-client": "6.6.0",
"kurento-utils": "6.6.2"
}
Note: We are in active development. You can find the latest version of Kurento JavaScript Client at Bower.
WebRTC repository
This is similar to the recording tutorial, but using the repository to store metadata.
Java - Repository
This web application extends Hello World adding recording capabilities by means of the Kurento Repository.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
You need to have installed the Kurento Media Server before running this example. Read the installation guide for
further information.
In addition, you also need the kurento-repository-server. This component is in charge of the storage and retrieval of
the media. Please visit the Kurento Repository Server installation guide for further details.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
Access the application connecting to the URL https://localhost:8443/ in a WebRTC capable browser (Chrome, Fire-
fox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
225
Kurento Documentation, Release 6.6.1
executing the demo. In addition, by default this demo is also suppossing that the Kurento Repository is up and running
in the localhost. It can be changed by means of the property repository.uri. All in all, and due to the fact that
we can use Maven to run the tutorial, you should execute the following command:
mvn compile exec:java -Dkms.url=ws://kms_host:kms_port/kurento \
-Drepository.uri=http://repository_host:repository_url
On top of the recording capabilities from the base tutorial, this application creates a repository element to store media
in that repository. Additionally, metadata about the recorded file can be also stored in the repository.
This is a web application, and therefore it follows a client-server architecture. At the client-side, the logic is imple-
mented in JavaScript. At the server-side, we use a Spring-Boot based server application consuming the Kurento
Java Client API, to control Kurento Media Server capabilities. All in all, the high level architecture of this demo
is three-tier. To communicate these entities, two WebSockets are used. First, a WebSocket is created between client
and application server to implement a custom signaling protocol. Second, another WebSocket is used to perform the
communication between the Kurento Java Client and the Kurento Media Server. This communication takes place
using the Kurento Protocol. For further information on it, please see this page of the documentation.
The following sections analyze in deep the server (Java) and client-side (JavaScript) code of this application. The
complete source code can be found in GitHub.
This demo has been developed using Java in the server-side, based on the Spring Boot framework, which embeds a
Tomcat web server within the generated maven artifact, and thus simplifies the development and deployment process.
Note: You can use whatever Java server side technology you prefer to build web applications with Kurento. For
example, a pure Java EE application, SIP Servlets, Play, Vert.x, etc. Here we chose Spring Boot for convenience.
The main class of this demo is HelloWorldRecApp. As you can see, the KurentoClient is instantiated in this class as a
Spring Bean. This bean is used to create Kurento Media Pipelines, which are used to add media capabilities to the
application. In this instantiation we see that we need to specify to the client library the location of the Kurento Media
Server. In this example, we assume it is located at localhost listening in port 8888. If you reproduce this example
youll need to insert the specific location of your Kurento Media Server instance there.
Once the Kurento Client has been instantiated, you are ready for communicating with Kurento Media Server and
controlling its multimedia capabilities.
@SpringBootApplication
@EnableWebSocket
public class HelloWorldRecApp implements WebSocketConfigurer {
@Bean
public HelloWorldRecHandler handler() {
return new HelloWorldRecHandler();
@Bean
public KurentoClient kurentoClient() {
return KurentoClient.create();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler(), "/repository");
}
@Bean
public RepositoryClient repositoryServiceProvider() {
return REPOSITORY_SERVER_URI.startsWith("file://") ? null
: RepositoryClientProvider.create(REPOSITORY_SERVER_URI);
}
@Bean
public UserRegistry registry() {
return new UserRegistry();
}
This web application follows a Single Page Application architecture (SPA), and uses a WebSocket to communicate
client with application server by means of requests and responses. Specifically, the main app class implements the
interface WebSocketConfigurer to register a WebSocketHanlder to process WebSocket requests in the path
/repository.
HelloWorldRecHandler class implements TextWebSocketHandler to handle text WebSocket requests. The cen-
tral piece of this class is the method handleTextMessage. This method implements the actions for requests,
returning responses through the WebSocket. In other words, it implements the server part of the signaling protocol
depicted in the previous sequence diagram.
In the designed protocol there are three different kinds of incoming messages to the Server : start, stop,
stopPlay, play and onIceCandidates. These messages are treated in the switch clause, taking the proper
steps in each case.
@Autowired
private UserRegistry registry;
@Autowired
@Autowired
private RepositoryClient repositoryClient;
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws
Exception {
switch (jsonMessage.get("id").getAsString()) {
case "start":
start(session, jsonMessage);
break;
case "stop":
case "stopPlay":
if (user != null) {
user.release();
}
break;
case "play":
play(user, session, jsonMessage);
break;
case "onIceCandidate": {
JsonObject jsonCandidate = jsonMessage.get("candidate").getAsJsonObject();
if (user != null) {
IceCandidate candidate = new IceCandidate(jsonCandidate.get("candidate").
getAsString(),
jsonCandidate.get("sdpMid").getAsString(),
jsonCandidate.get("sdpMLineIndex").getAsInt());
user.addCandidate(candidate);
}
break;
}
default:
sendError(session, "Invalid message with id " + jsonMessage.get("id").
getAsString());
break;
}
}
In the following snippet, we can see the start method. If a repository REST client or interface has been created, it
will obtain a RepositoryItem from the remote service. This item contains an ID and a recording URI that will be used
by the Kurento Media Server. The ID will be used after the recording ends in order to manage the stored media. If the
client doesnt exist, the recording will be performed to a local URI, on the same machine as the KMS. This method also
deals with the ICE candidates gathering, creates a Media Pipeline, creates the Media Elements (WebRtcEndpoint
and RecorderEndpoint) and makes the connections between them. A startResponse message is sent back
to the client with the SDP answer.
.withMediaProfile(MediaProfileSpecType.WEBM).build();
webRtcEndpoint.connect(recorder);
// 3. SDP negotiation
String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
The play method, creates a Media Pipeline with the Media Elements (WebRtcEndpoint and PlayerEndpoint)
and make the connections between them. It will then send the recorded media to the client. The media can be served
from the repository or directly from the disk. If the repository interface exists, it will try to connect to the remote
service in order to obtain an URI from which the KMS will read the media streams. The inner workings of the
repository restrict reading an item before it has been closed (after the upload finished). This will happen only when
a certain number of seconds elapse after the last byte of media is uploaded by the KMS (safe-guard for gaps in the
network communications).
try {
// 0. Repository logic
RepositoryItemPlayer itemPlayer = null;
if (repositoryClient != null) {
try {
Date stopTimestamp = user.getStopTimestamp();
if (stopTimestamp != null) {
Date now = new Date();
long diff = now.getTime() - stopTimestamp.getTime();
if (diff >= 0 && diff < REPOSITORY_DISCONNECT_TIMEOUT) {
log.info(
"Waiting for {}ms before requesting the repository read endpoint "
+ "(requires {}ms before upload is considered terminated "
+ "and only {}ms have passed)",
REPOSITORY_DISCONNECT_TIMEOUT - diff, REPOSITORY_DISCONNECT_TIMEOUT,
diff);
Thread.sleep(REPOSITORY_DISCONNECT_TIMEOUT - diff);
}
} else {
log.warn("No stop timeout was found, repository endpoint might not be
ready");
}
itemPlayer = repositoryClient.getReadEndpoint(user.getRepoItem().getId());
} catch (Exception e) {
log.warn("Unable to obtain kurento repository endpoint", e);
}
} else {
itemPlayer = new RepositoryItemPlayer();
itemPlayer.setId(user.getRepoItem().getId());
itemPlayer.setUrl(user.getRepoItem().getUrl());
}
log.debug("Playing from {}: id={}, url={}",
(repositoryClient == null ? "disk" : "repository"), itemPlayer.getId(),
itemPlayer.getUrl());
// 1. Media logic
final MediaPipeline pipeline = kurento.createMediaPipeline();
WebRtcEndpoint webRtcEndpoint = new WebRtcEndpoint.Builder(pipeline).build();
PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, itemPlayer.
getUrl()).build();
player.connect(webRtcEndpoint);
// Player listeners
player.addErrorListener(new EventListener<ErrorEvent>() {
@Override
public void onEvent(ErrorEvent event) {
log.info("ErrorEvent for session '{}': {}", session.getId(), event.
getDescription());
sendPlayEnd(session, pipeline);
}
});
player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
@Override
public void onEvent(EndOfStreamEvent event) {
log.info("EndOfStreamEvent for session '{}'", session.getId());
sendPlayEnd(session, pipeline);
}
});
// 3. SDP negotiation
String sdpOffer = jsonMessage.get("sdpOffer").getAsString();
String sdpAnswer = webRtcEndpoint.processOffer(sdpOffer);
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
} catch (IOException e) {
log.error(e.getMessage());
}
}
});
The sendError method is quite simple: it sends an error message to the client when an exception is caught in the
server-side.
private void sendError(WebSocketSession session, String message) {
try {
JsonObject response = new JsonObject();
response.addProperty("id", "error");
response.addProperty("message", message);
session.sendMessage(new TextMessage(response.toString()));
} catch (IOException e) {
log.error("Exception sending message", e);
}
}
Client-Side Logic
Lets move now to the client-side of the application. To call the previously created WebSocket service in the server-
side, we use the JavaScript class WebSocket. We use a specific Kurento JavaScript library called kurento-utils.js
to simplify the WebRTC interaction with the server. This library depends on adapter.js, which is a JavaScript We-
bRTC utility maintained by Google that abstracts away browser differences. Finally jquery.js is also needed in this
application.
These libraries are linked in the index.html web page, and are used in the index.js. In the following snippet we can
see the creation of the WebSocket (variable ws) in the path /repository. Then, the onmessage listener of the
WebSocket is used to implement the JSON signaling protocol in the client-side. Notice that there are three incoming
messages to client: startResponse, playResponse, playEnd,error, and iceCandidate. Convenient
actions are taken to implement each step in the communication. For example, in functions start the function
WebRtcPeer.WebRtcPeerSendrecv of kurento-utils.js is used to start a WebRTC communication.
var ws = new WebSocket('wss://' + location.host + '/repository');
ws.onmessage = function(message) {
var parsedMessage = JSON.parse(message.data);
console.info('Received message: ' + message.data);
switch (parsedMessage.id) {
case 'startResponse':
startResponse(parsedMessage);
break;
case 'playResponse':
playResponse(parsedMessage);
break;
case 'playEnd':
playEnd();
break;
case 'error':
setState(NO_CALL);
onError('Error message from server: ' + parsedMessage.message);
break;
case 'iceCandidate':
webRtcPeer.addIceCandidate(parsedMessage.candidate, function(error) {
if (error)
return console.error('Error adding candidate: ' + error);
});
break;
default:
setState(NO_CALL);
onError('Unrecognized message', parsedMessage);
}
}
function start() {
console.log('Starting video call ...');
var options = {
localVideo : videoInput,
remoteVideo : videoOutput,
onicecandidate : onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options,
function(error) {
if (error)
return console.error(error);
webRtcPeer.generateOffer(onOffer);
});
}
function onError(error) {
console.error(error);
}
function onIceCandidate(candidate) {
console.log('Local candidate' + JSON.stringify(candidate));
var message = {
id : 'onIceCandidate',
candidate : candidate
};
sendMessage(message);
}
function startResponse(message) {
setState(IN_CALL);
webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
if (error)
return console.error(error);
});
}
function stop() {
var stopMessageId = (state == IN_CALL) ? 'stop' : 'stopPlay';
console.log('Stopping video while in ' + state + '...');
setState(POST_CALL);
if (webRtcPeer) {
webRtcPeer.dispose();
webRtcPeer = null;
var message = {
id : stopMessageId
}
sendMessage(message);
}
hideSpinner(videoInput, videoOutput);
}
function play() {
console.log("Starting to play recorded video...");
var options = {
remoteVideo : videoOutput,
onicecandidate : onIceCandidate
}
webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options,
function(error) {
if (error)
return console.error(error);
webRtcPeer.generateOffer(onPlayOffer);
});
}
function playResponse(message) {
setState(IN_PLAY);
webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
if (error)
return console.error(error);
});
}
function playEnd() {
setState(POST_CALL);
hideSpinner(videoInput, videoOutput);
}
function sendMessage(message) {
var jsonMessage = JSON.stringify(message);
console.log('Senging message: ' + jsonMessage);
ws.send(jsonMessage);
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
WebRTC statistics
This tutorial implements a WebRTC loopback and shows how to collect WebRTC statistics.
This web application extends the Hello World tutorial showing how statistics are collected.
Youll need to install Kurento Media Server before running this example. Read installation guide for further informa-
tion.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
Due to Same-origin policy, this demo has to be served by an HTTP server. A very simple way of doing this is by
means of an HTTP Node.js server which can be installed using npm :
Clone source code from GitHub and then start the HTTP server:
237
Kurento Documentation, Release 6.6.1
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the parameter ws_uri to the
URL, as follows:
https://localhost:8443/index.html?ws_uri=wss://kms_host:kms_port/kurento
Notice that the Kurento Media Server must connected using a Secure WebSocket (i.e., the KMS URI starts with
wss:// ). For this reason, the support for secure WebSocket must be enabled in the Kurento Media Server you are using
to run this tutorial. For further information about securing applications, please visit the following page.
The logic of the application is quite simple: the local stream is sent to the Kurento Media Server, which returns it
back to the client without modifications. To implement this behavior we need to create a Media Pipeline composed by
the Media Element WebRtcEndpoint, which holds the capability of exchanging full-duplex (bidirectional) WebRTC
media flows. This media element is connected to itself so any received media (from browser) is send back (to browser).
Using method getStats the application shows all stats of element WebRtcEndpoint.
The complete source code of this demo can be found in GitHub.
JavaScript Logic
This demo follows a Single Page Application architecture (SPA). The interface is the following HTML page: in-
dex.html. This web page links two Kurento JavaScript libraries:
kurento-client.js : Implementation of the Kurento JavaScript Client.
kurento-utils.js : Kurento utility library aimed to simplify the WebRTC management in the browser.
In addition, these two JavaScript libraries are also required:
Bootstrap : Web framework for developing responsive web sites.
jquery.js : Cross-platform JavaScript library designed to simplify the client-side scripting of HTML.
adapter.js : WebRTC JavaScript utility library maintained by Google that abstracts away browser differences.
ekko-lightbox : Module for Bootstrap to open modal images, videos, and galleries.
demo-console : Custom JavaScript console.
The specific logic of this demo is coded in the following JavaScript page: index.js. In this file, there is a function
which is called when the green button labeled as Start in the GUI is clicked.
startButton.addEventListener("click", function() {
var options = {
localVideo: videoInput,
remoteVideo: videoOutput
};
});
[...]
}
The function WebRtcPeer.WebRtcPeerSendrecv hides internal details (i.e. PeerConnection and getUserStream) and
makes possible to start a full-duplex WebRTC communication, using the HTML video tag with id videoInput to show
the video camera (local stream) and the video tag videoOutput to show the remote stream provided by the Kurento
Media Server.
Inside this function, a call to generateOffer is performed. This function accepts a callback in which the SDP offer is
received. In this callback we create an instance of the KurentoClient class that will manage communications with the
Kurento Media Server. So, we need to provide the URI of its WebSocket endpoint. In this example, we assume its
listening in port 8433 at the same host than the HTTP serving the application.
[...]
[...]
Once we have an instance of kurentoClient, the following step is to create a Media Pipeline, as follows:
client.create("MediaPipeline", function(error, _pipeline){
[...]
});
If everything works correctly, we have an instance of a media pipeline (variable pipeline in this example). With
this instance, we are able to create Media Elements. In this example we just need a WebRtcEndpoint. Then, this media
elements is connected itself:
pipeline.create("WebRtcEndpoint", function(error, webRtc) {
if (error) return onError(error);
webRtcEndpoint = webRtc;
webRtc.gatherCandidates(onError);
webRtcPeer.processAnswer(sdpAnswer, onError);
});
webRtc.connect(webRtc, function(error) {
console.log("Loopback established");
webRtcEndpoint.on('MediaStateChanged', function(event) {
if (event.newState == "CONNECTED") {
console.log("MediaState is CONNECTED ... printing stats...")
activateStatsTimeout();
}
});
});
});
In the following snippet, we can see getStats method. This method returns several statistic values of WebRtcEnd-
point.
peerConnection.getStats(function(stats) {
var results = stats.result();
Note: The TURN and STUN servers to be used can be configured simple adding the parameter ice_servers to
the application URL, as follows:
https://localhost:8443/index.html?ice_servers=[{"urls":"stun:stun1.example.net"},{
"urls":"stun:stun2.example.net"}]
https://localhost:8443/index.html?ice_servers=[{"urls":"turn:turn.example.org",
"username":"user","credential":"myPassword"}]
Dependencies
Demo dependencies are located in file bower.json. Bower is used to collect them.
"dependencies": {
"kurento-client": "6.6.0",
"kurento-utils": "6.6.2"
}
Note: We are in active development. You can find the latest version of Kurento JavaScript Client at Bower.
Mastering Kurento
243
CHAPTER 20
Kurento Architecture
Kurento Architecture
Kurento, as most multimedia communication technologies out there, is built using two layers (called planes) to abstract
key functions in all interactive communication systems:
Signaling Plane. The parts of the system in charge of the management of communications, that is, the modules
that provides functions for media negotiation, QoS parametrization, call establishment, user registration, user
presence, etc. are conceived as forming part of the Signaling Plane.
Media Plane Functionalities such as media transport, media encoding/decoding and media processing make the
Media Plane, which takes care of the handling of media. The distinction comes from the telephony differentia-
tion between the handling of voice and the handling of meta-information such as tone, billing, etc.
The following figure shows a conceptual representation of the high level architecture of Kurento.
The right side of the picture shows the application, which is in charge of the signaling plane and contains the business
logic and connectors of the particular multimedia application being deployed. It can be build with any programming
technology like Java, Node.js, PHP, Ruby, .NET, etc. The application can use mature technologies such as HTTP and
SIP Servlets, Web Services, database connectors, messaging services, etc. Thanks to this, this plane provides access
to the multimedia signaling protocols commonly used by end-clients such as SIP, RESTful and raw HTTP based
formats, SOAP, RMI, CORBA or JMS. These signaling protocols are used by client side of applications to command
the creation of media sessions and to negotiate their desired characteristics on their behalf. Hence, this is the part of
the architecture, which is in contact with application developers and, for this reason, it needs to be designed pursuing
simplicity and flexibility.
On the left side, we have the Kurento Media Server, which implements the media plane capabilities providing access
to the low-level media features: media transport, media encoding/decoding, media transcoding, media mixing, media
processing, etc. The Kurento Media Server must be capable of managing the multimedia streams with minimal latency
and maximum throughput. Hence the Kurento Media Server must be optimized for efficiency.
245
Kurento Documentation, Release 6.6.1
Fig. 20.1: Kurento Architecture. Kurento architecture follows the traditional separation between signaling and media
planes.
The capabilities of the media plane (Kurento Media Server) and signaling plane (Application) are exposed through a
number of APIs, which provide increasing abstraction levels.
Following this, the role of the different APIs can be summarized in the following way:
Kurento Protocol: Is a network protocol exposing the Kurento Media Server capabilities through WebSocket
(read more in Kurento Protocol section).
Kurento API: Is the object oriented view of the Kurento Protocol. This API makes possible the creation and
management of media elements and pipelines by using references (ids). Accessing the Kurento API is possible
from any of the computer languages and frameworks implementing Kurento Protocol. (read more in Kurento
API section)
Kurento Java Client: Is a Java SE layer which consumes the Kurento API and exposes its capabilities through
a simple-to-use modularity based on Java POJOs representing media elements and media pipelines. This API
is abstract in the sense that all the non-intuitive inherent complexities of the internal Kurento Protocol workings
are abstracted and developers do not need to deal with them when creating applications. Using the Kurento Java
Client only requires adding the appropriate dependency to a maven project or to download the corresponding jar
into the application developer CLASSPATH. It is important to remark that the Kurento Java Client is a media-
plane control API. In other words, its objective is to expose the capability of managing media objects, but it does
not provide any signaling plane capabilities.
Kurento JavaScript Client: Is a JavaScript layer which consumes the Kurento API and exposes its capabilities
to JavaScript developers. It allow to build node.js and browser based applications. In the future, further Kurento
Clients can be created exposing the same kind of modularity in other languages such as Python, C/C++, PHP,
etc.
From an architectural perspective, the only relevant aspect is that application developers can use Kurento Clients or
Kurento API directly for creating their multimedia enabled applications. This opens a wide spectrum of potential usage
scenarios ranging from web applications (written using the Kurento JavaScript client), desktop applications (written
using the Kurento Java Client), distibuted applications (writen using Kurento Protocol, etc.).
Kurento Modules
Kurento has been designed as a pluggable framework. Kurento Media Server uses several modules by default,
named kms-core, kms-elements and kms-filters. In addition, there are others built-in modules to en-
hance the capabilities provided by the Kurento Media Server. These modules are called kms-crowddetector,
kms-pointerdetector, kms-chroma, and kms-platedetector. Finally Kurento Media Server can be
expanded with new custom modules.
Kurento modules architecture. Kurento Media Server can be extended with built-it modules (crowddetector, pointer-
detector, chroma, platedetector) and also with other custom modules.
For further details please visit the Kurento Modules page.
Kurento can be used following the architectural principles of the WWW. That is, creating a multimedia applications
basing on it can be a similar experience to creating a web application using any of the popular web development
frameworks.
At the highest abstraction level, web applications have an architecture comprised of three different layers:
Presentation layer (client side): Here we can find all the application code which is in charge of interacting
with end users so that information is represented in a comprehensive way user input is captured. This usually
consists on HTML pages.
Application logic (server side): This layer is in charge of implementing the specific functions executed by the
application.
Service layer (server or Internet side): This layer provides capabilities used by the application logic such as
databases, communications, security, etc. This services can be hosted in the same server as application logic or
can be provided by external parties.
Following this parallelism, multimedia applications created using Kurento can also be implemented with the same
architecture:
Presentation layer (client side): Is in charge of multimedia representation and multimedia capture. It is usually
based on specific build-in capabilities of the client. For example, when creating a browser-based application,
the presentation layer will use capabilities such as the <video> HTML tag or the WebRTC JavaScript APIs.
Application logic: This layer provides the specific multimedia logic. In other words, this layer is in charge of
building the appropriate pipeline (by chaining the desired media elements) that the multimedia flows involved
in the application will need to traverse.
Service layer: This layer provides the multimedia services that support the application logic such as media
recording, media ciphering, etc. The Kurento Media Server (i.e. the specific pipeline of media elements) is in
charge of this layer.
The interesting aspect of this discussion is that, as happens with WWW development, Kurento applications can place
the Presentation layer at the client side and the Service layer at the server side. However, the Application Logic layer,
in both cases, can be located at either of the sides or even distributed between them. This idea is represented in the
following picture:
Layered architecture of web and multimedia applications. Applications created using Kurento (right) can be similar to
standard WWW applications (left). Both types of applications may choose to place the application logic at the client
or at the server code.
This means that Kurento developers can choose to include the code creating the specific media pipeline required by
their applications at the client side (using a suitable Kurento Client or directly with Kurento Protocol) or can place it
at the server side.
Both options are valid but each of them drives to different development styles. Having said this, it is important to
note that in the WWW developers usually tend to maintain client side code as simple as possible, bringing most of
their application logic to the server. Reproducing this kind of development experience is the most usual way of using
Kurento. That is, by locating the multimedia application logic at the server side, so that the specific media pipelines
are created using the Kurento Client for your favorite language.
Note: In the following sections it is considered that all Kurento handling is done at the server side. Although this
is the most common way of using Kurento, is important to note that all multimedia logic can be implemented at the
client with Kurento JavaScript Client.
As can be observed in Figure above, a Kurento application involves interactions among three main modules:
Client Application: which involves the native multimedia capabilities of the client platform plus the specific
client-side application logic. It can use Kurento Clients designed to client platforms (for example, Kurento
JavaScript Client).
Application Server: which involves an application server and the server-side application logic. It can use
Kurento Clients designed to server platforms (for example, Kurento Java Client for Java EE and Kurento
JavaScript Client for Node.js).
Kurento Media Server: which receives commands for creating specific multimedia capabilities (i.e. specific
pipelines adapted to the needs of specific applications)
The interactions maintained among these modules depend on the specificities of each application. However, in general,
for most applications they can be reduced to the following conceptual scheme:
Main interactions between architectural modules. Main interactions occur in two phases: negotiation and media
exchange. Remark that the color of the different arrows and boxes is aligned with the architectural figures presented
above, so that, for example, orange arrows show exchanges belonging to the signaling plane, blue arrows show
exchanges belonging to the Kurento Protocol, red boxes are associated to the Kurento Media Server and green boxes
with the application.
As it can be observed, at a first stage, a client (a browser in a computer, a mobile application, etc.) issues a message to
the application requesting some kind of multimedia capability. This message can be implemented with any protocol
(http, websockets, SIP, etc.). For instance, that request could ask for the visualization of a given video clip.
When the application receives the request, if appropriate, it will carry out the specific server side application logic,
which can include Authentication, Authorization and Accounting (AAA), CDR generation, consuming some type of
web service, etc.
After that, the application processes the request and, according to the specific instructions programmed by the devel-
oper, commands Kurento Media Server to instantiate the suitable media elements and to chain them in an appropriate
media pipeline. Once the pipeline has been created successfully, kurento Media server responds accordingly and the
application forwards the successful response to the client, showing it how and where the media service can be reached.
During the above mentioned steps no media data is really exchanged. All the interactions have the objective of
negotiating the whats, hows, wheres and whens of the media exchange. For this reason, we call it the negotiation
phase. Clearly, during this phase only signaling protocols are involved.
After that, a new phase starts devoted to producing the actual media exchange. The client addresses a request for the
media to the Kurento Media Server using the information gathered during the negotiation phase. Following with the
video-clip visualization example mentioned above, the browser will send a GET request to the IP address and port of
the Kurento Media Server where the clip can be obtained and, as a result, an HTTP reponse with the media will be
received.
Following the discussion with that simple example, one may wonder why such a complex scheme for just playing a
video, when in most usual scenarios clients just send the request to the appropriate URL of the video without requiring
any negotiation. The answer is straightforward. Kurento is designed for media applications involving complex media
processing. For this reason, we need to establish a two-phase mechanism enabling a negotiation before the media
exchange. The price to pay is that simple applications, such as one just downloading a video, also need to get through
these phases. However, the advantage is that when creating more advanced services the same simple philosophy will
hold. For example, if we want to add augmented reality or computer vision features to that video-clip, we just need to
create the appropriate pipeline holding the desired media element during the negotiation phase. After that, from the
client perspective, the processed clip will be received as any other video.
Kurento allows the establishment of real time multimedia session between a browser and the Kurento Media Server
directly through the use of WebRTC. In addition, Kurento Media Server can be used to act as media proxy for making
possible the communication among different clients, which are mediated by the kurento infrastructure. Hence, Kurento
Media Server can act as a conference bridge (Multi-Conference Unit, MCU), as a machine-to-machine communication
system, as a video call recording system, etc.
As shown in the picture, the client exposes its media capabilities through an SDP (Session Description Protocol) sent in
a request. Hence, the application is able to instantiate the appropriate WebRTC endpoint, and to require it to generate a
response SDP based on its own capabilities and on the offered SDP. When the answer SDP is obtained, it is given back
to the client and the media exchange can be started. The interactions among the different modules are summarized in
the following picture
Main interactions in a WebRTC session. Interactions taking place in a Real Time Communications (RTC) session.
During the negotiation phase, a Session Description Protocol (SDP) message is exchanged offering the capabilities of
the client. As a result, Kurento Media Server generates an SDP answer that can be used by the client for extablishing
the media exchange.
The application developer is able to create the desired pipeline during the negotiation phase, so that the real time
multimedia stream is processed accordingly to the application needs. Just as an example, imagine that we want to
create a WebRTC application recording the media received from the client and augmenting it so that if a human face is
found, a hat will be rendered on top of it. This pipeline is schematically shown in the figure below, where we assume
that the Filter element is capable of detecting the face and adding the hat to it.
Example pipeline for a WebRTC session. During the negotiation phase, the application developer can create a pipeline
providing the desired specific functionality. For example, this pipeline uses a WebRtcEndpoint for communicating with
the client, which is connected to a RecorderEndpoint storing the received media streamd and to an augmented reality
filter, which feeds its output media stream back to the client. As a result, the end user will receive its own image filtered
(e.g. with a hat added onto her head) and the stream will be recorded and made available for further recovery into a
repository (e.g. a file).
Kurento Media Server exposes an API to high level languages that allow application programmers to control it.
This high level API can be used with a Kurento Client for Java or JavaScript. If you prefer another programming
language, you can use the Kurento Protocol, based on WebSocket and JSON-RPC.
In the following sections we will describe the Kurento API in a high level way. We will show the media capabilities
exposed by Kurento Media Server to clients. If you want see working demos using Kurento, please refer to Tutorials
section.
Kurento is based on two concepts that act as building blocks for application developers:
Media Elements. A Media element is a functional unit performing a specific action on a media stream. Media
elements are a way of every capability is represented as a self-contained black box (the media element) to the
application developer, who does not need to understand the low-level details of the element for using it. Media
elements are capable of receiving media from other elements (through media sources) and of sending media to
other elements (through media sinks). Depending on their function, media elements can be split into different
groups:
Input Endpoints: Media elements capable of receiving media and injecting it into a pipeline. There are
several types of input endpoints. File input endpoints take the media from a file, Network input endpoints
take the media from the network, and Capture input endpoints are capable of capturing the media stream
directly from a camera or other kind of hardware resource.
Filters: Media elements in charge of transforming or analyzing media. Hence there are filters for perform-
ing operations such as mixing, muxing, analyzing, augmenting, etc.
Hubs: Media Objects in charge of managing multiple media flows in a pipeline. A Hub has several hub
ports where other media elements are connected. Depending on the Hub type, there are different ways to
control the media. For example, there are a Hub called Composite that merge all input video streams in a
unique output video stream with all inputs in a grid.
253
Kurento Documentation, Release 6.6.1
Output Endpoints: Media elements capable of taking a media stream out of the pipeline. Again, there
are several types of output endpoints specialized in files, network, screen, etc.
Media Pipeline: A Media Pipeline is a chain of media elements, where the output stream generated by one
element (source) is fed into one or more other elements input streams (sinks). Hence, the pipeline represents a
machine capable of performing a sequence of operations over a stream.
Fig. 21.1: Example of a Media Pipeline implementing an interactive multimedia application receiving media from a
WebRtcEndpoint, overlaying and image on the detected faces and sending back the resulting stream
Kurento API is an object oriented API. That is, there are classes that can be instantiated. This classes define operations
that can be invoked over objects of this classes. The classes can have an inheritance relationship with other classes,
inheriting operations from parent classes to children ones.
The following class diagram shows some of the relationships of the main classes in the Kurento API.
Endpoints
A WebRtcEndpoint is an output and input endpoint that provides media streaming for Real Time Communications
(RTC) through the web. It implements WebRTC technology to communicate with browsers.
A RtpEndpoint is an output and input endpoint. That is, provides bidirectional content delivery capabilities with
remote networked peers through RTP protocol. As you can imagine, to send and receive media through the network it
uses RTP protocol and SDP for media negotiation.
An HttpPostEndpoint is an input endpoint that accepts media using http POST requests like HTTP file upload func-
tion.
A PlayerEndpoint is an input endpoint that retrieves content from file system, http URL or RTSP url and inject it into
the media pipeline.
A RecorderEndpoint is an output endpoint that provides function to store contents in reliable mode (doesnt discard
data). It contains Media Sink pads for audio and video.
The following class diagram shows the relationships of the main endpoint classes.
Filters
Filters are MediaElements that perform media processing, computer vision, augmented reality, and so on. Let see the
available filters in Kurento:
The ZBarFilter filter detects QR and bar codes in a video stream. When a code is found, the filter raises a
CodeFoundEvent. Clients can add a listener to this event to execute some action.
The FaceOverlayFilter filter detects faces in a video stream and overlaid it with a configurable image.
GStreamerFilter is a generic filter interface that allow use GStreamer filter in Kurento Media Pipelines.
The following class diagram shows the relationships of the main filter classes.
Hubs
Hubs are media objects in charge of managing multiple media flows in a pipeline. A Hub has several hub ports where
other media elements are connected. Lets see the available hubs in Kurento:
Composite is a hub that mixes the audio stream of its connected inputs and constructs a grid with the video streams
of them.
DispatcherOneToMany is a Hub that sends a given input to all the connected output HubPorts.
Dispatcher is a hub that allows routing between arbitrary input-output HubPort pairs.
You see the details of the Kurento Clients see the JavaDoc/JsDoc:
kurento-client-java : JavaDoc of Kurento Java Client.
kurento-client-js : JsDoc of Kurento JavaScript Client.
kurento-utils-js : JsDoc of an utility JavaScript library aimed to simplify the development of WebRTC applica-
tions.
Kurento Protocol
Kurento Protocol
Kurento Media Server can be controlled by means of two out of the box Kurento Clients, i.e. Java or JavaScript.
These clients use the Kurento Protocol to speak with the KMS. Kurento Protocol is based on WebSocket and uses
JSON-RPC V2.0 messages for making requests and sending responses.
Kurento Protocol uses JSON-RPC V2.0 to code its messages. The following subsections shows how to use this format
in JSON messages.
Request messages
An RPC call is represented by sending a request message to a server. The request message has the following members:
jsonrpc: a string specifying the version of the JSON-RPC protocol. It must be exactly 2.0.
id: an unique identifier established by the client that contains a string or number. The server must reply with the
same value in the response message. This member is used to correlate the context between both messages.
method: a string containing the name of the method to be invoked.
params: a structured value that holds the parameter values to be used during the invocation of the method.
The following JSON shows a sample request for the creation of a PlayerEndpoint Media Element:
{
"jsonrpc": "2.0",
"id": 1,
"method": "create",
"params": {
"type": "PlayerEndpoint",
"constructorParams": {
259
Kurento Documentation, Release 6.6.1
"pipeline": "6829986",
"uri": "http://host/app/video.mp4"
},
"sessionId": "c93e5bf0-4fd0-4888-9411-765ff5d89b93"
}
}
When an RPC call is made the server replies with a response message. In the case of a successful response, the
response message will contain the following members:
jsonrpc: a string specifying the version of the JSON-RPC protocol. It must be exactly 2.0.
id: this member is mandatory and it must match the value of the id member in the request message.
result: its value is determined by the method invoked on the server. In case the connection is rejected, its
returned an message with a rejected attribute containing an message with a code and message attributes with the
reason why the session was not accepted, and no sessionId is defined.
The following example shows a typical successful response:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"value": "442352747",
"sessionId": "c93e5bf0-4fd0-4888-9411-765ff5d89b93"
}
}
When an RPC call is made the server replies with a response message. In the case of an error response, the response
message will contain the following members:
jsonrpc: a string specifying the version of the JSON-RPC protocol. It must be exactly 2.0.
id: this member is mandatory and it must match the value of the id member in the request message. If there was
an error in detecting the id in the request message (e.g. Parse Error/Invalid Request), it equals to null.
error: an message describing the error through the following members:
code: an integer number that indicates the error type that occurred.
message: a string providing a short description of the error.
data: a primitive or structured value that contains additional information about the error. It may be omitted.
The value of this member is defined by the server.
The following example shows a typical error response:
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": "33",
"message": "Invalid paramter format"
}
}
As explained in Kurento API section, Kurento Media Server exposes a full fledged API to let applications to process
media in several ways.
To allow this rich API, Kurento Clients require requires full-duplex communications between client and server infras-
tructure. For this reason, the Kurento Protocol is based on WebSocket transports.
Previous to issuing commands, the Kurento Client requires establishing a WebSocket connection with Kurento Media
Server to the URL: ws://hostname:port/kurento
Once the WebSocket has been established, the Kurento Protocol offers different types of request/response messages:
ping: Keep-alive method between client and Kurento Media Server.
create: Instantiates a new media object, that is, a pipeline or media element.
invoke: Calls a method of an existing media object.
subscribe: Creates a subscription to an event in a object.
unsubscribe: Removes an existing subscription to an event.
release: Deletes the object and release resources used by it.
The Kurento Protocol allows to Kurento Media Server send requests to clients:
onEvent: This request is sent from Kurento Media server to clients when an event occurs.
Ping
In order to warranty the WebSocket connectivity between the client and the Kurento Media Server, a keep-alive
method is implemented. This method is based on a ping method sent by the client, which must be replied with a
pong message from the server. If no response is obtained in a time interval, the client is aware that the connectivity
with the media server has been lost.The parameter interval is the time out to receive the Pong message from the
server, in milliseconds. By default this value is 240000 (i.e. 40 seconds). This is an example of ping request:
{
"id": 1,
"method": "ping",
"params": {
"interval": 240000
},
"jsonrpc": "2.0"
}
The response to a ping request must contain a result object with a value parameter with a fixed name: pong.
The following snippet shows the pong response to the previous ping request:
{
"id": 1,
"result": {
"value": "pong"
},
"jsonrpc": "2.0"
}
Create
Create message requests the creation of an object of the Kurento API (Media Pipelines and Media Elements). The
parameter type specifies the type of the object to be created. The parameter constructorParams contains all the
information needed to create the object. Each message needs different constructorParams to create the object.
These parameters are defined in Kurento API section.
Media Elements have to be contained in a previously created Media Pipeline. Therefore, before creating Media
Elements, a Media Pipeline must exist. The response of the creation of a Media Pipeline contains a parameter called
sessionId, which must be included in the next create requests for Media Elements.
The following example shows a request message requesting the creation of an object of the type MediaPipeline:
{
"id": 2,
"method": "create",
"params": {
"type": "MediaPipeline",
"constructorParams": {},
"properties": {}
},
"jsonrpc": "2.0"
}
The response to this request message is as follows. Notice that the parameter value identifies the created Media
Pipelines, and sessionId is the identifier of the current session:
{
"id": 2,
"result": {
"value": "6ba9067f-cdcf-4ea6-a6ee-d74519585acd_kurento.MediaPipeline",
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
The response message contains the identifier of the new object in the field value. As usual, the message id must
match with the request message. The sessionId is also returned in each response. The following example shows
a request message requesting the creation of an object of the type WebRtcEndpoint within an existing Media
Pipeline (identified by the parameter mediaPipeline). Notice that in this request, the sessionId is already
present, while in the previous example it was not (since at that point was unknown for the client):
{
"id": 3,
"method": "create",
"params": {
"type": "WebRtcEndpoint",
"constructorParams": {
"mediaPipeline": "6ba9067f-cdcf-4ea6-a6ee-d74519585acd_kurento.
MediaPipeline"
},
"properties": {},
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
The following example shows a request message requesting the creation of an object of the type WebRtcEndpoint
within an existing Media Pipeline (identified by the parameter mediaPipeline). Notice that in this request, the
sessionId is already present, while in the previous example it was not (since at that point was unknown for the
client):
{
"id": 3,
"result": {
"value": "6ba9067f-cdcf-4ea6-a6ee-d74519585acd_kurento.MediaPipeline/087b7777-
aab5-4787-816f-f0de19e5b1d9_kurento.WebRtcEndpoint",
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
Invoke
Invoke message requests the invocation of an operation in the specified object. The parameter object indicates the
id of the object in which the operation will be invoked. The parameter operation carries the name of the operation
to be executed. Finally, the parameter operationParams has the parameters needed to execute the operation.
The following example shows a request message requesting the invocation of the operation connect on a
PlayerEndpoint connected to a WebRtcEndpoint:
{
"id": 5,
"method": "invoke",
"params": {
"object": "6ba9067f-cdcf-4ea6-a6ee-d74519585acd_kurento.MediaPipeline/
76dcb8d7-5655-445b-8cb7-cf5dc91643bc_kurento.PlayerEndpoint",
"operation": "connect",
"operationParams": {
"sink": "6ba9067f-cdcf-4ea6-a6ee-d74519585acd_kurento.MediaPipeline/
087b7777-aab5-4787-816f-f0de19e5b1d9_kurento.WebRtcEndpoint"
},
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
The response message contains the value returned while executing the operation invoked in the object or nothing if the
operation doesnt return any value.
The following example shows a typical response while invoking the operation connect (that doesnt return anything):
{
"id": 5,
"result": {
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
Release
Release message requests the release of the specified object. The parameter object indicates the id of the object to
be released:
{
"id": 36,
"method": "release",
"params": {
"object": "6ba9067f-cdcf-4ea6-a6ee-d74519585acd_kurento.MediaPipeline",
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
The response message only contains the sessionId. The following example shows the typical response of a release
request:
{
"id": 36,
"result": {
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
Subscribe
Subscribe message requests the subscription to a certain kind of events in the specified object. The parameter object
indicates the id of the object to subscribe for events. The parameter type specifies the type of the events. If a client
is subscribed for a certain type of events in an object, each time an event is fired in this object, a request with method
onEvent is sent from Kurento Media Server to the client. This kind of request is described few sections later.
The following example shows a request message requesting the subscription of the event type EndOfStream on a
PlayerEndpoint object:
{
"id": 11,
"method": "subscribe",
"params": {
"type": "EndOfStream",
"object": "6ba9067f-cdcf-4ea6-a6ee-d74519585acd_kurento.MediaPipeline/
76dcb8d7-5655-445b-8cb7-cf5dc91643bc_kurento.PlayerEndpoint",
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
The response message contains the subscription identifier. This value can be used later to remove this subscription.
The following example shows the response of subscription request. The value attribute contains the subscription id:
{
"id": 11,
"result": {
"value": "052061c1-0d87-4fbd-9cc9-66b57c3e1280",
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
Unsubscribe
Unsubscribe message requests the cancellation of a previous event subscription. The parameter subscription contains
the subscription id received from the server when the subscription was created.
The following example shows a request message requesting the cancellation of the subscription
353be312-b7f1-4768-9117-5c2f5a087429 for a given object:
{
"id": 38,
"method": "unsubscribe",
"params": {
"subscription": "052061c1-0d87-4fbd-9cc9-66b57c3e1280",
"object": "6ba9067f-cdcf-4ea6-a6ee-d74519585acd_kurento.MediaPipeline/
76dcb8d7-5655-445b-8cb7-cf5dc91643bc_kurento.PlayerEndpoint",
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
The response message only contains the sessionId. The following example shows the typical response of an
unsubscription request:
{
"id": 38,
"result": {
"sessionId": "bd4d6227-0463-4d52-b1c3-c71f0be68466"
},
"jsonrpc": "2.0"
}
OnEvent
When a client is subscribed to a type of events in an object, the server sends an onEvent request each time an event
of that type is fired in the object. This is possible because the Kurento Protocol is implemented with WebSockets and
there is a full duplex channel between client and server. The request that server send to client has all the information
about the event:
source: the object source of the event.
type: The type of the event.
timestamp: Date and time of the media server.
tags: Media elements can be labeled using the methods setSendTagsInEvents and addTag present in
each element. These tags are key-value metadata that can be used by developers for custom purposes. Tags are
returned with each event by the media server in this field.
The following example shows a notification sent for server to client to notify an event of type EndOfStream for a
PlayerEndpoint object:
{
"jsonrpc":"2.0",
"method":"onEvent",
"params":{
"value":{
"data":{
"source":"681f1bc8-2d13-4189-a82a-2e2b92248a21_kurento.MediaPipeline/
e983997e-ac19-4f4b-9575-3709af8c01be_kurento.PlayerEndpoint",
"tags":[],
"timestamp":"1441277150",
"type":"EndOfStream"
},
"object":"681f1bc8-2d13-4189-a82a-2e2b92248a21_kurento.MediaPipeline/e983997e-
ac19-4f4b-9575-3709af8c01be_kurento.PlayerEndpoint",
"type":"EndOfStream"
}
}
}
Notice that this message has no id field due to the fact that no response is required.
Network issues
Resources handled by KMS are high-consuming. For this reason, KMS implements a garbage collector.
A Media Element is collected when the client is disconnected longer than 4 minutes. After that time, these media
elements are disposed automatically.
Therefore the WebSocket connection between client and KMS be active any time. In case of temporary network
disconnection, KMS implements a mechanism to allow the client reconnection.
There is an special kind of message with the format above. This message allows a client to reconnect to the same KMS
previously connected:
{
"jsonrpc": "2.0",
"id": 7,
"method": "connect",
"params": {
"sessionId":"4f5255d5-5695-4e1c-aa2b-722e82db5260"
}
}
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"sessionId":"4f5255d5-5695-4e1c-aa2b-722e82db5260"
}
}
... this means that client is reconnected to the same KMS. In case of reconnection to another KMS, the message is the
following:
{
"jsonrpc":"2.0",
"id": 7,
"error":{
"code":40007,
"message":"Invalid session",
"data":{
"type":"INVALID_SESSION"
}
}
}
In this case client is supposed to invoke the connect primitive once again in order to get a new sessionId:
{
"jsonrpc":"2.0",
"id": 7,
"method":"connect"
}
Kurento API
In order to implement a Kurento client you need the reference documentation. The best way to know all details is take
a look to IDL file that defines the interface of the Kurento elements. We have defined a custom IDL format based on
JSON. From it, we generate the client code for Java and JavaScript. Kurento API is defined in the following IDL files:
KMS core
KMS elements
KMS filters
This section describes an example of the messages interchanged between a Kurento client and the Kurento Media
Server in order to create a WebRTC in loopback. This example is fully depicted in the tutorials section. The steps are
the following:
1. Client sends a request message in order to a media pipeline:
{
"id":1,
"method":"create",
"params":{
"type":"MediaPipeline",
"constructorParams":{},
"properties":{}
},
"jsonrpc":"2.0"
}
2. KMS sends a response message with the identifier for the media pipeline and the media session:
{
"id":1,
"result":{
"value":"c4a84b47-1acd-4930-9f6d-008c10782dfe_MediaPipeline",
"sessionId":"ba4be2a1-2b09-444e-a368-f81825a6168c"
},
"jsonrpc":"2.0"
}
4. KMS creates the WebRtcEndpoint sending back the media element identifier to the client:
{
"id":2,
"result":{
"value":"c4a84b47-1acd-4930-9f6d-008c10782dfe_MediaPipeline/e72a1ff5-e416-48ff-
99ef-02f7fadabaf7_WebRtcEndpoint",
"sessionId":"ba4be2a1-2b09-444e-a368-f81825a6168c"
},
"jsonrpc":"2.0"
}
5. Client invokes the connect primitive in the WebRtcEndpoint in order to create a loopback:
{
"id":3,
"method":"invoke",
"params":{
"object":"c4a84b47-1acd-4930-9f6d-008c10782dfe_MediaPipeline/e72a1ff5-e416-48ff-
99ef-02f7fadabaf7_WebRtcEndpoint",
"operation":"connect",
"operationParams":{
"sink":"c4a84b47-1acd-4930-9f6d-008c10782dfe_MediaPipeline/e72a1ff5-e416-48ff-
99ef-02f7fadabaf7_WebRtcEndpoint"
},
"sessionId":"ba4be2a1-2b09-444e-a368-f81825a6168c"
},
"jsonrpc":"2.0"
}
},
"jsonrpc":"2.0"
}
7. Client invokes the processOffer primitive in the WebRtcEndpoint in order to negotiate SDP in WebRTC:
{
"id":4,
"method":"invoke",
"params":{
"object":"c4a84b47-1acd-4930-9f6d-008c10782dfe_MediaPipeline/e72a1ff5-e416-48ff-
99ef-02f7fadabaf7_WebRtcEndpoint",
"operation":"processOffer",
"operationParams":{
"offer":"SDP"
},
"sessionId":"ba4be2a1-2b09-444e-a368-f81825a6168c"
},
"jsonrpc":"2.0"
}
8. KMS carry out the SDP negotiation and returns the SDP answer:
{
"id":4,
"result":{
"value":"SDP"
},
"jsonrpc":"2.0"
}
The default Kurento clients (Java and JavaScript) are created using a tool called Kurento Module Creator. Therefore,
this tool can be also be used to create custom clients in other languages.
Kurento Module Creator can be installed in an Ubuntu machine using the following command:
The aim of this tools is to generate the client code and also the glue code needed in the server-side. For code generation
it uses Freemarker as template engine. The typical way to use Kurento Module Creator is by running a command like
this:
Where:
CODEGEN_DIR: Destination directory for generated files.
ROM_FILE: A space separated list of Kurento Media Element Description (kmd) files or folders containing this
files. As an example, you can take a look to the kmd files within the Kurento Media Server source code.
TEMPLATES_DIR: Directory that contains template files. As an example, you can take a look to the internal
Java and JavaScript templates.
The main KMS configuration file is located in /etc/kurento/kurento.conf.json. After a fresh installation
this file is the following:
{
"mediaServer" : {
"resources": {
// //Resources usage limit for raising an exception when an object creation is
attempted
// "exceptionLimit": "0.8",
// // Resources usage limit for restarting the server when no objects are alive
// "killLimit": "0.7",
// Garbage collector period in seconds
"garbageCollectorPeriod": 240
},
"net" : {
"websocket": {
"port": 8888,
//"secure": {
// "port": 8433,
// "certificate": "defaultCertificate.pem",
// "password": ""
//},
//"registrar": {
// "address": "ws://localhost:9090",
// "localAddress": "localhost"
//},
"path": "kurento",
"threads": 10
}
271
Kurento Documentation, Release 6.6.1
}
}
}
As of Kurento Media Server version 6, in addition to this general configuration file, the specific features of KMS are
tuned as individual modules. Each of these modules has its own configuration file:
/etc/kurento/modules/kurento/MediaElement.conf.ini: Generic parameters for Media Ele-
ments.
/etc/kurento/modules/kurento/SdpEndpoint.conf.ini: Audio/video parameters for Sd-
pEndpoints (i.e. WebRtcEndpoint and RtpEndpoint).
/etc/kurento/modules/kurento/WebRtcEndpoint.conf.ini: Specific parameters for WebRt-
cEndpoint.
/etc/kurento/modules/kurento/HttpEndpoint.conf.ini: Specific parameters for HttpEnd-
point.
WebSocket Port
Unless configured otherwise, KMS will open the port 8888 to receive requests and send responses to/from by means
of the Kurento Protocol. To verify if this port is listening execute the following command:
Kurento Media Server logs file are stored in the folder /var/log/kurento-media-server/. The content of
this folder is as follows:
media-server_<timestamp>.<log_number>.<kms_pid>.log: Current log for Kurento Media
Server.
media-server_error.log: Third-party errors.
logs: Folder that contains the KMS rotated logs.
Each line in the Kurento Media Server logs has a fixed structure, as follows:
... where:
[timestamp] : Date and time of the logging trace (e.g. 2016-10-26 12:04:22,493295).
[pid] : Process identifier of kurento-media-sever (e.g. 17521).
[memory] : Memory address in which the kurento-media-sever component is running (e.g.
0x00007fd59f2a78c0).
[level] : Log level. This value typically will be info and debug. If unexpected error situation happens,
the error level will contain information about the problem.
[component] : Kurento Media Server component name, for example KurentoModuleManager,
KurentoLoadConfig, or KurentoMediaServer, among others.
[filename:loc] : Code source file name (e.g. main.cp) followed by the line of code (loc) number.
[method] : Name of the method of function in which the log trace is invoked (e.g. loadModule(),
doGarbageCollection(), etc).
[message] : Specific log information.
For example, when KMS starts correctly, this trace is written in the log file:
Kurento is composed by several components. Each component is being developed with very different technologies.
Kurento Media Server: This is the core component of Kurento. It is implemented using C/C++ and GStreamer
platform.
Kurento Java Client: This Kurento Client is implemented in Java with Maven and Sprint.
Kurento JavaScript Client: This Kurento Client is implemented in JavaScript with Node.js and NPM.
In this section, we will see how to use nightly compiled versions of Kurento code base. This is not the recommended
way to use Kurento, but can be useful if you are testing brand new features.
Well also explain in detail how Kurento can be built from sources. This is a complex task because Kurento uses
several technologies, although it can be very funny ;)
In this section we are going to explain how to use development versions of Kurento. We build every Kurento compo-
nent at least once a day as we follow the Continuous Integration principles.
Some components are build nightly, with the code developed that day. Other components are created automatically
when code is merged into source repository.
Using development versions is not the recommended way to use Kurento, but it can be useful to try brand new features.
Warning: You have to use this versions with caution, because them can be broken. Usually they have bugs and
incomplete functionalities. Never use development versions in production.
275
Kurento Documentation, Release 6.6.1
As you can imagine, it is not possible to have installed at the same time latest stable version and latest development
version of Kurento Media Server.
In order to install older versions of Kurento Media Server, you need to configure the proper repository (trusty or
xenial) in your apt sources:
deb http://ubuntu.kurento.org/[VERSION_TAG] trusty kms6
deb http://ubuntu.kurento.org/[VERSION_TAG] xenial kms6
... where [VERSION_TAG] is the version of Kurento Media Server to be installed (for instance, 6.4.0). After that
you should install KMS as usual:
sudo apt-get update
sudo apt-get install kurento-media-server-6.0
Notice that an old version of KMS cannot live in the same machine that a stable/unstable release. Therefore, if you
have KMS previously installed and you want to downgrade to a former release, first your need to purge your previous
installation:
sudo apt-get remove kurento-media-server-6.0
sudo apt-get purge kurento-media-server-6.0
sudo apt-get autoremove
sudo apt-get dist-upgrade
The development builds of Kurento Java Client Maven artifacts hosted in http://maven.kurento.org.
To use development versions, first you have to add this repository in your Maven installation as a valid snapshot
repository. To do this, add following configuration repository to the repositories section to file ~/.m2/settings.
xml:
<repositories>
<repository>
<id>kurento-snapshots</id>
<name>Kurento Snapshot Repository</name>
<url>http://maven.kurento.org/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>kurento-snapshots</id>
<name>Kurento Snapshot Repository</name>
<url>http://maven.kurento.org/snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
Then, you have to change the dependency in your applications pom.xml to point to a development version. There is
no way in Maven to use the latest development version of an artifact. You have to specify the concrete development
version you want to depend on. To know what is the current Kurento Java Client development version, you can take
a look to the internal Kurento Maven repository and search for the latest version. Then, you have to include in your
applications pom.xml the following dependency:
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
<version>latest-version-SNAPSHOT</version>
</dependency>
JavaScript is special because in some cases there is no need to build anything. JavaScript is a scripting language
that can execute directly from sources. But in some cases, the code have to be processed to be used from client
applications.
Node.js development
If you are using Kurento JavaScript Client from a Node.js application and want to use the latest development version
of this library, you have to change the dependencies section in the applications package.json. You have to
point directly to the development repository, that is:
"dependencies": {
"kurento-client": "Kurento/kurento-client-js#master"
}
If you are using Kurento JavaScript Client from a browser application with Bower and want to use the latest develop-
ment version of this library, you have to change the dependencies section in the applications bower.json. You
have to point directly to the development bower repository, that is:
"dependencies": {
"kurento-client": "master"
"kurento-utils": "master"
}
Alternatively, if your browser application is pointing directly to JavaScript libraries from HTML resources, then, you
have to change to development URLs:
<script type="text/javascript"
src="http://builds.kurento.org/dev/master/latest/js/kurento-client.min.js"></
script>
Kurento Modules
Kurento Modules
Kurento is a pluggable framework. Each plugin in Kurento is called module. We classify Kurento modules into three
groups, namely:
Main modules. Incorporated out of the box with Kurento Media Server
kms-core: Main components of Kurento Media Server.
kms-elements: Implementation of Kurento Media Elements (WebRtcEndpoint,
PlayerEndpoint, and so on).
kms-filters: Implementation of Kurento Filters (FaceOverlayFilter, ZBarFilter,
GStreamerFilter).
Built-in modules. Extra modules developed by the Kurento team to enhance the basic capabilities of Kurento
Media Server. So far, there are four built-in modules, namely:
kms-pointerdetector: Filter that detects pointers in video streams based on color tracking. The
command to install this module is:
kms-chroma: Filter that makes transparent a color range in the top layer, revealing another image behind.
279
Kurento Documentation, Release 6.6.1
Warning: Plate detector module is a prototype and its results is not always accurate. Consider this if
you are planning to use this module in a production environment.
Custom modules. Extensions to Kurento Media Server which provides new media capabilities. If you are
planning to develop your own custom module, please take a look to the following page:
You can expand the Kurento Media Server developing your own modules. There are two flavors of Kurento modules:
Modules based on OpenCV. This kind of modules are recommended if you would like to develop a computer
vision filter.
Modules based on GStreamer. This kind of modules are more powerful but also they are more difficult to
develop. Skills in GStreamer development are necessary.
The starting point to develop a filter is create the filter structure. For this task, you can use the
kurento-module-scaffold tool. This tool is distributed with the kurento-media-server-6.0-dev
package. To install this tool run this command in the shell:
2. Gstreamer module:
The tool generates the folder tree, all the CmakeLists.txt files necessaries and example files of Kurento module
descriptor files (.kmd). These files describe our modules, the constructor, the methods, the properties, the events and
the complex types defined by the developer.
Once, kmd files are completed we can generate code. The tool kurento-module-creator generates glue code
to server-side. From the root directory:
cd build
cmake ..
The following section details how to create your module depending on the filter type you chose (OpenCV or
GStreamer):
OpenCV module
ModuleNameImpl.cpp
ModuleNameImpl.hpp
ModuleNameOpenCVImpl.cpp
ModuleNameOpenCVImpl.hpp
The first two files should not be modified. The last two files will contain the logic of your module. The file
ModuleNameOpenCVImpl.cpp contains functions to deal with the methods and the parameters (you must im-
plement the logic). Also, this file contains a function called process. This function will be called with each new frame,
thus you must implement the logic of your filter inside this function.
GStreamer module
In this case, we have two directories inside the src folder. The gst-plugins folder contains the implementation
of your GStreamer element (the kurento-module-scaffold generates a dummy filter). Inside the server/
objects folder you have two files:
ModuleNameImpl.cpp
ModuleNameImpl.hpp
In the file ModuleNameImpl.cpp you have to invoke the methods of your GStreamer element. The module logic
will be implemented in the GStreamer element.
If you need extra compilation dependencies you can add compilation rules to the kurento-module-creator using the
function generate_code in the CmakeLists.txt file in src/server. The following parameters are avail-
able:
MODELS (required): This parameter receives the folders where the models (.kmd files) are located.
INTERFACE_LIB_EXTRA_SOURCES, INTERFACE_LIB_EXTRA_HEADERS,
INTERFACE_LIB_EXTRA_INCLUDE_DIRS, INTERFACE_LIB_EXTRA_LIBRARIES: These
parameters allow to add additional source code to the static library. Files included in
INTERFACE_LIB_EXTRA_HEADERS will be installed in the system as headers for this library. All
the parameters accept a list as input.
SERVER_IMPL_LIB_EXTRA_SOURCES, SERVER_IMPL_LIB_EXTRA_HEADERS,
SERVER_IMPL_LIB_EXTRA_INCLUDE_DIRS, SERVER_IMPL_LIB_EXTRA_LIBRARIES:
These parameters allows to add additional source code to the interface library. Files included in
SERVER_IMPL_LIB_EXTRA_HEADERS will be installed in the system as headers for this library. All
the parameters accept a list as input.
MODULE_EXTRA_INCLUDE_DIRS, MODULE_EXTRA_LIBRARIES: These parameters allows to add extra
include directories and libraries to the module.
SERVER_IMPL_LIB_FIND_CMAKE_EXTRA_LIBRARIES: This parameter receives a list of strings, each
string has this format libname[ libversion range] (possible ranges can use symbols AND OR < <= >
>= ^ and ~):
^ indicates a version compatible using Semantic Versioning
~ Indicates a version similar, that can change just last indicated version character
SERVER_STUB_DESTINATION (required): The generated code that you may need to modify will be gener-
ated on the folder indicated by this parameter.
Once the module logic is implemented and the compilation process is finished, you need to install your module in your
system. You can follow two different ways:
You can generate the Debian package (debuild -us -uc) and install it (dpkg -i) or
you can define the following environment variables in the file /etc/default/kurento:
KURENTO_MODULES_PATH=<module_path>/build/src GST_PLUGIN_PATH=<module_path>/
build/src.
Now, you need to generate code for Java or JavaScript to use your module from the client-side.
For Java, from the build directory you have to execute cmake ..
-DGENERATE_JAVA_CLIENT_PROJECT=TRUE command generates a Java folder with client code.
You can run make java_install and your module will be installed in your Maven local repository. To use
the module in your Maven project, you have to add the dependency to the pom.xml file:
<dependency>
<groupId>org.kurento.module</groupId>
<artifactId>modulename</artifactId>
<version>moduleversion</version>
</dependency>
"dependencies": {
"modulename": "moduleversion"
}
Examples
Fig. 25.1: Kurento modules architecture. Kurento Media Server can be extended with built-it modules (crowddetec-
tor, pointerdetector, chroma, platedetector) and also with other custom modules.
Fig. 25.2: Extended Kurento Toolbox. The basic Kurento toolbox (left side of the picture) is extended with more
computer vision and augmented reality filters (right side of the picture) provided by the built-in modules.
This web application consists on a WebRTC video communication in mirror (loopback) with a pointer tracking filter
element.
This web application consists on a WebRTC video communication in mirror (loopback) with a pointer tracking filter
element.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-pointerdetector-6.0 should be also installed:
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
The web application starts on port 8443 in the localhost by default. Therefore, open the URL https://localhost:8443/
in a WebRTC compliant browser (Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
This application uses computer vision and augmented reality techniques to detect a pointer in a WebRTC stream based
on color tracking.
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
The complete source code of this demo can be found in GitHub.
This example is a modified version of the Magic Mirror tutorial. In this case, this demo uses a PointerDetector instead
of FaceOverlay filter.
In order to perform pointer detection, there must be a calibration stage, in which the color of the pointer is registered
by the filter. To accomplish this step, the pointer should be placed in a square visible in the upper left corner of the
video after going thorugh the filter, as follows:
When the desired color to track is filling that box, a calibration message is sent from the client to the server. This is
done by clicking on the Calibrate blue button of the GUI.
After that, the color of the pointer is tracked in real time by Kurento Media Server. PointerDetectorFilter can
also define regions in the screen called windows in which some actions are performed when the pointer is detected when
the pointer enters (WindowInEvent event) and exits (WindowOutEvent event) the windows. This is implemented
in the server-side logic as follows:
webRtcEndpoint
.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>() {
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils
.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(
response.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
pointerDetectorFilter
.addWindow(new PointerDetectorWindowMediaParam("window0",
50, 50, 500, 150));
pointerDetectorFilter
.addWindow(new PointerDetectorWindowMediaParam("window1",
50, 50, 500, 250));
webRtcEndpoint.connect(pointerDetectorFilter);
pointerDetectorFilter.connect(webRtcEndpoint);
pointerDetectorFilter
.addWindowInListener(new EventListener<WindowInEvent>() {
@Override
public void onEvent(WindowInEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "windowIn");
response.addProperty("roiId", event.getWindowId());
try {
session.sendMessage(new TextMessage(response
.toString()));
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
});
pointerDetectorFilter
.addWindowOutListener(new EventListener<WindowOutEvent>() {
@Override
public void onEvent(WindowOutEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "windowOut");
response.addProperty("roiId", event.getWindowId());
try {
session.sendMessage(new TextMessage(response
.toString()));
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
});
webRtcEndpoint.gatherCandidates();
The following picture illustrates the pointer tracking in one of the defined windows:
In order to send the calibration message from the client side, this function is used in the JavaScript side of this demo:
function calibrate() {
console.log("Calibrate color");
var message = {
id : 'calibrate'
}
sendMessage(message);
}
When this message is received in the application server side, this code is execute to carry out the calibration:
private void calibrate(WebSocketSession session, JsonObject jsonMessage) {
if (pointerDetectorFilter != null) {
pointerDetectorFilter.trackColorFromCalibrationRegion();
}
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This web application consists on a WebRTC video communication in mirror (loopback) with a pointer tracking filter
element.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-pointerdetector-6.0 should be also installed:
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
Due to Same-origin policy, this demo has to be served by an HTTP server. A very simple way of doing this is by
means of an HTTP Node.js server which can be installed using npm :
You also need the source code of this demo. You can clone it from GitHub. Then start the HTTP server:
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
Kurento Media Server must use WebSockets over SSL/TLS (WSS), so make sure you check this too. It is possible to
locate the KMS in other machine simple adding the parameter ws_uri to the URL:
https://localhost:8443/index.html?ws_uri=wss://kms_host:kms_port/kurento
Notice that the Kurento Media Server must connected using a Secure WebSocket (i.e., the KMS URI starts with
wss:// ). For this reason, the support for secure WebSocket must be enabled in the Kurento Media Server you are using
to run this tutorial. For further information about securing applications, please visit the following page.
This application uses computer vision and augmented reality techniques to detect a pointer in a WebRTC stream based
on color tracking.
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
The complete source code of this demo can be found in GitHub.
This example is a modified version of the Magic Mirror tutorial. In this case, this demo uses a PointerDetector instead
of FaceOverlay filter.
In order to perform pointer detection, there must be a calibration stage, in which the color of the pointer is registered
by the filter. To accomplish this step, the pointer should be placed in a square in the upper left corner of the video, as
follows:
Note: Modules can have options. For configuring these options, youll need to get the constructor for them. In
Javascript and Node, you have to use kurentoClient.getComplexType(qualifiedName) . There is an example in the
code.
In that precise moment, a calibration operation should be carried out. This is done by clicking on the Calibrate blue
button of the GUI.
After that, the color of the pointer is tracked in real time by Kurento Media Server. PointerDetectorFilter
can also define regions in the screen called windows in which some actions are performed when the pointer is detected
when the pointer enters (WindowIn event) and exits (WindowOut event) the windows. This is implemented in the
JavaScript logic as follows:
...
kurentoClient.register('kurento-module-pointerdetector')
const PointerDetectorWindowMediaParam = kurentoClient.getComplexType('pointerdetector.
PointerDetectorWindowMediaParam')
...
pipeline = _pipeline;
console.log("Got MediaPipeline");
console.log("Got WebRtcEndpoint");
webRtc.gatherCandidates(onError);
webRtcPeer.processAnswer(sdpAnswer);
});
var options =
{
calibrationRegion: WindowParam({
topRightCornerX: 5,
topRightCornerY:5,
width:30,
height: 30
})
};
pipeline.create('pointerdetector.PointerDetectorFilter', options,
function(error, _filter) {
if (error) return onError(error);
filter = _filter;
width:50,
upperRightX: 500,
upperRightY: 150
});
filter.addWindow(options, onError);
filter.addWindow(options, onError);
console.log("Connecting ...");
client.connect(webRtc, filter, webRtc, function(error) {
if (error) return onError(error);
The following picture illustrates the pointer tracking in one of the defined windows:
In order to carry out the calibration process, this JavaScript function is used:
function calibrate() {
if(filter) filter.trackColorFromCalibrationRegion(onError);
}
function onError(error) {
if(error) console.error(error);
}
Note: The TURN and STUN servers to be used can be configured simple adding the parameter ice_servers to
the application URL, as follows:
https://localhost:8443/index.html?ice_servers=[{"urls":"stun:stun1.example.net"},{
"urls":"stun:stun2.example.net"}]
https://localhost:8443/index.html?ice_servers=[{"urls":"turn:turn.example.org",
"username":"user","credential":"myPassword"}]
Dependencies
The dependencies of this demo has to be obtained using Bower. The definition of these dependencies are defined in
the bower.json file, as follows:
"dependencies": {
"kurento-client": "6.6.0",
"kurento-utils": "6.6.2"
"kurento-module-pointerdetector": "6.6.0"
}
bower install
Note: We are in active development. You can find the latest versions at Bower.
This web application consists on a WebRTC video communication in mirror (loopback) with a pointer tracking filter
element.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-pointerdetector-6.0 should be also installed:
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
To launch the application, you need to clone the GitHub project where this demo is hosted, install it and run it:
If you have problems installing any of the dependencies, please remove them and clean the npm cache, and try to
install them again:
rm -r node_modules
npm cache clean
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the argument ws_uri to the
npm execution command, as follows:
In this case you need to use npm version 2. To update it you can use this command:
This application uses computer vision and augmented reality techniques to detect a pointer in a WebRTC stream based
on color tracking.
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
Note: Modules can have options. For configuring these options, youll need to get the constructor for them. In
Javascript and Node, you have to use kurentoClient.getComplexType(qualifiedName) . There is an example in the
code.
In that precise moment, a calibration operation should be carried out. This is done by clicking on the Calibrate blue
button of the GUI.
After that, the color of the pointer is tracked in real time by Kurento Media Server. PointerDetectorFilter
can also define regions in the screen called windows in which some actions are performed when the pointer is detected
when the pointer enters (WindowIn event) and exits (WindowOut event) the windows. This is implemented in the
JavaScript logic as follows:
...
kurento.register('kurento-module-pointerdetector');
const PointerDetectorWindowMediaParam = kurento.getComplexType('pointerdetector.
PointerDetectorWindowMediaParam');
...
getKurentoClient(function(error, kurentoClient) {
if (error) {
return callback(error);
}
if (candidatesQueue[sessionId]) {
while(candidatesQueue[sessionId].length) {
var candidate = candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.
candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
sessions[sessionId] = {
'pipeline' : pipeline,
'webRtcEndpoint' : webRtcEndpoint,
'pointerDetector' : filter
}
return callback(null, 'sdpAnswer', sdpAnswer);
});
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
return callback(error);
}
});
});
});
});
});
}
var options = {
calibrationRegion: WindowParam({
topRightCornerX: 5,
topRightCornerY:5,
width:30,
height: 30
})
};
pipeline.create('pointerdetector.PointerDetectorFilter', options,
function(error, filter) {
if (error) {
return callback(error);
}
The following picture illustrates the pointer tracking in one of the defined windows:
In order to carry out the calibration process, this JavaScript function is used:
function calibrate() {
if (webRtcPeer) {
console.log("Calibrating...");
var message = {
id : 'calibrate'
}
sendMessage(message);
}
}
Dependencies
Dependencies of this demo are managed using NPM. Our main dependency is the Kurento Client JavaScript (kurento-
client). The relevant part of the package.json file for managing this dependency is:
"dependencies": {
"kurento-client" : "6.6.0"
}
At the client side, dependencies are managed using Bower. Take a look to the bower.json file and pay attention to the
following section:
"dependencies": {
"kurento-utils" : "6.6.2",
"kurento-module-pointerdetector": "6.6.0"
}
Note: We are in active development. You can find the latest versions at npm and Bower.
This web application consists on a WebRTC video communication in mirror (loopback) with a chroma filter element.
This web application consists on a WebRTC video communication in mirror (loopback) with a chroma filter element.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-chroma-6.0 should be also installed:
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
The web application starts on port 8443 in the localhost by default. Therefore, open the URL https://localhost:8443/
in a WebRTC compliant browser (Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
This application uses computer vision and augmented reality techniques to detect a chroma in a WebRTC stream based
on color tracking.
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
The complete source code of this demo can be found in GitHub.
This example is a modified version of the Magic Mirror tutorial. In this case, this demo uses a Chroma instead of
FaceOverlay filter.
In order to perform chroma detection, there must be a color calibration stage. To accomplish this step, at the beginning
of the demo, a little square appears in upper left of the video, as follows:
In the first second of the demo, a calibration process is done, by detecting the color inside that square. When the
calibration is finished, the square disappears and the chroma is substituted with the configured image. Take into
account that this process requires good lighting condition. Otherwise the chroma substitution will not be perfect. This
behavior can be seen in the upper right corner of the following screenshot:
The media pipeline of this demo is is implemented in the server-side logic as follows:
webRtcEndpoint
.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>()
{
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils
.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(
response.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
webRtcEndpoint.connect(chromaFilter);
chromaFilter.connect(webRtcEndpoint);
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
webRtcEndpoint.gatherCandidates();
} catch (Throwable t) {
sendError(session, t.getMessage());
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This web application consists on a WebRTC video communication in mirror (loopback) with a chroma filter element.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-chroma-6.0 should be also installed:
sudo apt-get install kms-chroma-6.0
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
curl -sL https://deb.nodesource.com/setup_4.x | sudo bash -
sudo apt-get install -y nodejs
sudo npm install -g bower
Due to Same-origin policy, this demo has to be served by an HTTP server. A very simple way of doing this is by
means of an HTTP Node.js server which can be installed using npm :
sudo npm install http-server -g
You also need the source code of this demo. You can clone it from GitHub. Then start the HTTP server:
git clone https://github.com/Kurento/kurento-tutorial-js.git
cd kurento-tutorial-js/kurento-chroma
git checkout 6.6.1
bower install
http-server -p 8443 -S -C keys/server.crt -K keys/server.key
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
Kurento Media Server must use WebSockets over SSL/TLS (WSS), so make sure you check this too. It is possible to
locate the KMS in other machine simple adding the parameter ws_uri to the URL:
https://localhost:8443/index.html?ws_uri=wss://kms_host:kms_port/kurento
Notice that the Kurento Media Server must connected using a Secure WebSocket (i.e., the KMS URI starts with
wss:// ). For this reason, the support for secure WebSocket must be enabled in the Kurento Media Server you are using
to run this tutorial. For further information about securing applications, please visit the following page.
This application uses computer vision and augmented reality techniques to detect a chroma in a WebRTC stream based
on color tracking.
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
In the first second of the demo, a calibration process is done, by detecting the color inside that square. When the
calibration is finished, the square disappears and the chroma is substituted with the configured image. Take into
account that this process requires lighting condition. Otherwise the chroma substitution will not be perfect. This
behavior can be seen in the upper right corner of the following screenshot:
Note: Modules can have options. For configure these options, you need get the constructor to them. In Javascript and
Node, you have to use kurentoClient.getComplexType(qualifiedName) . There is an example in the code.
The media pipeline of this demo is is implemented in the JavaScript logic as follows:
...
kurentoClient.register('kurento-module-chroma')
const WindowParam = kurentoClient.getComplexType('chroma.WindowParam')
...
pipeline = _pipeline;
console.log("Got MediaPipeline");
webRtc.gatherCandidates(onError);
webRtcPeer.processAnswer(sdpAnswer);
});
console.log("Got WebRtcEndpoint");
var options =
{
window: WindowParam({
topRightCornerX: 5,
topRightCornerY: 5,
width: 30,
height: 30
})
}
console.log("Got Filter");
filter.setBackground(args.bg_uri, function(error) {
if (error) return onError(error);
console.log("Set Image");
});
Note: The TURN and STUN servers to be used can be configured simple adding the parameter ice_servers to
the application URL, as follows:
https://localhost:8443/index.html?ice_servers=[{"urls":"stun:stun1.example.net"},{
"urls":"stun:stun2.example.net"}]
https://localhost:8443/index.html?ice_servers=[{"urls":"turn:turn.example.org",
"username":"user","credential":"myPassword"}]
Dependencies
The dependencies of this demo has to be obtained using Bower. The definition of these dependencies are defined in
the bower.json file, as follows:
"dependencies": {
"kurento-client": "6.6.0",
"kurento-utils": "6.6.2"
"kurento-module-pointerdetector": "6.6.0"
}
bower install
Note: We are in active development. You can find the latest versions at Bower.
This web application consists on a WebRTC video communication in mirror (loopback) with a chroma filter element.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-chroma-6.0 should be also installed:
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
To launch the application, you need to clone the GitHub project where this demo is hosted, install it and run it:
If you have problems installing any of the dependencies, please remove them and clean the npm cache, and try to
install them again:
rm -r node_modules
npm cache clean
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the argument ws_uri to the
npm execution command, as follows:
npm start -- --ws_uri=ws://kms_host:kms_port/kurento
In this case you need to use npm version 2. To update it you can use this command:
sudo npm install npm -g
This application uses computer vision and augmented reality techniques to detect a chroma in a WebRTC stream based
on color tracking.
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
Note: Modules can have options. For configuring these options, youll need to get the constructor for them. In
Javascript and Node, you have to use kurentoClient.getComplexType(qualifiedName) . There is an example in the
code.
The media pipeline of this demo is is implemented in the JavaScript logic as follows:
...
kurento.register('kurento-module-chroma');
...
getKurentoClient(function(error, kurentoClient) {
if (error) {
return callback(error);
}
if (candidatesQueue[sessionId]) {
while(candidatesQueue[sessionId].length) {
var candidate = candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.
candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
sessions[sessionId] = {
'pipeline' : pipeline,
'webRtcEndpoint' : webRtcEndpoint
}
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
return callback(error);
}
});
});
});
});
});
}
var options = {
window: kurento.getComplexType('chroma.WindowParam')({
topRightCornerX: 5,
topRightCornerY: 5,
width: 30,
height: 30
})
}
pipeline.create('chroma.ChromaFilter', options, function(error, filter) {
if (error) {
return callback(error);
}
filter.connect(webRtcEndpoint, function(error) {
if (error) {
return callback(error);
}
return callback(null);
});
});
});
Dependencies
Dependencies of this demo are managed using NPM. Our main dependency is the Kurento Client JavaScript (kurento-
client). The relevant part of the package.json file for managing this dependency is:
"dependencies": {
"kurento-client" : "6.6.0"
}
At the client side, dependencies are managed using Bower. Take a look to the bower.json file and pay attention to the
following section:
"dependencies": {
"kurento-utils" : "6.6.2",
"kurento-module-pointerdetector": "6.6.0"
}
Note: We are in active development. You can find the latest versions at npm and Bower.
This web application consists on a WebRTC video communication in mirror (loopback) with a crowd detector filter.
This filter detects people agglomeration in video streams.
This web application consists on a WebRTC video communication in mirror (loopback) with a crowd detector filter.
This filter detects clusters of people in video streams.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-crowddetector-6.0 should be also installed:
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
The web application starts on port 8443 in the localhost by default. Therefore, open the URL https://localhost:8443/
in a WebRTC compliant browser (Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
This application uses computer vision and augmented reality techniques to detect a crowd in a WebRTC stream.
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
config.setFluidityLevelMin(10);
config.setFluidityLevelMed(35);
config.setFluidityLevelMax(65);
config.setFluidityNumFramesToEvent(5);
config.setOccupancyLevelMin(10);
config.setOccupancyLevelMed(35);
config.setOccupancyLevelMax(65);
config.setOccupancyNumFramesToEvent(5);
config.setSendOpticalFlowEvent(false);
config.setOpticalFlowNumFramesToEvent(3);
config.setOpticalFlowNumFramesToReset(3);
config.setOpticalFlowAngleOffset(0);
webRtcEndpoint.connect(crowdDetectorFilter);
crowdDetectorFilter.connect(webRtcEndpoint);
// addEventListener to crowddetector
crowdDetectorFilter.addCrowdDetectorDirectionListener(
new EventListener<CrowdDetectorDirectionEvent>() {
@Override
public void onEvent(CrowdDetectorDirectionEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "directionEvent");
response.addProperty("roiId", event.getRoiID());
response.addProperty("angle",
event.getDirectionAngle());
try {
session.sendMessage(new TextMessage(response
.toString()));
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
});
crowdDetectorFilter.addCrowdDetectorFluidityListener(
new EventListener<CrowdDetectorFluidityEvent>() {
@Override
public void onEvent(CrowdDetectorFluidityEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "fluidityEvent");
response.addProperty("roiId", event.getRoiID());
response.addProperty("level",
event.getFluidityLevel());
response.addProperty("percentage",
event.getFluidityPercentage());
try {
session.sendMessage(new TextMessage(response
.toString()));
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
});
crowdDetectorFilter.addCrowdDetectorOccupancyListener(
new EventListener<CrowdDetectorOccupancyEvent>() {
@Override
public void onEvent(CrowdDetectorOccupancyEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "occupancyEvent");
response.addProperty("roiId", event.getRoiID());
response.addProperty("level",
event.getOccupancyLevel());
response.addProperty("percentage",
event.getOccupancyPercentage());
try {
session.sendMessage(new TextMessage(response
.toString()));
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
});
webRtcEndpoint.gatherCandidates();
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This web application consists on a WebRTC video communication in mirror (loopback) with a crowd detector filter.
This filter detects people agglomeration in video streams.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-crowddetector-6.0 should be also installed:
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
Due to Same-origin policy, this demo has to be served by an HTTP server. A very simple way of doing this is by
means of an HTTP Node.js server which can be installed using npm :
You also need the source code of this demo. You can clone it from GitHub. Then start the HTTP server:
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
Kurento Media Server must use WebSockets over SSL/TLS (WSS), so make sure you check this too. It is possible to
locate the KMS in other machine simple adding the parameter ws_uri to the URL:
https://localhost:8443/index.html?ws_uri=wss://kms_host:kms_port/kurento
Notice that the Kurento Media Server must connected using a Secure WebSocket (i.e., the KMS URI starts with
wss:// ). For this reason, the support for secure WebSocket must be enabled in the Kurento Media Server you are using
to run this tutorial. For further information about securing applications, please visit the following page.
This application uses computer vision and augmented reality techniques to detect a crowd in a WebRTC stream.
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
The complete source code of this demo can be found in GitHub.
This example is a modified version of the Magic Mirror tutorial. In this case, this demo uses a CrowdDetector instead
of FaceOverlay filter.
To setup a CrowdDetectorFilter, first we need to define one or more region of interests (ROIs). A ROI delimits
the zone within the video stream in which crowd are going to be tracked. To define a ROI, we need to configure at
least three points. These points are defined in relative terms (0 to 1) to the video width and height.
CrowdDetectorFilter performs two actions in the defined ROIs. On the one hand, the detected crowd are
colored over the stream. On the other hand, different events are raised to the client.
To understand crowd coloring, we can take a look to an screenshot of a running example of
CrowdDetectorFilter. In the picture below, we can see that there are two ROIs (bounded with white lines
in the video). On these ROIs, we can see two different colors over the original video stream: red zones are drawn over
detected static crowds (or moving slowly). Blue zones are drawn over the detected crowds moving fast.
CrowdDetectorFluidityEvent. Event raised when a certain level of fluidity is detected in a ROI. Fluidity can be
seen as the level of general movement in a crowd.
CrowdDetectorOccupancyEvent. Event raised when a level of occupancy is detected in a ROI. Occupancy can
be seen as the level of agglomeration in stream.
CrowdDetectorDirectionEvent. Event raised when a movement direction is detected in a ROI by a crowd.
Both fluidity as occupancy are quantified in a relative metric from 0 to 100%. Then, both attributes are qualified into
three categories: i) Minimum (min); ii) Medium (med); iii) Maximum (max).
Regarding direction, it is quantified as an angle (0-360), where 0 is the direction from the central point of the video
to the top (i.e., north), 90 correspond to the direction to the right (east), 180 is the south, and finally 270 is the west.
With all these concepts, now we can check out the Java server-side code of this demo. As depicted in the snippet
below, we create a ROI by adding RelativePoint instances to a list. Each ROI is then stored into a list of
RegionOfInterest instances.
Then, each ROI should be configured. To do that, we have the following methods:
fluidityLevelMin: Fluidity level (0-100%) for the category minimum.
fluidityLevelMed: Fluidity level (0-100%) for the category medium.
fluidityLevelMax: Fluidity level (0-100%) for the category maximum.
fluidityNumFramesToEvent: Number of consecutive frames detecting a fluidity level to rise a event.
occupancyLevelMin: Occupancy level (0-100%) for the category minimum.
occupancyLevelMed: Occupancy level (0-100%) for the category medium.
occupancyLevelMax: Occupancy level (0-100%) for the category maximum.
occupancyNumFramesToEvent: Number of consecutive frames detecting a occupancy level to rise a
event.
sendOpticalFlowEvent: Boolean value that indicates whether or not directions events are going to be
tracked by the filter. Be careful with this feature, since it is very demanding in terms of resource usage (CPU,
memory) in the media server. Set to true this parameter only when you are going to need directions events in
your client-side.
opticalFlowNumFramesToEvent: Number of consecutive frames detecting a direction level to rise a
event.
opticalFlowNumFramesToReset: Number of consecutive frames detecting a occupancy level in which
the counter is reset.
opticalFlowAngleOffset: Counterclockwise offset of the angle. This parameters is useful to move the
default axis for directions (0=north, 90=east, 180=south, 270=west).
Note: Modules can have options. For configuring these options, youll need to get the constructor for them. In
Javascript and Node, you have to use kurentoClient.getComplexType(qualifiedName) . There is an example in the
code.
...
client.create('MediaPipeline', function(error, p) {
if (error) return onError(error);
pipeline = p;
console.log("Got MediaPipeline");
console.log("Got WebRtcEndpoint");
webRtc.gatherCandidates(onError);
webRtcPeer.processAnswer(sdpAnswer);
});
var options =
{
rois:
[
RegionOfInterest({
id: 'roi1',
points:
[
RelativePoint({x: 0, y: 0}),
RelativePoint({x: 0.5, y: 0}),
RelativePoint({x: 0.5, y: 0.5}),
RelativePoint({x: 0, y: 0.5})
],
regionOfInterestConfig: RegionOfInterestConfig({
occupancyLevelMin: 10,
occupancyLevelMed: 35,
occupancyLevelMax: 65,
occupancyNumFramesToEvent: 5,
fluidityLevelMin: 10,
fluidityLevelMed: 35,
fluidityLevelMax: 65,
fluidityNumFramesToEvent: 5,
sendOpticalFlowEvent: false,
opticalFlowNumFramesToEvent: 3,
opticalFlowNumFramesToReset: 3,
opticalFlowAngleOffset: 0
})
})
]
}
console.log("Connecting...");
Note: The TURN and STUN servers to be used can be configured simple adding the parameter ice_servers to
the application URL, as follows:
https://localhost:8443/index.html?ice_servers=[{"urls":"stun:stun1.example.net"},{
"urls":"stun:stun2.example.net"}]
https://localhost:8443/index.html?ice_servers=[{"urls":"turn:turn.example.org",
"username":"user","credential":"myPassword"}]
Dependencies
The dependencies of this demo has to be obtained using Bower. The definition of these dependencies are defined in
the bower.json file, as follows:
"dependencies": {
"kurento-client": "6.6.0",
"kurento-utils": "6.6.2"
"kurento-module-pointerdetector": "6.6.0"
}
bower install
Note: We are in active development. You can find the latest versions at Bower.
This web application consists on a WebRTC video communication in mirror (loopback) with a crowd detector filter.
This filter detects people agglomeration in video streams.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-crowddetector-6.0 should be also installed:
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
To launch the application, you need to clone the GitHub project where this demo is hosted, install it and run it:
If you have problems installing any of the dependencies, please remove them and clean the npm cache, and try to
install them again:
rm -r node_modules
npm cache clean
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the argument ws_uri to the
npm execution command, as follows:
In this case you need to use npm version 2. To update it you can use this command:
This application uses computer vision and augmented reality techniques to detect a crowd in a WebRTC stream.
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
Regarding direction, it is quantified as an angle (0-360), where 0 is the direction from the central point of the video
to the top (i.e., north), 90 correspond to the direction to the right (east), 180 is the south, and finally 270 is the west.
With all these concepts, now we can check out the Java server-side code of this demo. As depicted in the snippet
below, we create a ROI by adding RelativePoint instances to a list. Each ROI is then stored into a list of
RegionOfInterest instances.
Then, each ROI should be configured. To do that, we have the following methods:
fluidityLevelMin: Fluidity level (0-100%) for the category minimum.
fluidityLevelMed: Fluidity level (0-100%) for the category medium.
fluidityLevelMax: Fluidity level (0-100%) for the category maximum.
fluidityNumFramesToEvent: Number of consecutive frames detecting a fluidity level to rise a event.
occupancyLevelMin: Occupancy level (0-100%) for the category minimum.
occupancyLevelMed: Occupancy level (0-100%) for the category medium.
occupancyLevelMax: Occupancy level (0-100%) for the category maximum.
occupancyNumFramesToEvent: Number of consecutive frames detecting a occupancy level to rise a
event.
sendOpticalFlowEvent: Boolean value that indicates whether or not directions events are going to be
tracked by the filter. Be careful with this feature, since it is very demanding in terms of resource usage (CPU,
memory) in the media server. Set to true this parameter only when you are going to need directions events in
your client-side.
opticalFlowNumFramesToEvent: Number of consecutive frames detecting a direction level to rise a
event.
opticalFlowNumFramesToReset: Number of consecutive frames detecting a occupancy level in which
the counter is reset.
opticalFlowAngleOffset: Counterclockwise offset of the angle. This parameters is useful to move the
default axis for directions (0=north, 90=east, 180=south, 270=west).
Note: Modules can have options. For configuring these options, youll need to get the constructor for them. In
Javascript and Node, you have to use kurentoClient.getComplexType(qualifiedName) . There is an example in the
code.
...
kurento.register('kurento-module-crowddetector');
const RegionOfInterest = kurento.getComplexType('crowddetector.RegionOfInterest
');
getKurentoClient(function(error, kurentoClient) {
if (error) {
return callback(error);
}
if (candidatesQueue[sessionId]) {
while(candidatesQueue[sessionId].length) {
var candidate = candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.
candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
sessions[sessionId] = {
'pipeline' : pipeline,
'webRtcEndpoint' : webRtcEndpoint
}
return callback(null, 'sdpAnswer', sdpAnswer);
});
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
return callback(error);
}
});
});
});
});
});
}
var options = {
rois: [
RegionOfInterest({
id: 'roi1',
points: [
RelativePoint({x: 0 , y: 0 }),
RelativePoint({x: 0.5, y: 0 }),
RelativePoint({x: 0.5, y: 0.5}),
RelativePoint({x: 0 , y: 0.5})
],
regionOfInterestConfig: RegionOfInterestConfig({
occupancyLevelMin: 10,
occupancyLevelMed: 35,
occupancyLevelMax: 65,
occupancyNumFramesToEvent: 5,
fluidityLevelMin: 10,
fluidityLevelMed: 35,
fluidityLevelMax: 65,
fluidityNumFramesToEvent: 5,
sendOpticalFlowEvent: false,
opticalFlowNumFramesToEvent: 3,
opticalFlowNumFramesToReset: 3,
opticalFlowAngleOffset: 0
})
})
]
}
pipeline.create('crowddetector.CrowdDetectorFilter', options, function(error,
filter) {
if (error) {
return callback(error);
}
Dependencies
Dependencies of this demo are managed using NPM. Our main dependency is the Kurento Client JavaScript (kurento-
client). The relevant part of the package.json file for managing this dependency is:
"dependencies": {
"kurento-client" : "6.6.0"
}
At the client side, dependencies are managed using Bower. Take a look to the bower.json file and pay attention to the
following section:
"dependencies": {
"kurento-utils" : "6.6.2",
"kurento-module-pointerdetector": "6.6.0"
}
Note: We are in active development. You can find the latest versions at npm and Bower.
This web application consists on a WebRTC video communication in mirror (loopback) with a plate detector filter
element.
This web application consists on a WebRTC video communication in mirror (loopback) with a plate detector filter
element.
Note: This tutorial has been configured to use https. Follow the instructions to secure your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-platedetector-6.0 should be also installed:
Warning: Plate detector module is a prototype and its results is not always accurate. Consider this if you are
planning to use this module in a production environment.
To launch the application, you need to clone the GitHub project where this demo is hosted, and then run the main
class:
The web application starts on port 8443 in the localhost by default. Therefore, open the URL https://localhost:8443/
in a WebRTC compliant browser (Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the flag kms.url to the JVM
executing the demo. As well be using maven, you should execute the following command
This application uses computer vision and augmented reality techniques to detect a plate in a WebRTC stream on
optical character recognition (OCR).
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
.build();
user.setWebRtcEndpoint(webRtcEndpoint);
users.put(session.getId(), user);
webRtcEndpoint
.addIceCandidateFoundListener(new EventListener<IceCandidateFoundEvent>()
{
@Override
public void onEvent(IceCandidateFoundEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "iceCandidate");
response.add("candidate", JsonUtils
.toJsonObject(event.getCandidate()));
try {
synchronized (session) {
session.sendMessage(new TextMessage(
response.toString()));
}
} catch (IOException e) {
log.debug(e.getMessage());
}
}
});
webRtcEndpoint.connect(plateDetectorFilter);
plateDetectorFilter.connect(webRtcEndpoint);
plateDetectorFilter
.addPlateDetectedListener(new EventListener<PlateDetectedEvent>() {
@Override
public void onEvent(PlateDetectedEvent event) {
JsonObject response = new JsonObject();
response.addProperty("id", "plateDetected");
response.addProperty("plate", event.getPlate());
try {
session.sendMessage(new TextMessage(response
.toString()));
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
});
synchronized (session) {
session.sendMessage(new TextMessage(response.toString()));
}
webRtcEndpoint.gatherCandidates();
} catch (Throwable t) {
sendError(session, t.getMessage());
}
}
Dependencies
This Java Spring application is implemented using Maven. The relevant part of the pom.xml is where Kurento depen-
dencies are declared. As the following snippet shows, we need two dependencies: the Kurento Client Java dependency
(kurento-client) and the JavaScript Kurento utility library (kurento-utils) for the client-side. Other client libraries are
managed with webjars:
<dependencies>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-client</artifactId>
</dependency>
<dependency>
<groupId>org.kurento</groupId>
<artifactId>kurento-utils-js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>demo-console</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>adapter.js</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>jquery</artifactId>
</dependency>
<dependency>
<groupId>org.webjars.bower</groupId>
<artifactId>ekko-lightbox</artifactId>
</dependency>
</dependencies>
Note: We are in active development. You can find the latest version of Kurento Java Client at Maven Central.
Kurento Java Client has a minimum requirement of Java 7. Hence, you need to include the following properties in
your pom:
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
This web application consists on a WebRTC video communication in mirror (loopback) with a plate detector filter
element.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-platedetector-6.0 should be also installed:
Warning: Plate detector module is a prototype and its results is not always accurate. Consider this if you are
planning to use this module in a production environment.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
Due to Same-origin policy, this demo has to be served by an HTTP server. A very simple way of doing this is by
means of an HTTP Node.js server which can be installed using npm :
You also need the source code of this demo. You can clone it from GitHub. Then start the HTTP server:
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
Kurento Media Server must use WebSockets over SSL/TLS (WSS), so make sure you check this too. It is possible to
locate the KMS in other machine simple adding the parameter ws_uri to the URL:
https://localhost:8443/index.html?ws_uri=wss://kms_host:kms_port/kurento
Notice that the Kurento Media Server must connected using a Secure WebSocket (i.e., the KMS URI starts with
wss:// ). For this reason, the support for secure WebSocket must be enabled in the Kurento Media Server you are using
to run this tutorial. For further information about securing applications, please visit the following page.
This application uses computer vision and augmented reality techniques to detect a plate in a WebRTC stream on
optical character recognition (OCR).
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
Note: Modules can have options. For configuring these options, youll need to get the constructor for them. In
Javascript and Node, you have to use kurentoClient.getComplexType(qualifiedName) . There is an example in the
code.
The following snippet shows how the media pipeline is implemented in the Java server-side code of the
demo. An important issue in this code is that a listener is added to the PlateDetectorFilter object
(addPlateDetectedListener). This way, each time a plate is detected in the stream, a message is sent to
the client side. As shown in the screenshot below, this event is printed in the console of the GUI.
...
kurentoClient.register('kurento-module-platedetector')
...
pipeline = _pipeline;
console.log("Got MediaPipeline");
console.log("Got WebRtcEndpoint");
webRtc.gatherCandidates(onError);
webRtcPeer.processAnswer(sdpAnswer);
});
console.log("Got Filter");
Note: The TURN and STUN servers to be used can be configured simple adding the parameter ice_servers to
the application URL, as follows:
https://localhost:8443/index.html?ice_servers=[{"urls":"stun:stun1.example.net"},{
"urls":"stun:stun2.example.net"}]
https://localhost:8443/index.html?ice_servers=[{"urls":"turn:turn.example.org",
"username":"user","credential":"myPassword"}]
Dependencies
The dependencies of this demo has to be obtained using Bower. The definition of these dependencies are defined in
the bower.json file, as follows:
"dependencies": {
"kurento-client": "6.6.0",
"kurento-utils": "6.6.2"
"kurento-module-pointerdetector": "6.6.0"
}
bower install
Note: We are in active development. You can find the latest versions at Bower.
This web application consists on a WebRTC video communication in mirror (loopback) with a plate detector filter
element.
Note: This tutorial has been configurated for using https. Follow these instructions for securing your application.
First of all, you should install Kurento Media Server to run this demo. Please visit the installation guide for further
information. In addition, the built-in module kms-platedetector-6.0 should be also installed:
Warning: Plate detector module is a prototype and its results is not always accurate. Consider this if you are
planning to use this module in a production environment.
Be sure to have installed Node.js and Bower in your system. In an Ubuntu machine, you can install both as follows:
To launch the application, you need to clone the GitHub project where this demo is hosted, install it and run it:
If you have problems installing any of the dependencies, please remove them and clean the npm cache, and try to
install them again:
rm -r node_modules
npm cache clean
Finally, access the application connecting to the URL https://localhost:8443/ through a WebRTC capable browser
(Chrome, Firefox).
Note: These instructions work only if Kurento Media Server is up and running in the same machine as the tutorial.
However, it is possible to connect to a remote KMS in other machine, simply adding the argument ws_uri to the
npm execution command, as follows:
In this case you need to use npm version 2. To update it you can use this command:
This application uses computer vision and augmented reality techniques to detect a plate in a WebRTC stream on
optical character recognition (OCR).
The interface of the application (an HTML web page) is composed by two HTML5 video tags: one for the video
camera stream (the local client-side stream) and other for the mirror (the remote stream). The video camera stream is
sent to Kurento Media Server, which processes and sends it back to the client as a remote stream. To implement this,
we need to create a Media Pipeline composed by the following Media Element s:
Note: Modules can have options. For configuring these options, youll need to get the constructor for them. In
Javascript and Node, you have to use kurentoClient.getComplexType(qualifiedName) . There is an example in the
code.
The following snippet shows how the media pipeline is implemented in the Java server-side code of the
demo. An important issue in this code is that a listener is added to the PlateDetectorFilter object
(addPlateDetectedListener). This way, each time a plate is detected in the stream, a message is sent to
the client side. As shown in the screenshot below, this event is printed in the console of the GUI.
...
kurento.register('kurento-module-platedetector');
...
getKurentoClient(function(error, kurentoClient) {
if (error) {
return callback(error);
}
if (candidatesQueue[sessionId]) {
while(candidatesQueue[sessionId].length) {
var candidate = candidatesQueue[sessionId].shift();
webRtcEndpoint.addIceCandidate(candidate);
}
}
webRtcEndpoint.on('OnIceCandidate', function(event) {
var candidate = kurento.getComplexType('IceCandidate')(event.
candidate);
ws.send(JSON.stringify({
id : 'iceCandidate',
candidate : candidate
}));
});
sessions[sessionId] = {
'pipeline' : pipeline,
'webRtcEndpoint' : webRtcEndpoint
}
return callback(null, 'sdpAnswer', sdpAnswer);
});
webRtcEndpoint.gatherCandidates(function(error) {
if (error) {
return callback(error);
}
});
});
});
});
});
}
Dependencies
Dependencies of this demo are managed using NPM. Our main dependency is the Kurento Client JavaScript (kurento-
client). The relevant part of the package.json file for managing this dependency is:
"dependencies": {
"kurento-client" : "6.6.0"
}
At the client side, dependencies are managed using Bower. Take a look to the bower.json file and pay attention to the
following section:
"dependencies": {
"kurento-utils" : "6.6.2",
"kurento-module-pointerdetector": "6.6.0"
}
Note: We are in active development. You can find the latest versions at npm and Bower.
WebRTC Statistics
WebRTC Statistics
Introduction
WebRTC streams (audio, video, or data) can be lost, and experience varying amounts of network delay. In order to
assess the performance of WebRTC applications, it could be required to be able to monitor the WebRTC features of
the underlying network and media pipeline.
To that aim, Kurento provides WebRTC statistics gathering for the server-side (Kurento Media Server, KMS). The
implementation of this capability follows the guidelines provided in the W3C WebRTCs Statistics API. Therefore,
the statistics gathered in the KMS can be divided into two groups:
inboundrtp: statistics on the stream received in the KMS.
outboundrtp: statistics on the stream sent by KMS.
API description
As usual, WebRTC statistics gathering capability is provided by the KMS and is consumed by means of the different
Kurento client implementations (Java, JavaScript clients are provided out of the box). To read these statistics, first it
should be enabled using the method setLatencyStats of a Media Pipeline object. Using the Kurento Java client
this is done as follows:
// ...
349
Kurento Documentation, Release 6.6.1
// ...
});
});
});
Once WebRTC statistics are enabled, the second step is reading the statistics values using the method getStats of
a Media Element, For example, to read the statistics of a WebRtcEndpoint object in Java:
// ...
// ...
});
});
Notice that the WebRTC statistics are read as a map. Therefore, each entry of this collection has a key and a value, in
which the key is the specific statistic, with a given value at the reading time. Take into account that these values make
reference to real-time properties, and so these values vary in time depending on multiple factors (for instance network
performance, KMS load, and so on). The complete description of the statistics are defined in the KMD interface
description. The most relevant statistics are listed below:
ssrc: The synchronized source (SSRC).
firCount: Count the total number of Full Intra Request (FIR) packets received by the sender. This metric is
only valid for video and is sent by receiver.
pliCount: Count the total number of Packet Loss Indication (PLI) packets received by the sender and is sent
by receiver.
nackCount: Count the total number of Negative ACKnowledgement (NACK) packets received by the sender
and is sent by receiver.
sliCount: Count the total number of Slice Loss Indication (SLI) packets received by the sender. This metric
is only valid for video and is sent by receiver.
remb: The Receiver Estimated Maximum Bitrate (REMB). This metric is only valid for video.
packetsLost: Total number of RTP packets lost for this SSRC.
packetsReceived: Total number of RTP packets received for this SSRC.
bytesReceived: Total number of bytes received for this SSRC.
jitter: Packet Jitter measured in seconds for this SSRC.
Example
There is a running tutorial which uses the WebRTC gathering as described before. This demo has been implemented
using the JavaScript client and it is available on GitHub: kurento-loopback-stats.
From a the Media Pipeline point of view, this demo application consists in a WebRtcEndpoint in loopback. Once
the demo is up and running, WebRTC are enabled and gathered with a rate of 1 second.
In addition to the KMS WebRTC statistics, the client-side (i.e. browser WebRtc peer) are also gathered by the ap-
plication. This is done using the standard method provided by the peerConnection object, i.e using its method
getStats. Please check out the JavaScript logic located in the index.js file for implementation details.
Both kinds of WebRTC statistics values (i.e. browser and KMS side) are updated and shown each second in the
application GUI, as follows:
Kurento Utils JS
Kurento Utils JS
Overview
Kurento Utils is a wrapper object of an RTCPeerConnection. This object is aimed to simplify the development of
WebRTC-based applications.
The source code of this project can be cloned from the GitHub repository.
How to use it
<script
src="bower_components/kurento-utils/js/kurento-utils.js"></script>
353
Kurento Documentation, Release 6.6.1
Examples
There are several tutorials that show kurento-utils used in complete WebRTC applications developed on Java, Node
and JavaScript. These tutorials are in GitHub, and you can download and run them at any time.
Java - https://github.com/Kurento/kurento-tutorial-java
Node - https://github.com/Kurento/kurento-tutorial-node
JavaScript - https://github.com/Kurento/kurento-tutorial-js
In the following lines we will show how to use the library to create an RTCPeerConnection, and how to negotiate
the connection with another peer. The library offers a WebRtcPeer object, which is a wrapper of the browsers
RTCPeerConnection API. Peer connections can be of different types: unidirectional (send or receive only) or bidirec-
tional (send and receive). The following code shows how to create the latter, in order to be able to send and receive
media (audio and video). The code assumes that there are two video tags in the page that loads the script. These tags
will be used to show the video as captured by your own client browser, and the media received from the other peer.
The constructor receives a property that holds all the information needed for the configuration.
var constraints = {
audio: true,
video: {
width: 640,
framerate: 15
}
};
var options = {
localVideo: videoInput,
remoteVideo: videoOutput,
onicecandidate : onIceCandidate,
mediaConstraints: constraints
};
this.generateOffer(onOffer)
});
With this little code, the library takes care of creating the RTCPeerConnection, and invoking getUserMedia in
the browser if needed. The constraints in the property are used in the invocation, and in this case both microphone and
webcam will be used. However, this does not create the connection. This is only achieved after completing the SDP
negotiation between peers. This process implies exchanging SDPs offer and answer and, since Trickle ICE is used, a
number of candidates describing the capabilities of each peer. How the negotiation works is out of the scope of this
document. More info can be found in this link.
In the previous piece of code, when the webRtcPeer object gets created, the SDP offer is generated with this.
generateOffer(onOffer). The only argument passed is a function, that will be invoked one the browsers peer
connection has generated that offer. The onOffer callback method is responsible for sending this offer to the other
peer, by any means devised in your application. Since that is part of the signaling plane and business logic of each
particular application, it wont be covered in this document.
Assuming that the SDP offer has been received by the remote peer, it must have generated an SDP answer, that should
be received in return. This answer must be processed by the webRtcEndpoint, in order to fulfill the negotiation. This
could be the implementation of the onOffer callback function. Weve assumed that theres a function somewhere in
the scope, that allows sending the SDP to the remote peer.
function onOffer(error, sdpOffer) {
if (error) return onError(error);
As weve commented before, the library assumes the use of Trickle ICE to complete the connection between both
peers. In the configuration of the webRtcPeer, there is a reference to a onIceCandidate callback function. The
library will use this function to send ICE candidates to the remote peer. Since this is particular to each application, we
will just show the signature
function onIceCandidate(candidate) {
// Send the candidate to the remote peer
}
In turn, our client application must be able to receive ICE candidates from the remote peer. Assuming the signaling
takes care of receiving those candidates, it is enough to invoke the following method in the webRtcPeer to consider
the ICE candidate
webRtcPeer.addIceCandidate(candidate);
WebRTC data channels lets you send text or binary data over an active WebRTC connection. The WebRtcPeer object
can provide access to this functionality by using the RTCDataChannel form the wrapped RTCPeerConnection object.
This allows you to inject into and consume data from the pipeline. This data can be treated by each endpoint differently.
For instance, a WebRtcPeer object in the browser, will have the same behavior as the RTCDataChannel (you can
see a description here). Other endpoints could make use of this channel to send information: a filter that detects QR
codes in a video stream, could send the detected code to the clients through a data channel. This special behavior
should be specified in the filter.
The use of data channels in the WebRtcPeer object is indicated by passing the dataChannels flag in the options
bag, along with the desired options.
var options = {
localVideo : videoInput,
remoteVideo : videoOutput,
dataChannels : true,
dataChannelConfig: {
id : getChannelName(),
onmessage : onMessage,
onopen : onOpen,
onclose : onClosed,
onbufferedamountlow : onbufferedamountlow,
onerror : onerror
},
onicecandidate : onIceCandidate
}
The values in dataChannelConfig are all optional. Once the webRtcPeer object is created, and after the
connection has been successfully negotiated, users can send data through the data channel
The format of the data you are sending, is determined by your application, and the definition of the endpoints that you
are using.
The lifecycle of the underlying RTCDataChannel, is tied to that of the webRtcPeer: when the webRtcPeer.
dispose() method is invoked, the data channel will be closed and released too.
Reference documentation
WebRtcPeer
* webcam
* screen
* window
onstreamended: Method that will be invoked when stream ended event happens
onicecandidate: Method that will be invoked when ice candidate event happens
oncandidategatheringdone: Method that will be invoked when all candidates have been harvested
dataChannels: Flag for enabling the use of data channels. If true, then a data channel will be created in
the RTCPeerConnection object.
dataChannelConfig: It is a JSON object with the configuration passed to the DataChannel when created.
It supports the following keys:
* id: Specifies the id of the data channel. If none specified, the same id of the WebRtcPeer object will
be used.
* onmessage: Function invoked in the onmessage event of the data channel. This event is fired every
time a message is received.
* onbufferedamountlow: Is the event handler called when the bufferedamountlow event is re-
ceived. Such an event is sent when RTCDataChannel.bufferedAmount drops to less than
or equal to the amount specified by the RTCDataChannel.bufferedAmountLowThreshold
property.
* onerror: Callback function onviked when an error in the data channel is produced. If none is provided,
an error trace message will be logged in the browser console.
simulcast: Indicates whether simulcast is going to be used. Value is true|false
configuration: It is a JSON object where ICE Servers are defined using
[{"urls":"stun:stun1.example.net"},{"urls":"stun:stun2.example.net"}]
MediaConstraints
Constraints provide a general control surface that allows applications to both select an appropriate source for a track
and, once selected, to influence how a source operates. getUserMedia() uses constraints to help select an appro-
priate source for a track and configure it. For more information about media constraints and its values, you can check
here.
By default, if the mediaConstraints is undefined, this constraints are used when getUserMedia is called:
{
audio: true,
video: {
width: 640,
framerate: 15
}
}
If mediaConstraints has any value, the library uses this value for the invocation of getUserMedia. It is up to the
browser whether those constraints are accepted or not.
In the examples section, there is one example about the use of media constraints.
Methods
getPeerConnection
Using this method the user can get the peerConnection and use it directly.
showLocalVideo
getLocalStream
Using this method the user can get the local stream. You can use muted property to silence the audio, if this property
is true.
getRemoteStream
Using this method the user can get the remote stream.
getCurrentFrame
Using this method the user can get the current frame and get a canvas with an image of the current frame.
processAnswer
Callback function invoked when a SDP answer is received. Developers are expected to invoke this function in order
to complete the SDP negotiation. This method has two parameters:
sdpAnswer: Description of sdpAnswer
callback: It is a function with error like parameter. It is called when the remote description has been set
successfully.
processOffer
Callback function invoked when a SDP offer is received. Developers are expected to invoke this function in order to
complete the SDP negotiation. This method has two parameters:
sdpOffer: Description of sdpOffer
callback: It is a function with error and sdpAnswer like parameters. It is called when the remote description
has been set successfully.
dispose
addIceCandidate
Callback function invoked when an ICE candidate is received. Developers are expected to invoke this function in order
to complete the SDP negotiation. This method has two parameters:
iceCandidate: Literal object with the ICE candidate description
callback: It is a function with error like parameter. It is called when the ICE candidate has been added.
getLocalSessionDescriptor
Using this method the user can get peerconnections local session descriptor.
getRemoteSessionDescriptor
Using this method the user can get peerconnections remote session descriptor.
generateOffer
Creates an offer that is a request to find a remote peer with a specific configuration.
Screen and window sharing depends on the privative module kurento-browser-extensions. To enable its support, youll
need to install the package dependency manually or provide a getScreenConstraints function yourself on runtime. The
option sendSource could be window or screen before create a WebRtcEndpoint. If its not available, when trying to
share the screen or a window content it will throw an exception.
Souce code
Alternatively, you can download the code using Git and install manually its dependencies:
After you download the project, to build the browser version of the library youll only need to execute the grunt task
runner. The file needed will be generated on the dist folder. Alternatively, if you dont have it globally installed, you
can run a local copy by executing:
cd kurento-utils
node_modules/.bin/grunt
kurento-client-java
361
Kurento Documentation, Release 6.6.1
kurento-client-js
363
Kurento Documentation, Release 6.6.1
kurento-utils-js
365
Kurento Documentation, Release 6.6.1
Starting with Chrome 47, WebRTC is only allowed from SECURE ORIGINS (HTTPS or localhost). Check their
release notes for further information about this issue.
Note: Keep in mind that serving your application through HTTPS, forces you to use WebSockets Secure (WSS) if
you are using websockets to control your application server.
server.port: 8443
server.ssl.key-store: keystore.jks
server.ssl.key-store-password: yourPassword
367
Kurento Documentation, Release 6.6.1
server.ssl.keyStoreType: JKS
server.ssl.keyAlias: yourKeyAlias
You can also specify the location of the properties file. When launching your Spring-Boot based
app, issue the flag -Dspring.config.location=<path-to-properties> .
Start application
Note: If you plan on using a webserver as proxy, like Nginx or Apache, youll need to setAllowedOrigins
when registering the handler. Please read the official Spring documentation entry for more info.
...
var express = require('express');
var ws = require('ws');
var fs = require('fs');
var https = require('https');
...
var options =
{
key: fs.readFileSync('key/server.key'),
cert: fs.readFileSync('keys/server.crt')
};
wss.on('connection', function(ws) {
....
Start application
npm start
First, you need to change the configuration file of Kurento Media Server, i.e. /etc/kurento/kurento.conf.
json, uncommenting the following lines:
"secure": {
"port": 8433,
"certificate": "defaultCertificate.pem",
"password": ""
},
If this PEM certificate is a signed certificate (by a Certificate Authority such as Verisign), then you are done. If you
are going to use a self-signed certificate (suitable for development), then there is still more work to do.
You can generate a self signed certificate by doing this:
Due to the fact that the certificate is self-signed, applications will reject it by default. For this reason, youll need to
force them to accept it.
Browser applications: Youll need to manually accept the certificate as trusted one before secure WebSocket
connections can be established. By default, this can be done by connecting to connecting to https://localhost:
8433/kurento and accepting the certificate in the browser.
Java applications, follow the instructions of this link (get InstallCert.java from here). Youll need to
instruct the KurentoClient needs to be configured to allow the use of certificates. For this purpose, we need
to create our own JsonRpcClient:
Second, you have to change the WebSocket URI in your application logic. For instance, in the hello-world application
within the tutorials, this would be done as follows:
Java: Changing this line in HelloWorldApp.java:
Kurento FAQ
371
Kurento Documentation, Release 6.6.1
This is a list of Frequently Asked Questions about Kurento. Feel free to suggest new entries or different wording for
answers!
373
Kurento Documentation, Release 6.6.1
374
CHAPTER 32
How do I...
If you are installing Kurento in a NAT environment (i.e. in any cloud provider), youll need to provide a
STUN server configuration in /etc/kurento/modules/kurento/WebRtcEndpoint.conf.
ini. Apart from that, you will have to open all UDP ports in your security group, as STUN will use any
port available from the whole 0-65535 range.
Though for most situations its enough to configure a STUN server in the KMS configuration files, you
might need to install a TURN server, for example coturn. Here are some instructions on how to install this
TURN server for Kurento:
1. Download the package from the projects page.
2. Extract the contents. You should have a INSTALL file with instructions, and a .deb package. Follow
the instructions to install the package.
3. Once the package is installed, youll need to modify the startup script in /etc/init.d/coturn.
Add the external and local IPs as vars:
EXTERNAL_IP=$(curl http://169.254.169.254/latest/meta-data/public-ipv4)
LOCAL_IP=$(curl http://169.254.169.254/latest/meta-data/local-ipv4)
Modify the DAEMON_ARGS var to take these IPs into account, along with the long-term creden-
tials user and password (kurento:kurento in this case, but could be different), realm and some
other options:
4. Then lets enable the turnserver to run as an automatic service daemon. For this, open the file /etc/
default/coturn and uncomment the key:
TURNSERVER_ENABLED=1
375
Kurento Documentation, Release 6.6.1
5. Now, you have to tell the Kurento server where is the turnserver installed. For this, modify the turnURL
key in /etc/kurento/modules/kurento/WebRtcEndpoint.conf.ini:
turnURL=kurento:kurento@<public-ip>:3478
stunServerAddress=<public-ip>
stunServerPort=3478
Note: While the RFC specifies the ports used by TURN, if you are using STUN you will need to open all UDP ports,
as those ports are not constrained.
6. The last thing to do, is to start the coturn server and the media server:
Note: Please do make sure you check your installation using this test application
Media Elements can only communicate with each other when they are part of the same pipeline. Different
MediaPipelines in the server are independent do not share audio, video, data or events.
A good heuristic is that you will need one pipeline per each set of communicating partners in a channel,
and one Endpoint in this pipeline per audio/video streams reaching a partner.
Your application will need to create an Endpoint for each media stream flowing to (or from) the pipeline.
As we said in the previous answer, each set of communicating partners in a channel will be in the same
Media Pipeline, and each of them will use one or more Endpoints. They could use more than one if they
are recording or reproducing several streams.
Kurento API currently offers no way to get application attributes stored in a Media Element. How-
ever, the application developer can maintain a hashmap or equivalent data structure mapping the
WebRtcEndpoint internal Id (which is a string) to whatever application information is desired.
This is a typical error which happens when you update Kurento Media Server from version 4 to 5. The
problem is related to the GStreamer dependency version. The solution is the following:
377
Kurento Documentation, Release 6.6.1
Glossary
379
Kurento Documentation, Release 6.6.1
This is a glossary of terms that often appear in discussion about multimedia transmissions. Most of the terms are
described and linked to its wikipedia, RFC or W3C relevant documents. Some of the terms are specific to gstreamer
or kurento.
Agnostic, Media One of the big problems of media is that the number of variants of video and audio codecs, formats
and variants quickly creates high complexity in heterogeneous applications. So kurento developed the concept
of an automatic converter of media formats that enables development of agnostic elements. Whenever a media
elements source is connected to another media elements sink, the kurento framework verifies if media adaption
and transcoding is necessary and, if needed, it transparently incorporates the appropriate transformations making
possible the chaining of the two elements into the resulting Pipeline.
AVI Audio Video Interleaved, known by its initials AVI, is a multimedia container format introduced by Microsoft
in November 1992 as part of its Video for Windows technology. AVI files can contain both audio and video
data in a file container that allows synchronous audio-with-video playback. AVI is a derivative of the Resource
Interchange File Format (RIFF).
See also:
Wikipedia reference of the AVI format
Wikipedia reference of the RIFF format
Bower Bower is a package manager for the web. It offers a generic solution to the problem of front-end package
management, while exposing the package dependency model via an API that can be consumed by a build stack.
Builder Pattern The builder pattern is an object creation software design pattern whose intention is to find a solution
to the telescoping constructor anti-pattern. The telescoping constructor anti-pattern occurs when the increase of
object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous
constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by
step and then returns the resulting constructed object at once.
See also:
Wikipedia reference of the Builder Pattern
CORS
is a mechanism that allows JavaScript code on a web page to make XMLHttpRequests to different domains than
the one the JavaScript originated from. It works by adding new HTTP headers that allow servers to serve re-
sources to permitted origin domains. Browsers support these headers and enforce the restrictions they establish.
See also:
enable-cors.org for information on the relevance of CORS and how and when to enable it.
DOM
Document Object Model Document Object Model is a cross-platform and language-independent convention for
representing and interacting with objects in HTML, XHTML and XML documents.
EOS Acronym of End Of Stream. In Kurento some elements will raise an EndOfStream event when the media
they are processing is finished.
GStreamer GStreamer is a pipeline-based multimedia framework written in the C programming language.
H.264 A Video Compression Format. The H.264 standard can be viewed as a family of standards composed of a
number of profiles. Each specific decoder deals with at least one such profiles, but not necessarily all. See
See also:
RFC 6184 RTP Payload Format for H.264 Video. This RFC obsoletes RFC 3984.
HTTP The is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the
foundation of data communication for the World Wide Web.
381
Kurento Documentation, Release 6.6.1
See also:
RFC 2616
ICE
Interactive Connectivity Establishment Interactive Connectivity Establishment (ICE) is a technique used to
achieve NAT Traversal. ICE makes use of the STUN protocol and its extension, TURN. ICE can be used by
any protocol utilizing the offer/answer model.
See also:
RFC 5245
Wikipedia reference of ICE
IMS is
Mobile Architectural Framework for delivering IP Multimedia Services in 3G (and beyond) Mobile Networks.
See also:
RFC 3574
Java EE Java EE, or Java Platform, Enterprise Edition, is a standardised set of APIs for Enterprise software devel-
opment.
See also:
Oracle Site Java EE Overview
Wikipedia
jQuery jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML.
JSON JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is designed to be easy to
understand and write for humans and easy to parse for machines.
JSON-RPC JSON-RPC is a simple remote procedure call protocol encoded in JSON. JSON-RPC allows for notifi-
cations and for multiple calls to be sent to the server which may be answered out of order.
Kurento Kurento is a platform for the development of multimedia enabled applications. Kurento is the Esperanto
term for the English word stream. We chose this name because we believe the Esperanto principles are inspir-
ing for what the multimedia community needs: simplicity, openness and universality. Kurento is open source,
released under Apache 2.0, and has several components, providing solutions to most multimedia common ser-
vices requirements. Those components include: Kurento Media Server, Kurento API, Kurento Protocol, and
Kurento Client.
Kurento API Kurento API is an object oriented API to create media pipelines to control media. It can be seen as
and interface to Kurento Media Server. It can be used from the Kurento Protocol or from Kurento Clients.
Kurento Client A Kurento Client is a programming library (Java or JavaScript) used to control Kurento Media
Server from an application. For example, with this library, any developer can create a web application that uses
Kurento Media Server to receive audio and video from the user web browser, process it and send it back again
over Internet. Kurento Client exposes the Kurento API to app developers.
Kurento Protocol Communication between KMS and clients by means of JSON-RPC messages. It is based on
WebSocket that uses JSON-RPC V2.0 messages for making requests and sending responses.
Kurento Media Server Kurento Media Server is the core element of Kurento since it responsible for media trans-
mission, processing, loading and recording.
Maven Maven is a build automation tool used primarily for Java projects.
Media Element A Media Element is a module that encapsulates a specific media capability. For example
RecorderEndpoint, PlayerEndpoint, etc.
382
Kurento Documentation, Release 6.6.1
Media Pipeline A Media Pipeline is a chain of media elements, where the output stream generated by one element
(source) is fed into one or more other elements input streams (sinks). Hence, the pipeline represents a machine
capable of performing a sequence of operations over a stream.
Media Plane In the traditional , the handling of media is conceptually splitted in two layers. The one that handles the
media itself, with functionalities such as media transport, encoding/decoding, and processing, is called Media
Plane.
See also:
Signaling Plane
MP4 MPEG-4 Part 14 or MP4 is a digital multimedia format most commonly used to store video and audio, but can
also be used to store other data such as subtitles and still images.
See also:
Wikipedia definition of .
Multimedia Multimedia is concerned with the computer controlled integration of text, graphics, video, animation,
audio, and any other media where information can be represented, stored, transmitted and processed digitally.
There is a temporal relationship between many forms of media, for instance audio, video and animations. There
2 are forms of problems involved in
Sequencing within the media, i.e. playing frames in correct order or time frame.
Synchronisation, i.e. inter-media scheduling. For example, keeping video and audio synchronized or
displaying captions or subtitles in the required intervals.
See also:
Wikipedia definition of
Multimedia container format Container or wrapper formats are metafile formats whose specification describes how
different data elements and metadata coexist in a computer file.
Simpler multimedia container formats can contain different types of audio formats, while more advanced con-
tainer formats can support multiple audio and video streams, subtitles, chapter-information, and meta-data,
along with the synchronization information needed to play back the various streams together. In most cases, the
file header, most of the metadata and the synchro chunks are specified by the container format.
See also:
Wikipedia definition of
NAT
Network Address Translation Network address translation (NAT) is the technique of modifying network address
information in Internet Protocol (IP) datagram packet headers while they are in transit across a traffic routing
device for the purpose of remapping one IP address space into another.
See also:
definition at Wikipedia
NAT-T
NAT Traversal NAT traversal (sometimes abbreviated as NAT-T) is a general term for techniques that establish and
maintain Internet protocol connections traversing network address translation (NAT) gateways, which break
end-to-end connectivity. Intercepting and modifying traffic can only be performed transparently in the absence
of secure encryption and authentication.
See also:
NAT Traversal White Paper White paper on NAT-T and solutions for end-to-end connectivity in its presence
383
Kurento Documentation, Release 6.6.1
Node.js Node.js is a cross-platform runtime environment for server-side and networking applications. Node.js appli-
cations are written in JavaScript, and can be run within the Node.js runtime on OS X, Microsoft Windows and
Linux with no changes.
npm npm is the official package manager for Node.js.
OpenCL OpenCL is standard framework for cross-platform, parallel programming of heterogeneous platforms
consisting of central processing units (CPUs), graphics processing units (GPUs), digital signal processors
(DSPs), field-programmable gate arrays (FPGAs) and other processors.
OpenCV OpenCV (Open Source Computer Vision Library) is a BSD-licensed open source computer vision and
machine learning software library. OpenCV aims to provide a common infrastructure for computer vision
applications and to accelerate the use of machine perception.
Pad, Media A Media Pad is is an elements interface with the outside world. Data streams from the MediaSource
pad to another elements MediaSink pad.
See also:
GStreamer Pad Definition of the Pad structure in GStreamer
PubNub PubNub is a publish/subscribe cloud service for sending and routing data. It streams data to global audiences
on any device using persistent socket connections. PubNub has been designed to deliver data with low latencies
to end-user devices. These devices can be behind firewalls, NAT environments, and other hard-to-reach network
environments. PubNub provides message caching for retransmission of lost signals over unreliable network
environments. This is accomplished by maintaining an always open socket connection to every device.
QR QR code (Quick Response Code) is a type of two-dimensional barcode. that became popular in the mobile phone
industry due to its fast readability and greater storage capacity compared to standard UPC barcodes.
See also:
Entry in wikipedia
REST
is an architectural style consisting of a coordinated set of constraints applied to components, connectors, and
data elements, within a distributed hypermedia system. The term representational state transfer was introduced
and defined in 2000 by Roy Fielding in his doctoral dissertation.
RTCP The is a sister protocol of the RTP, that provides out-of-band statistics and control information for an RTP
flow.
See also:
RFC 3605
RTP The is a standard packet format designed for transmitting audio and video streams on IP networks. It is used in
conjunction with the RTP Control Protocol. Transmissions using
typically use SDP to describe the technical parameters of the media streams.
See also:
RFC 3550
Same-origin policy The is web application security model. The policy permits scripts running on pages originating
from the same site to access each others DOM with no specific restrictions, but prevents access to DOM on
different sites.
SDP
Session Description Protocol The describes initialization parameters for a streaming media session. Both parties
of a streaming media session exchange SDP files to negotiate and agree in the parameters to be used for the
streaming.
384
Kurento Documentation, Release 6.6.1
See also:
RFC 4566 Definition of Session Description Protocol
RFC 4568 Security Descriptions for Media Streams in SDP
Semantic Versioning
Semantic Versioning is a formal convention for specifying compatibility using a three-part version number:
major version; minor version; and patch.
Signaling Plane It is the layer of a media system in charge of the information exchanges concerning the establishment
and control of the different media circuits and the management of the network, in contrast to the transfer of
media, done by the Signaling Plane.
Functions such as media negotiation, QoS parametrization, call establishment, user registration, user presence,
etc. as managed in this plane.
See also:
Media Plane
Sink, Media A Media Sink is a MediaPad that outputs a Media Stream. Data streams from a MediaSource pad to
another elements MediaSink pad.
SIP
is a signaling plane protocol widely used for controlling multimedia communication sessions such as voice and
video calls over Internet Protocol (IP) networks. SIP works in conjunction with several other application layer
protocols:
SDP for media identification and negotiation
RTP, SRTP or WebRTC for the transmission of media streams
A TLS layer may be used for secure transmission of SIP messages
Source, Media A Media Source is a Media Pad that generates a Media Stream.
SPA
Single-Page Application A single-page application is a web application that fits on a single web page with the goal
of providing a more fluid user experience akin to a desktop application.
Sphinx Documentation generation system used for kurento documentation
See also:
Easy and beautiful documentation with Sphinx
Spring Boot Spring Boot is Springs convention-over-configuration solution for creating stand-alone, production-
grade Spring based applications that can you can just run. It embeds Tomcat or Jetty directly and so there is
no need to deploy WAR files in order to run web applications.
SRTCP SRTCP provides the same security-related features to RTCP, as the ones provided by SRTP to RTP. Encryp-
tion, message authentication and integrity, and replay protection are the features added by SRTCP to RTCP.
See also:
SRTP
SRTP
is a profile of RTP (Real-time Transport Protocol), intended to provide encryption, message authentication and
integrity, and replay protection to the RTP data in both unicast and multicast applications. Similar to how
RTP has a sister RTCP protocol, SRTP also has a sister protocol, called Secure RTCP (or SRTCP);
385
Kurento Documentation, Release 6.6.1
See also:
RFC 3711
SSL Secure Socket Layer. See TLS.
STUN
Session Traversal Utilities for NAT STUN is a standardized set of methods to allow an end host to discover its
public IP address if it is located behind a NAT. STUN is a client-server protocol returning the public IP address
to a client together with information from which the client can infer the type of NAT it sits behind.
Trickle ICE Extension to the ICE protocol that allows ICE agents to send and receive candidates incrementally
rather than exchanging complete lists. With such incremental provisioning, ICE agents can begin connectivity
checks while they are still gathering candidates and considerably shorten the time necessary for ICE processing
to complete.
See also:
Trickle ICE IETF Draft
TLS
and its prececessor Secure Socket Layer (SSL)
See also:
RFC 5246 Version 1.2 of the Transport Layer Security protocol
TURN
Traversal Using Relays around NAT TURN is a protocol that allows for a client behind a NAT or firewall to receive
incoming data over TCP or UDP connections. TURN places a third party server to relay messages between two
clients where peer to peer media traffic is not allowed by a firewall.
VP8 VP8 is a video compression format created by On2 Technologies as a successor to VP7. Its patents rights are
owned by Google, who made an irrevocable patent promise on its patents for implementing it and released a
specification under the Creative Commons Attribution 3.0 license.
See also:
RFC 6386 VP8 Data Format and Decoding Guide
VP8 page at Wikipedia
WebM WebM is an open media file format designed for the web. WebM files consist of video streams compressed
with the VP8 video codec and audio streams compressed with the Vorbis audio codec. The WebM file structure
is based on the Matroska media container.
WebRTC WebRTC is an open source project that provides rich Real-Time Communcations capabilities to web
browsers via Javascript and HTML5 APIs and components. These APIs are being drafted by the World Wide
Web Consortium (W3C).
See also:
WebRTC Working Draft
WebSocket WebSocket specification (developed as part of the HTML5 initiative) defines a full-duplex single socket
connection over which messages can be sent between client and server.
386
Index
B M
Bower, 381 Maven, 382
Builder Pattern, 381 Media
Element, 253
C Pad, 384
CORS, 381 Pipeline, 383
Sink, 385
D Source, 385
Media Element, 382
Document Object Model, 381
Media Pipeline, 383
DOM, 381
Media Plane, 383
E MP4, 383
Multimedia, 383
EOS, 381
Multimedia container format, 383
G N
GStreamer, 381 NAT, 383
H NAT Traversal, 383
NAT-T, 383
H.264, 381 Network Address Translation, 383
HTTP, 381 Node.js, 384
npm, 384
I
ICE, 382 O
IMS, 382
OpenCL, 384
Interactive Connectivity Establishment, 382
OpenCV, 384
J P
Java EE, 382
Pad, Media, 384
jQuery, 382
Pipeline: single
JSON, 382
Media, 253
JSON-RPC, 382
Plane
K Media, 383
Signaling, 385
Kurento, 382
PubNub, 384
Kurento API, 382
387
Kurento Documentation, Release 6.6.1
Q
QR, 384
R
REST, 384
RFC
RFC 2616, 382
RFC 3550, 384
RFC 3574, 382
RFC 3605, 384
RFC 3711, 386
RFC 3984, 381
RFC 4566, 385
RFC 4568, 385
RFC 5245, 382
RFC 5246, 386
RFC 5766, 376
RFC 6184, 381
RFC 6386, 386
RTCP, 384
RTP, 384
S
Same-origin policy, 384
SDP, 384
Semantic Versioning, 385
Session Description Protocol, 384
Session Traversal Utilities for NAT, 386
Signaling Plane, 385
Single-Page Application, 385
Sink, Media, 385
SIP, 385
Source, Media, 385
SPA, 385
Sphinx, 385
Spring Boot, 385
SRTCP, 385
SRTP, 385
SSL, 386
STUN, 386
T
TLS, 386
Traversal Using Relays around NAT, 386
Trickle ICE, 386
TURN, 386
V
VP8, 386
W
WebM, 386
WebRTC, 386
WebSocket, 386
388 Index