Skip to content

Peer connections

Alex Andres edited this page Nov 7, 2022 · 3 revisions

Getting started with peer connections

Peer connections play the central part of WebRTC. The following will show you how to initiate peer connections with webrtc-java.

Signaling

This project does not provide any signaling protocol! Signaling can be implemented in many different ways, thus it is up to you to implement your own signaling component or use any existing one.

Initiating peer connections

Let's get started with the most basic peer connection.

First of all, you need to create a PeerConnectionFactory. With it you can create peer connections. Each peer connection requires a RTCConfiguration which defines how the connection is set up. The second to the configuration you need to provide an implementation of the PeerConnectionObserver interface. This interface has a bunch of default callback methods - only one is mandatory.

PeerConnectionFactory factory = new PeerConnectionFactory();

// Define a STUN-server to provide ICE candidates to the remote peer.
RTCIceServer iceServer = new RTCIceServer();
iceServer.urls.add("stun:stun.l.google.com:19302");

RTCConfiguration config = new RTCConfiguration();
config.iceServers.add(iceServer);

// Provide an simple PeerConnectionObserver with the only mandatory callback method.
RTCPeerConnection peerConnection = factory.createPeerConnection(config, candidate -> { /* transmit the candidate over a signaling channel */ });

// When you are done with the WebRTC session.
peerConnection.close();
factory.dispose();

Set bitrate and framerate constraints

for (RTCRtpSender sender : peerConnection.getSenders()) {
	MediaStreamTrack track = sender.getTrack();

	if (nonNull(track) && track.getId().equals(YOUR_TRACK_ID)) {
		RTCRtpSendParameters sendParams = sender.getParameters();

		for (var encoding : sendParams.encodings) {
			// In this example the min/max bitrate is 100/300 kbit/s
			encoding.minBitrate = 100 * 1000;	// bits per second
			encoding.maxBitrate = 300 * 1000;
			encoding.maxFramerate = 20;		// for video
		}

		sender.setParameters(sendParams);
	}
}
Clone this wiki locally