Skip to content

Commit 83a00ff

Browse files
committed
feat: add the missing peer connection signaling and control calls
RTCPeerConnection gains: - addIceCandidate(candidate, AddIceCandidateObserver), which is queued behind pending offer/answer operations and reports whether the candidate was accepted. - removeIceCandidate(candidate), and PeerConnectionObserver gains onIceCandidateRemoved for local candidates that go away. - setLocalDescription(observer), which creates the offer or answer itself, as perfect negotiation needs. - setBitrate(min, current, max) for the connection's send bandwidth. - setAudioPlayout and setAudioRecording. PeerConnectionObserver also gains onSelectedCandidatePairChanged with an RTCCandidatePairChangeEvent carrying both candidates of the pair, the reason for the switch and the disconnection estimate. Its default passes the remote address, port and type on to the existing callback, so observers that override that one keep working. The new callbacks report a Java exception to the thread's uncaught exception handler instead of throwing it through WebRTC's frames; ReportUncaughtException moves to WebRTCUtils to be shared with the data channel send observer.
1 parent 00b0daf commit 83a00ff

21 files changed

Lines changed: 1375 additions & 58 deletions

‎docs/guide/get-started.md‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,54 @@ signalingChannel.onIceCandidate(candidateMessage -> {
215215
});
216216
```
217217

218+
### Letting the Peer Connection Create the Description
219+
220+
`setLocalDescription` can also be called with only an observer. It then creates the offer or the answer, whichever the signaling state calls for, and applies it in one step, so nothing can change in between. That makes it the simpler way to implement "perfect negotiation". Read the result with `getLocalDescription()` once the observer reports success:
221+
222+
```java
223+
peerConnection.setLocalDescription(new SetSessionDescriptionObserver() {
224+
@Override
225+
public void onSuccess() {
226+
signalingChannel.send(peerConnection.getLocalDescription());
227+
}
228+
229+
@Override
230+
public void onFailure(String error) {
231+
System.err.println("Failed to set local description: " + error);
232+
}
233+
});
234+
```
235+
236+
### Adding Candidates and Knowing the Outcome
237+
238+
`addIceCandidate(candidate)` reports nothing and fails silently when the remote description is not set yet. The form that takes an `AddIceCandidateObserver` is queued behind any pending offer/answer operation, as the standard requires, so a candidate can be added right after `setRemoteDescription()` without waiting for it, and the observer says whether it was accepted:
239+
240+
```java
241+
peerConnection.addIceCandidate(candidate, new AddIceCandidateObserver() {
242+
@Override
243+
public void onSuccess() {
244+
}
245+
246+
@Override
247+
public void onFailure(String error) {
248+
// e.g. "[INVALID_STATE] The remote description was null"
249+
System.err.println("Candidate rejected: " + error);
250+
}
251+
});
252+
```
253+
254+
A local candidate can also go away, for example when its network interface does. The observer's `onIceCandidateRemoved(RTCIceCandidate)` reports it; send it to the remote peer, which passes it to `removeIceCandidate(candidate)`.
255+
256+
Once ICE has picked the candidate pair it uses, `onSelectedCandidatePairChanged(RTCCandidatePairChangeEvent)` reports both candidates of the pair and why it was chosen. It fires again whenever ICE switches pairs:
257+
258+
```java
259+
@Override
260+
public void onSelectedCandidatePairChanged(RTCCandidatePairChangeEvent event) {
261+
System.out.println("Using " + event.getLocal().sdp + " <-> " + event.getRemote().sdp
262+
+ " (" + event.getReason() + ")");
263+
}
264+
```
265+
218266
## Media Streams
219267

220268
### Accessing Media Devices

‎docs/guide/media/directionality.md‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,12 +118,10 @@ transceiver.setDirection(RTCRtpTransceiverDirection.INACTIVE);
118118
transceiver.setDirection(RTCRtpTransceiverDirection.SEND_RECV);
119119

120120
// After changing directions, create a new offer and perform negotiation.
121-
RTCOfferOptions opts = new RTCOfferOptions();
122-
pc.createOffer(opts, new CreateSessionDescriptionObserver() {
121+
pc.setLocalDescription(new SetSessionDescriptionObserver() {
123122
@Override
124-
public void onSuccess(RTCSessionDescription description) {
125-
pc.setLocalDescription(description, /* observer */ null);
126-
// Send to remote and await/set remote answer accordingly
123+
public void onSuccess() {
124+
// Send pc.getLocalDescription() to the remote peer and set its answer
127125
}
128126
@Override
129127
public void onFailure(String error) { /* handle error */ }

‎docs/guide/networking/peer-connection-config.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,17 +69,33 @@ config.cryptoOptions = crypto;
6969

7070
`cryptexPolicy` encrypts the RTP header extensions and CSRCs as a whole (RFC 9335) where the peer supports it (`NEGOTIATE`) or always (`REQUIRE`).
7171

72+
`certificates` takes the DTLS certificate a peer connection authenticates with, as an `RTCCertificatePEM`; without one, WebRTC generates a certificate per connection. A certificate that does not parse makes `createPeerConnection()` and `setConfiguration()` throw.
73+
7274
## Signaling
7375

7476
| Setting | Effect |
7577
|---|---|
7678
| `offerExtmapAllowMixed` | Allows one- and two-byte header extensions to be mixed in offers. Default true. |
77-
| `enableImplicitRollback` | Rolls a pending local offer back when a remote offer arrives, as perfect negotiation needs. Default false. |
79+
| `enableImplicitRollback` | Rolls a pending local offer back when a remote offer arrives, as perfect negotiation needs. Default false. Pair it with `setLocalDescription(observer)`, which creates the offer or answer itself. |
7880
| `alwaysNegotiateDataChannels` | Includes data channels in offers before any is created. Default false. |
7981

82+
## Changing a Running Connection
83+
84+
A few controls are methods of `RTCPeerConnection` rather than configuration fields, and can be used at any time.
85+
86+
`setBitrate(min, current, max)` limits the bandwidth all streams sent by the connection may use together, in bits per second. A `null` value leaves that limit as it is, and `current` resets the bandwidth estimate to that value. Limits from the SDP and from each sender's encoding parameters still apply. Values that are negative or not ordered as min ≤ current ≤ max make it throw.
87+
88+
```java
89+
// Start from 1 Mbps and never use more than 2.5 Mbps.
90+
peerConnection.setBitrate(null, 1_000_000, 2_500_000);
91+
```
92+
93+
`setAudioPlayout(false)` stops the audio device from playing received audio; the audio is still decoded and its statistics still updated. `setAudioRecording(false)` stops the audio device from recording, so tracks fed by it send nothing, while tracks fed by a `CustomAudioSource` keep sending. Both are on by default and act on the audio device module, which all connections of a `PeerConnectionFactory` share.
94+
8095
## Related API
8196

8297
- `RTCConfiguration` — the configuration of a peer connection.
8398
- `RTCPeerConnection.getConfiguration()`, `setConfiguration()` — read and change it.
99+
- `RTCPeerConnection.setBitrate()`, `setAudioPlayout()`, `setAudioRecording()` — controls of a running connection.
84100
- `RTCCryptoOptions` — the SRTP cipher suites.
85101
- `PortAllocatorConfig` — ports and interfaces, see [Port Allocator Configuration](/guide/networking/port-allocator-config).

‎webrtc-jni/src/main/cpp/include/JNI_RTCPeerConnection.h‎

Lines changed: 48 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
#ifndef JNI_WEBRTC_API_ADD_ICE_CANDIDATE_OBSERVER_H_
18+
#define JNI_WEBRTC_API_ADD_ICE_CANDIDATE_OBSERVER_H_
19+
20+
#include "JavaClass.h"
21+
#include "JavaRef.h"
22+
23+
#include "api/rtc_error.h"
24+
25+
#include <jni.h>
26+
#include <memory>
27+
28+
namespace jni
29+
{
30+
// Reports the outcome of PeerConnectionInterface::AddIceCandidate to a
31+
// Java AddIceCandidateObserver, exactly once.
32+
class AddIceCandidateObserver
33+
{
34+
public:
35+
AddIceCandidateObserver(JNIEnv * env, const JavaGlobalRef<jobject> & observer);
36+
~AddIceCandidateObserver();
37+
38+
AddIceCandidateObserver(const AddIceCandidateObserver &) = delete;
39+
AddIceCandidateObserver & operator=(const AddIceCandidateObserver &) = delete;
40+
41+
void OnComplete(webrtc::RTCError error) noexcept;
42+
43+
private:
44+
class JavaAddIceCandidateObserverClass : public JavaClass
45+
{
46+
public:
47+
explicit JavaAddIceCandidateObserverClass(JNIEnv * env);
48+
49+
jmethodID onSuccess;
50+
jmethodID onFailure;
51+
};
52+
53+
void Notify(const char * error) noexcept;
54+
55+
JavaGlobalRef<jobject> observer;
56+
57+
const std::shared_ptr<JavaAddIceCandidateObserverClass> javaClass;
58+
};
59+
}
60+
61+
#endif

‎webrtc-jni/src/main/cpp/include/api/PeerConnectionObserver.h‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ namespace jni
4545
void OnIceGatheringChange(webrtc::PeerConnectionInterface::IceGatheringState state) override;
4646
void OnIceCandidate(const webrtc::IceCandidateInterface * candidate) override;
4747
void OnIceCandidateError(const std::string & address, int port, const std::string & url, int error_code, const std::string & error_text) override;
48+
void OnIceCandidateRemoved(const webrtc::IceCandidate * candidate) override;
4849
void OnIceConnectionReceivingChange(bool receiving) override;
4950
void OnIceSelectedCandidatePairChanged(const webrtc::CandidatePairChangeEvent & event) override;
5051

@@ -65,11 +66,16 @@ namespace jni
6566
jmethodID onIceGatheringChange;
6667
jmethodID onIceCandidate;
6768
jmethodID onIceCandidateError;
69+
jmethodID onIceCandidateRemoved;
6870
jmethodID onIceConnectionReceivingChange;
6971
jmethodID onSelectedCandidatePairChanged;
7072
};
7173

7274
private:
75+
// Reports a Java exception thrown by a callback without letting it
76+
// unwind through WebRTC.
77+
void ReportException(JNIEnv * env) noexcept;
78+
7379
JavaGlobalRef<jobject> observer;
7480

7581
const std::shared_ptr<JavaPeerConnectionObserverClass> javaClass;
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
* Copyright 2026 Alex Andres
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
#ifndef JNI_WEBRTC_API_RTC_CANDIDATE_PAIR_CHANGE_EVENT_H_
18+
#define JNI_WEBRTC_API_RTC_CANDIDATE_PAIR_CHANGE_EVENT_H_
19+
20+
#include "JavaClass.h"
21+
#include "JavaRef.h"
22+
23+
#include "p2p/base/port.h"
24+
25+
#include <jni.h>
26+
27+
namespace jni
28+
{
29+
namespace RTCCandidatePairChangeEvent
30+
{
31+
class JavaRTCCandidatePairChangeEventClass : public JavaClass
32+
{
33+
public:
34+
explicit JavaRTCCandidatePairChangeEventClass(JNIEnv * env);
35+
36+
jclass cls;
37+
jmethodID ctor;
38+
};
39+
40+
JavaLocalRef<jobject> toJava(JNIEnv * env, const webrtc::CandidatePairChangeEvent & event);
41+
};
42+
}
43+
44+
#endif

‎webrtc-jni/src/main/cpp/include/api/WebRTCUtils.h‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,12 @@ namespace jni
7777
}
7878

7979
std::string RTCErrorToString(const webrtc::RTCError & error);
80+
81+
// Hands an exception thrown by a Java callback to the calling thread's
82+
// uncaught exception handler, as the JVM does for an exception escaping a
83+
// Java thread. Callbacks that WebRTC invokes use it, because a C++
84+
// exception must not unwind through WebRTC's frames.
85+
void ReportUncaughtException(JNIEnv * env, jthrowable exception);
8086
}
8187

8288
#endif

0 commit comments

Comments
 (0)