Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(572)

Side by Side Diff: webrtc/api/android/jni/peerconnection_jni.cc

Issue 2106333005: Revert of Combine webrtc/api/java/android and webrtc/api/java/src. (Closed) Base URL: https://chromium.googlesource.com/external/webrtc.git@master
Patch Set: Created 4 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 * Copyright 2013 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 // Hints for future visitors:
12 // This entire file is an implementation detail of the org.webrtc Java package,
13 // the most interesting bits of which are org.webrtc.PeerConnection{,Factory}.
14 // The layout of this file is roughly:
15 // - various helper C++ functions & classes that wrap Java counterparts and
16 // expose a C++ interface that can be passed to the C++ PeerConnection APIs
17 // - implementations of methods declared "static" in the Java package (named
18 // things like Java_org_webrtc_OMG_Can_This_Name_Be_Any_Longer, prescribed by
19 // the JNI spec).
20 //
21 // Lifecycle notes: objects are owned where they will be called; in other words
22 // FooObservers are owned by C++-land, and user-callable objects (e.g.
23 // PeerConnection and VideoTrack) are owned by Java-land.
24 // When this file allocates C++ RefCountInterfaces it AddRef()s an artificial
25 // ref simulating the jlong held in Java-land, and then Release()s the ref in
26 // the respective free call. Sometimes this AddRef is implicit in the
27 // construction of a scoped_refptr<> which is then .release()d.
28 // Any persistent (non-local) references from C++ to Java must be global or weak
29 // (in which case they must be checked before use)!
30 //
31 // Exception notes: pretty much all JNI calls can throw Java exceptions, so each
32 // call through a JNIEnv* pointer needs to be followed by an ExceptionCheck()
33 // call. In this file this is done in CHECK_EXCEPTION, making for much easier
34 // debugging in case of failure (the alternative is to wait for control to
35 // return to the Java frame that called code in this file, at which point it's
36 // impossible to tell which JNI call broke).
37
38 #include <jni.h>
39 #undef JNIEXPORT
40 #define JNIEXPORT __attribute__((visibility("default")))
41
42 #include <limits>
43 #include <memory>
44 #include <utility>
45
46 #include "webrtc/api/androidvideocapturer.h"
47 #include "webrtc/api/dtlsidentitystore.h"
48 #include "webrtc/api/android/jni/androidmediadecoder_jni.h"
49 #include "webrtc/api/android/jni/androidmediaencoder_jni.h"
50 #include "webrtc/api/android/jni/androidnetworkmonitor_jni.h"
51 #include "webrtc/api/android/jni/androidvideocapturer_jni.h"
52 #include "webrtc/api/android/jni/classreferenceholder.h"
53 #include "webrtc/api/android/jni/jni_helpers.h"
54 #include "webrtc/api/android/jni/native_handle_impl.h"
55 #include "webrtc/api/mediaconstraintsinterface.h"
56 #include "webrtc/api/peerconnectioninterface.h"
57 #include "webrtc/api/rtpreceiverinterface.h"
58 #include "webrtc/api/rtpsenderinterface.h"
59 #include "webrtc/api/webrtcsdp.h"
60 #include "webrtc/base/bind.h"
61 #include "webrtc/base/checks.h"
62 #include "webrtc/base/event_tracer.h"
63 #include "webrtc/base/logging.h"
64 #include "webrtc/base/logsinks.h"
65 #include "webrtc/base/messagequeue.h"
66 #include "webrtc/base/networkmonitor.h"
67 #include "webrtc/base/rtccertificategenerator.h"
68 #include "webrtc/base/ssladapter.h"
69 #include "webrtc/base/stringutils.h"
70 #include "webrtc/media/base/videocapturer.h"
71 #include "webrtc/media/engine/webrtcvideodecoderfactory.h"
72 #include "webrtc/media/engine/webrtcvideoencoderfactory.h"
73 #include "webrtc/system_wrappers/include/field_trial_default.h"
74 #include "webrtc/system_wrappers/include/logcat_trace_context.h"
75 #include "webrtc/system_wrappers/include/trace.h"
76 #include "webrtc/voice_engine/include/voe_base.h"
77
78 using cricket::WebRtcVideoDecoderFactory;
79 using cricket::WebRtcVideoEncoderFactory;
80 using rtc::Bind;
81 using rtc::Thread;
82 using rtc::ThreadManager;
83 using webrtc::AudioSourceInterface;
84 using webrtc::AudioTrackInterface;
85 using webrtc::AudioTrackVector;
86 using webrtc::CreateSessionDescriptionObserver;
87 using webrtc::DataBuffer;
88 using webrtc::DataChannelInit;
89 using webrtc::DataChannelInterface;
90 using webrtc::DataChannelObserver;
91 using webrtc::IceCandidateInterface;
92 using webrtc::LogcatTraceContext;
93 using webrtc::MediaConstraintsInterface;
94 using webrtc::MediaSourceInterface;
95 using webrtc::MediaStreamInterface;
96 using webrtc::MediaStreamTrackInterface;
97 using webrtc::PeerConnectionFactoryInterface;
98 using webrtc::PeerConnectionInterface;
99 using webrtc::PeerConnectionObserver;
100 using webrtc::RtpReceiverInterface;
101 using webrtc::RtpSenderInterface;
102 using webrtc::SessionDescriptionInterface;
103 using webrtc::SetSessionDescriptionObserver;
104 using webrtc::StatsObserver;
105 using webrtc::StatsReport;
106 using webrtc::StatsReports;
107 using webrtc::VideoTrackSourceInterface;
108 using webrtc::VideoTrackInterface;
109 using webrtc::VideoTrackVector;
110 using webrtc::kVideoCodecVP8;
111
112 namespace webrtc_jni {
113
114 // Field trials initialization string
115 static char *field_trials_init_string = NULL;
116
117 // Set in PeerConnectionFactory_initializeAndroidGlobals().
118 static bool factory_static_initialized = false;
119 static bool video_hw_acceleration_enabled = true;
120
121 // Return the (singleton) Java Enum object corresponding to |index|;
122 // |state_class_fragment| is something like "MediaSource$State".
123 static jobject JavaEnumFromIndex(
124 JNIEnv* jni, const std::string& state_class_fragment, int index) {
125 const std::string state_class = "org/webrtc/" + state_class_fragment;
126 return JavaEnumFromIndex(jni, FindClass(jni, state_class.c_str()),
127 state_class, index);
128 }
129
130 static DataChannelInit JavaDataChannelInitToNative(
131 JNIEnv* jni, jobject j_init) {
132 DataChannelInit init;
133
134 jclass j_init_class = FindClass(jni, "org/webrtc/DataChannel$Init");
135 jfieldID ordered_id = GetFieldID(jni, j_init_class, "ordered", "Z");
136 jfieldID max_retransmit_time_id =
137 GetFieldID(jni, j_init_class, "maxRetransmitTimeMs", "I");
138 jfieldID max_retransmits_id =
139 GetFieldID(jni, j_init_class, "maxRetransmits", "I");
140 jfieldID protocol_id =
141 GetFieldID(jni, j_init_class, "protocol", "Ljava/lang/String;");
142 jfieldID negotiated_id = GetFieldID(jni, j_init_class, "negotiated", "Z");
143 jfieldID id_id = GetFieldID(jni, j_init_class, "id", "I");
144
145 init.ordered = GetBooleanField(jni, j_init, ordered_id);
146 init.maxRetransmitTime = GetIntField(jni, j_init, max_retransmit_time_id);
147 init.maxRetransmits = GetIntField(jni, j_init, max_retransmits_id);
148 init.protocol = JavaToStdString(
149 jni, GetStringField(jni, j_init, protocol_id));
150 init.negotiated = GetBooleanField(jni, j_init, negotiated_id);
151 init.id = GetIntField(jni, j_init, id_id);
152
153 return init;
154 }
155
156 class ConstraintsWrapper;
157
158 // Adapter between the C++ PeerConnectionObserver interface and the Java
159 // PeerConnection.Observer interface. Wraps an instance of the Java interface
160 // and dispatches C++ callbacks to Java.
161 class PCOJava : public PeerConnectionObserver {
162 public:
163 // We need these using declarations because there are two versions of each of
164 // the below methods and we only override one of them.
165 // TODO(deadbeef): Remove once there's only one version of the methods.
166 using PeerConnectionObserver::OnAddStream;
167 using PeerConnectionObserver::OnRemoveStream;
168 using PeerConnectionObserver::OnDataChannel;
169
170 PCOJava(JNIEnv* jni, jobject j_observer)
171 : j_observer_global_(jni, j_observer),
172 j_observer_class_(jni, GetObjectClass(jni, *j_observer_global_)),
173 j_media_stream_class_(jni, FindClass(jni, "org/webrtc/MediaStream")),
174 j_media_stream_ctor_(GetMethodID(
175 jni, *j_media_stream_class_, "<init>", "(J)V")),
176 j_audio_track_class_(jni, FindClass(jni, "org/webrtc/AudioTrack")),
177 j_audio_track_ctor_(GetMethodID(
178 jni, *j_audio_track_class_, "<init>", "(J)V")),
179 j_video_track_class_(jni, FindClass(jni, "org/webrtc/VideoTrack")),
180 j_video_track_ctor_(GetMethodID(
181 jni, *j_video_track_class_, "<init>", "(J)V")),
182 j_data_channel_class_(jni, FindClass(jni, "org/webrtc/DataChannel")),
183 j_data_channel_ctor_(GetMethodID(
184 jni, *j_data_channel_class_, "<init>", "(J)V")) {
185 }
186
187 virtual ~PCOJava() {
188 ScopedLocalRefFrame local_ref_frame(jni());
189 while (!remote_streams_.empty())
190 DisposeRemoteStream(remote_streams_.begin());
191 }
192
193 void OnIceCandidate(const IceCandidateInterface* candidate) override {
194 ScopedLocalRefFrame local_ref_frame(jni());
195 std::string sdp;
196 RTC_CHECK(candidate->ToString(&sdp)) << "got so far: " << sdp;
197 jclass candidate_class = FindClass(jni(), "org/webrtc/IceCandidate");
198 jmethodID ctor = GetMethodID(jni(), candidate_class,
199 "<init>", "(Ljava/lang/String;ILjava/lang/String;)V");
200 jstring j_mid = JavaStringFromStdString(jni(), candidate->sdp_mid());
201 jstring j_sdp = JavaStringFromStdString(jni(), sdp);
202 jobject j_candidate = jni()->NewObject(candidate_class, ctor, j_mid,
203 candidate->sdp_mline_index(), j_sdp);
204 CHECK_EXCEPTION(jni()) << "error during NewObject";
205 jmethodID m = GetMethodID(jni(), *j_observer_class_,
206 "onIceCandidate", "(Lorg/webrtc/IceCandidate;)V");
207 jni()->CallVoidMethod(*j_observer_global_, m, j_candidate);
208 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
209 }
210
211 void OnIceCandidatesRemoved(
212 const std::vector<cricket::Candidate>& candidates) override {
213 ScopedLocalRefFrame local_ref_frame(jni());
214 jobjectArray candidates_array = ToJavaCandidateArray(jni(), candidates);
215 jmethodID m =
216 GetMethodID(jni(), *j_observer_class_, "onIceCandidatesRemoved",
217 "([Lorg/webrtc/IceCandidate;)V");
218 jni()->CallVoidMethod(*j_observer_global_, m, candidates_array);
219 CHECK_EXCEPTION(jni()) << "Error during CallVoidMethod";
220 }
221
222 void OnSignalingChange(
223 PeerConnectionInterface::SignalingState new_state) override {
224 ScopedLocalRefFrame local_ref_frame(jni());
225 jmethodID m = GetMethodID(
226 jni(), *j_observer_class_, "onSignalingChange",
227 "(Lorg/webrtc/PeerConnection$SignalingState;)V");
228 jobject new_state_enum =
229 JavaEnumFromIndex(jni(), "PeerConnection$SignalingState", new_state);
230 jni()->CallVoidMethod(*j_observer_global_, m, new_state_enum);
231 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
232 }
233
234 void OnIceConnectionChange(
235 PeerConnectionInterface::IceConnectionState new_state) override {
236 ScopedLocalRefFrame local_ref_frame(jni());
237 jmethodID m = GetMethodID(
238 jni(), *j_observer_class_, "onIceConnectionChange",
239 "(Lorg/webrtc/PeerConnection$IceConnectionState;)V");
240 jobject new_state_enum = JavaEnumFromIndex(
241 jni(), "PeerConnection$IceConnectionState", new_state);
242 jni()->CallVoidMethod(*j_observer_global_, m, new_state_enum);
243 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
244 }
245
246 void OnIceConnectionReceivingChange(bool receiving) override {
247 ScopedLocalRefFrame local_ref_frame(jni());
248 jmethodID m = GetMethodID(
249 jni(), *j_observer_class_, "onIceConnectionReceivingChange", "(Z)V");
250 jni()->CallVoidMethod(*j_observer_global_, m, receiving);
251 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
252 }
253
254 void OnIceGatheringChange(
255 PeerConnectionInterface::IceGatheringState new_state) override {
256 ScopedLocalRefFrame local_ref_frame(jni());
257 jmethodID m = GetMethodID(
258 jni(), *j_observer_class_, "onIceGatheringChange",
259 "(Lorg/webrtc/PeerConnection$IceGatheringState;)V");
260 jobject new_state_enum = JavaEnumFromIndex(
261 jni(), "PeerConnection$IceGatheringState", new_state);
262 jni()->CallVoidMethod(*j_observer_global_, m, new_state_enum);
263 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
264 }
265
266 void OnAddStream(rtc::scoped_refptr<MediaStreamInterface> stream) override {
267 ScopedLocalRefFrame local_ref_frame(jni());
268 // Java MediaStream holds one reference. Corresponding Release() is in
269 // MediaStream_free, triggered by MediaStream.dispose().
270 stream->AddRef();
271 jobject j_stream =
272 jni()->NewObject(*j_media_stream_class_, j_media_stream_ctor_,
273 reinterpret_cast<jlong>(stream.get()));
274 CHECK_EXCEPTION(jni()) << "error during NewObject";
275
276 for (const auto& track : stream->GetAudioTracks()) {
277 jstring id = JavaStringFromStdString(jni(), track->id());
278 // Java AudioTrack holds one reference. Corresponding Release() is in
279 // MediaStreamTrack_free, triggered by AudioTrack.dispose().
280 track->AddRef();
281 jobject j_track =
282 jni()->NewObject(*j_audio_track_class_, j_audio_track_ctor_,
283 reinterpret_cast<jlong>(track.get()), id);
284 CHECK_EXCEPTION(jni()) << "error during NewObject";
285 jfieldID audio_tracks_id = GetFieldID(jni(),
286 *j_media_stream_class_,
287 "audioTracks",
288 "Ljava/util/LinkedList;");
289 jobject audio_tracks = GetObjectField(jni(), j_stream, audio_tracks_id);
290 jmethodID add = GetMethodID(jni(),
291 GetObjectClass(jni(), audio_tracks),
292 "add",
293 "(Ljava/lang/Object;)Z");
294 jboolean added = jni()->CallBooleanMethod(audio_tracks, add, j_track);
295 CHECK_EXCEPTION(jni()) << "error during CallBooleanMethod";
296 RTC_CHECK(added);
297 }
298
299 for (const auto& track : stream->GetVideoTracks()) {
300 jstring id = JavaStringFromStdString(jni(), track->id());
301 // Java VideoTrack holds one reference. Corresponding Release() is in
302 // MediaStreamTrack_free, triggered by VideoTrack.dispose().
303 track->AddRef();
304 jobject j_track =
305 jni()->NewObject(*j_video_track_class_, j_video_track_ctor_,
306 reinterpret_cast<jlong>(track.get()), id);
307 CHECK_EXCEPTION(jni()) << "error during NewObject";
308 jfieldID video_tracks_id = GetFieldID(jni(),
309 *j_media_stream_class_,
310 "videoTracks",
311 "Ljava/util/LinkedList;");
312 jobject video_tracks = GetObjectField(jni(), j_stream, video_tracks_id);
313 jmethodID add = GetMethodID(jni(),
314 GetObjectClass(jni(), video_tracks),
315 "add",
316 "(Ljava/lang/Object;)Z");
317 jboolean added = jni()->CallBooleanMethod(video_tracks, add, j_track);
318 CHECK_EXCEPTION(jni()) << "error during CallBooleanMethod";
319 RTC_CHECK(added);
320 }
321 remote_streams_[stream] = NewGlobalRef(jni(), j_stream);
322
323 jmethodID m = GetMethodID(jni(), *j_observer_class_, "onAddStream",
324 "(Lorg/webrtc/MediaStream;)V");
325 jni()->CallVoidMethod(*j_observer_global_, m, j_stream);
326 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
327 }
328
329 void OnRemoveStream(
330 rtc::scoped_refptr<MediaStreamInterface> stream) override {
331 ScopedLocalRefFrame local_ref_frame(jni());
332 NativeToJavaStreamsMap::iterator it = remote_streams_.find(stream);
333 RTC_CHECK(it != remote_streams_.end()) << "unexpected stream: " << std::hex
334 << stream;
335 jobject j_stream = it->second;
336 jmethodID m = GetMethodID(jni(), *j_observer_class_, "onRemoveStream",
337 "(Lorg/webrtc/MediaStream;)V");
338 jni()->CallVoidMethod(*j_observer_global_, m, j_stream);
339 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
340 // Release the refptr reference so that DisposeRemoteStream can assert
341 // it removes the final reference.
342 stream = nullptr;
343 DisposeRemoteStream(it);
344 }
345
346 void OnDataChannel(
347 rtc::scoped_refptr<DataChannelInterface> channel) override {
348 ScopedLocalRefFrame local_ref_frame(jni());
349 jobject j_channel = jni()->NewObject(
350 *j_data_channel_class_, j_data_channel_ctor_, (jlong)channel.get());
351 CHECK_EXCEPTION(jni()) << "error during NewObject";
352
353 jmethodID m = GetMethodID(jni(), *j_observer_class_, "onDataChannel",
354 "(Lorg/webrtc/DataChannel;)V");
355 jni()->CallVoidMethod(*j_observer_global_, m, j_channel);
356
357 // Channel is now owned by Java object, and will be freed from
358 // DataChannel.dispose(). Important that this be done _after_ the
359 // CallVoidMethod above as Java code might call back into native code and be
360 // surprised to see a refcount of 2.
361 int bumped_count = channel->AddRef();
362 RTC_CHECK(bumped_count == 2) << "Unexpected refcount OnDataChannel";
363
364 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
365 }
366
367 void OnRenegotiationNeeded() override {
368 ScopedLocalRefFrame local_ref_frame(jni());
369 jmethodID m =
370 GetMethodID(jni(), *j_observer_class_, "onRenegotiationNeeded", "()V");
371 jni()->CallVoidMethod(*j_observer_global_, m);
372 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
373 }
374
375 void SetConstraints(ConstraintsWrapper* constraints) {
376 RTC_CHECK(!constraints_.get()) << "constraints already set!";
377 constraints_.reset(constraints);
378 }
379
380 const ConstraintsWrapper* constraints() { return constraints_.get(); }
381
382 private:
383 typedef std::map<MediaStreamInterface*, jobject> NativeToJavaStreamsMap;
384
385 void DisposeRemoteStream(const NativeToJavaStreamsMap::iterator& it) {
386 jobject j_stream = it->second;
387 remote_streams_.erase(it);
388 jni()->CallVoidMethod(
389 j_stream, GetMethodID(jni(), *j_media_stream_class_, "dispose", "()V"));
390 CHECK_EXCEPTION(jni()) << "error during MediaStream.dispose()";
391 DeleteGlobalRef(jni(), j_stream);
392 }
393
394 jobject ToJavaCandidate(JNIEnv* jni,
395 jclass* candidate_class,
396 const cricket::Candidate& candidate) {
397 std::string sdp = webrtc::SdpSerializeCandidate(candidate);
398 RTC_CHECK(!sdp.empty()) << "got an empty ICE candidate";
399 jmethodID ctor = GetMethodID(jni, *candidate_class, "<init>",
400 "(Ljava/lang/String;ILjava/lang/String;)V");
401 jstring j_mid = JavaStringFromStdString(jni, candidate.transport_name());
402 jstring j_sdp = JavaStringFromStdString(jni, sdp);
403 // sdp_mline_index is not used, pass an invalid value -1.
404 jobject j_candidate =
405 jni->NewObject(*candidate_class, ctor, j_mid, -1, j_sdp);
406 CHECK_EXCEPTION(jni) << "error during Java Candidate NewObject";
407 return j_candidate;
408 }
409
410 jobjectArray ToJavaCandidateArray(
411 JNIEnv* jni,
412 const std::vector<cricket::Candidate>& candidates) {
413 jclass candidate_class = FindClass(jni, "org/webrtc/IceCandidate");
414 jobjectArray java_candidates =
415 jni->NewObjectArray(candidates.size(), candidate_class, NULL);
416 int i = 0;
417 for (const cricket::Candidate& candidate : candidates) {
418 jobject j_candidate = ToJavaCandidate(jni, &candidate_class, candidate);
419 jni->SetObjectArrayElement(java_candidates, i++, j_candidate);
420 }
421 return java_candidates;
422 }
423
424 JNIEnv* jni() {
425 return AttachCurrentThreadIfNeeded();
426 }
427
428 const ScopedGlobalRef<jobject> j_observer_global_;
429 const ScopedGlobalRef<jclass> j_observer_class_;
430 const ScopedGlobalRef<jclass> j_media_stream_class_;
431 const jmethodID j_media_stream_ctor_;
432 const ScopedGlobalRef<jclass> j_audio_track_class_;
433 const jmethodID j_audio_track_ctor_;
434 const ScopedGlobalRef<jclass> j_video_track_class_;
435 const jmethodID j_video_track_ctor_;
436 const ScopedGlobalRef<jclass> j_data_channel_class_;
437 const jmethodID j_data_channel_ctor_;
438 // C++ -> Java remote streams. The stored jobects are global refs and must be
439 // manually deleted upon removal. Use DisposeRemoteStream().
440 NativeToJavaStreamsMap remote_streams_;
441 std::unique_ptr<ConstraintsWrapper> constraints_;
442 };
443
444 // Wrapper for a Java MediaConstraints object. Copies all needed data so when
445 // the constructor returns the Java object is no longer needed.
446 class ConstraintsWrapper : public MediaConstraintsInterface {
447 public:
448 ConstraintsWrapper(JNIEnv* jni, jobject j_constraints) {
449 PopulateConstraintsFromJavaPairList(
450 jni, j_constraints, "mandatory", &mandatory_);
451 PopulateConstraintsFromJavaPairList(
452 jni, j_constraints, "optional", &optional_);
453 }
454
455 virtual ~ConstraintsWrapper() {}
456
457 // MediaConstraintsInterface.
458 const Constraints& GetMandatory() const override { return mandatory_; }
459
460 const Constraints& GetOptional() const override { return optional_; }
461
462 private:
463 // Helper for translating a List<Pair<String, String>> to a Constraints.
464 static void PopulateConstraintsFromJavaPairList(
465 JNIEnv* jni, jobject j_constraints,
466 const char* field_name, Constraints* field) {
467 jfieldID j_id = GetFieldID(jni,
468 GetObjectClass(jni, j_constraints), field_name, "Ljava/util/List;");
469 jobject j_list = GetObjectField(jni, j_constraints, j_id);
470 for (jobject entry : Iterable(jni, j_list)) {
471 jmethodID get_key = GetMethodID(jni,
472 GetObjectClass(jni, entry), "getKey", "()Ljava/lang/String;");
473 jstring j_key = reinterpret_cast<jstring>(
474 jni->CallObjectMethod(entry, get_key));
475 CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
476 jmethodID get_value = GetMethodID(jni,
477 GetObjectClass(jni, entry), "getValue", "()Ljava/lang/String;");
478 jstring j_value = reinterpret_cast<jstring>(
479 jni->CallObjectMethod(entry, get_value));
480 CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
481 field->push_back(Constraint(JavaToStdString(jni, j_key),
482 JavaToStdString(jni, j_value)));
483 }
484 }
485
486 Constraints mandatory_;
487 Constraints optional_;
488 };
489
490 static jobject JavaSdpFromNativeSdp(
491 JNIEnv* jni, const SessionDescriptionInterface* desc) {
492 std::string sdp;
493 RTC_CHECK(desc->ToString(&sdp)) << "got so far: " << sdp;
494 jstring j_description = JavaStringFromStdString(jni, sdp);
495
496 jclass j_type_class = FindClass(
497 jni, "org/webrtc/SessionDescription$Type");
498 jmethodID j_type_from_canonical = GetStaticMethodID(
499 jni, j_type_class, "fromCanonicalForm",
500 "(Ljava/lang/String;)Lorg/webrtc/SessionDescription$Type;");
501 jstring j_type_string = JavaStringFromStdString(jni, desc->type());
502 jobject j_type = jni->CallStaticObjectMethod(
503 j_type_class, j_type_from_canonical, j_type_string);
504 CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
505
506 jclass j_sdp_class = FindClass(jni, "org/webrtc/SessionDescription");
507 jmethodID j_sdp_ctor = GetMethodID(
508 jni, j_sdp_class, "<init>",
509 "(Lorg/webrtc/SessionDescription$Type;Ljava/lang/String;)V");
510 jobject j_sdp = jni->NewObject(
511 j_sdp_class, j_sdp_ctor, j_type, j_description);
512 CHECK_EXCEPTION(jni) << "error during NewObject";
513 return j_sdp;
514 }
515
516 template <class T> // T is one of {Create,Set}SessionDescriptionObserver.
517 class SdpObserverWrapper : public T {
518 public:
519 SdpObserverWrapper(JNIEnv* jni, jobject j_observer,
520 ConstraintsWrapper* constraints)
521 : constraints_(constraints),
522 j_observer_global_(jni, j_observer),
523 j_observer_class_(jni, GetObjectClass(jni, j_observer)) {
524 }
525
526 virtual ~SdpObserverWrapper() {}
527
528 // Can't mark override because of templating.
529 virtual void OnSuccess() {
530 ScopedLocalRefFrame local_ref_frame(jni());
531 jmethodID m = GetMethodID(jni(), *j_observer_class_, "onSetSuccess", "()V");
532 jni()->CallVoidMethod(*j_observer_global_, m);
533 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
534 }
535
536 // Can't mark override because of templating.
537 virtual void OnSuccess(SessionDescriptionInterface* desc) {
538 ScopedLocalRefFrame local_ref_frame(jni());
539 jmethodID m = GetMethodID(
540 jni(), *j_observer_class_, "onCreateSuccess",
541 "(Lorg/webrtc/SessionDescription;)V");
542 jobject j_sdp = JavaSdpFromNativeSdp(jni(), desc);
543 jni()->CallVoidMethod(*j_observer_global_, m, j_sdp);
544 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
545 }
546
547 protected:
548 // Common implementation for failure of Set & Create types, distinguished by
549 // |op| being "Set" or "Create".
550 void DoOnFailure(const std::string& op, const std::string& error) {
551 jmethodID m = GetMethodID(jni(), *j_observer_class_, "on" + op + "Failure",
552 "(Ljava/lang/String;)V");
553 jstring j_error_string = JavaStringFromStdString(jni(), error);
554 jni()->CallVoidMethod(*j_observer_global_, m, j_error_string);
555 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
556 }
557
558 JNIEnv* jni() {
559 return AttachCurrentThreadIfNeeded();
560 }
561
562 private:
563 std::unique_ptr<ConstraintsWrapper> constraints_;
564 const ScopedGlobalRef<jobject> j_observer_global_;
565 const ScopedGlobalRef<jclass> j_observer_class_;
566 };
567
568 class CreateSdpObserverWrapper
569 : public SdpObserverWrapper<CreateSessionDescriptionObserver> {
570 public:
571 CreateSdpObserverWrapper(JNIEnv* jni, jobject j_observer,
572 ConstraintsWrapper* constraints)
573 : SdpObserverWrapper(jni, j_observer, constraints) {}
574
575 void OnFailure(const std::string& error) override {
576 ScopedLocalRefFrame local_ref_frame(jni());
577 SdpObserverWrapper::DoOnFailure(std::string("Create"), error);
578 }
579 };
580
581 class SetSdpObserverWrapper
582 : public SdpObserverWrapper<SetSessionDescriptionObserver> {
583 public:
584 SetSdpObserverWrapper(JNIEnv* jni, jobject j_observer,
585 ConstraintsWrapper* constraints)
586 : SdpObserverWrapper(jni, j_observer, constraints) {}
587
588 void OnFailure(const std::string& error) override {
589 ScopedLocalRefFrame local_ref_frame(jni());
590 SdpObserverWrapper::DoOnFailure(std::string("Set"), error);
591 }
592 };
593
594 // Adapter for a Java DataChannel$Observer presenting a C++ DataChannelObserver
595 // and dispatching the callback from C++ back to Java.
596 class DataChannelObserverWrapper : public DataChannelObserver {
597 public:
598 DataChannelObserverWrapper(JNIEnv* jni, jobject j_observer)
599 : j_observer_global_(jni, j_observer),
600 j_observer_class_(jni, GetObjectClass(jni, j_observer)),
601 j_buffer_class_(jni, FindClass(jni, "org/webrtc/DataChannel$Buffer")),
602 j_on_buffered_amount_change_mid_(GetMethodID(
603 jni, *j_observer_class_, "onBufferedAmountChange", "(J)V")),
604 j_on_state_change_mid_(
605 GetMethodID(jni, *j_observer_class_, "onStateChange", "()V")),
606 j_on_message_mid_(GetMethodID(jni, *j_observer_class_, "onMessage",
607 "(Lorg/webrtc/DataChannel$Buffer;)V")),
608 j_buffer_ctor_(GetMethodID(jni, *j_buffer_class_, "<init>",
609 "(Ljava/nio/ByteBuffer;Z)V")) {}
610
611 virtual ~DataChannelObserverWrapper() {}
612
613 void OnBufferedAmountChange(uint64_t previous_amount) override {
614 ScopedLocalRefFrame local_ref_frame(jni());
615 jni()->CallVoidMethod(*j_observer_global_, j_on_buffered_amount_change_mid_,
616 previous_amount);
617 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
618 }
619
620 void OnStateChange() override {
621 ScopedLocalRefFrame local_ref_frame(jni());
622 jni()->CallVoidMethod(*j_observer_global_, j_on_state_change_mid_);
623 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
624 }
625
626 void OnMessage(const DataBuffer& buffer) override {
627 ScopedLocalRefFrame local_ref_frame(jni());
628 jobject byte_buffer = jni()->NewDirectByteBuffer(
629 const_cast<char*>(buffer.data.data<char>()), buffer.data.size());
630 jobject j_buffer = jni()->NewObject(*j_buffer_class_, j_buffer_ctor_,
631 byte_buffer, buffer.binary);
632 jni()->CallVoidMethod(*j_observer_global_, j_on_message_mid_, j_buffer);
633 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
634 }
635
636 private:
637 JNIEnv* jni() {
638 return AttachCurrentThreadIfNeeded();
639 }
640
641 const ScopedGlobalRef<jobject> j_observer_global_;
642 const ScopedGlobalRef<jclass> j_observer_class_;
643 const ScopedGlobalRef<jclass> j_buffer_class_;
644 const jmethodID j_on_buffered_amount_change_mid_;
645 const jmethodID j_on_state_change_mid_;
646 const jmethodID j_on_message_mid_;
647 const jmethodID j_buffer_ctor_;
648 };
649
650 // Adapter for a Java StatsObserver presenting a C++ StatsObserver and
651 // dispatching the callback from C++ back to Java.
652 class StatsObserverWrapper : public StatsObserver {
653 public:
654 StatsObserverWrapper(JNIEnv* jni, jobject j_observer)
655 : j_observer_global_(jni, j_observer),
656 j_observer_class_(jni, GetObjectClass(jni, j_observer)),
657 j_stats_report_class_(jni, FindClass(jni, "org/webrtc/StatsReport")),
658 j_stats_report_ctor_(GetMethodID(
659 jni, *j_stats_report_class_, "<init>",
660 "(Ljava/lang/String;Ljava/lang/String;D"
661 "[Lorg/webrtc/StatsReport$Value;)V")),
662 j_value_class_(jni, FindClass(
663 jni, "org/webrtc/StatsReport$Value")),
664 j_value_ctor_(GetMethodID(
665 jni, *j_value_class_, "<init>",
666 "(Ljava/lang/String;Ljava/lang/String;)V")) {
667 }
668
669 virtual ~StatsObserverWrapper() {}
670
671 void OnComplete(const StatsReports& reports) override {
672 ScopedLocalRefFrame local_ref_frame(jni());
673 jobjectArray j_reports = ReportsToJava(jni(), reports);
674 jmethodID m = GetMethodID(jni(), *j_observer_class_, "onComplete",
675 "([Lorg/webrtc/StatsReport;)V");
676 jni()->CallVoidMethod(*j_observer_global_, m, j_reports);
677 CHECK_EXCEPTION(jni()) << "error during CallVoidMethod";
678 }
679
680 private:
681 jobjectArray ReportsToJava(
682 JNIEnv* jni, const StatsReports& reports) {
683 jobjectArray reports_array = jni->NewObjectArray(
684 reports.size(), *j_stats_report_class_, NULL);
685 int i = 0;
686 for (const auto* report : reports) {
687 ScopedLocalRefFrame local_ref_frame(jni);
688 jstring j_id = JavaStringFromStdString(jni, report->id()->ToString());
689 jstring j_type = JavaStringFromStdString(jni, report->TypeToString());
690 jobjectArray j_values = ValuesToJava(jni, report->values());
691 jobject j_report = jni->NewObject(*j_stats_report_class_,
692 j_stats_report_ctor_,
693 j_id,
694 j_type,
695 report->timestamp(),
696 j_values);
697 jni->SetObjectArrayElement(reports_array, i++, j_report);
698 }
699 return reports_array;
700 }
701
702 jobjectArray ValuesToJava(JNIEnv* jni, const StatsReport::Values& values) {
703 jobjectArray j_values = jni->NewObjectArray(
704 values.size(), *j_value_class_, NULL);
705 int i = 0;
706 for (const auto& it : values) {
707 ScopedLocalRefFrame local_ref_frame(jni);
708 // Should we use the '.name' enum value here instead of converting the
709 // name to a string?
710 jstring j_name = JavaStringFromStdString(jni, it.second->display_name());
711 jstring j_value = JavaStringFromStdString(jni, it.second->ToString());
712 jobject j_element_value =
713 jni->NewObject(*j_value_class_, j_value_ctor_, j_name, j_value);
714 jni->SetObjectArrayElement(j_values, i++, j_element_value);
715 }
716 return j_values;
717 }
718
719 JNIEnv* jni() {
720 return AttachCurrentThreadIfNeeded();
721 }
722
723 const ScopedGlobalRef<jobject> j_observer_global_;
724 const ScopedGlobalRef<jclass> j_observer_class_;
725 const ScopedGlobalRef<jclass> j_stats_report_class_;
726 const jmethodID j_stats_report_ctor_;
727 const ScopedGlobalRef<jclass> j_value_class_;
728 const jmethodID j_value_ctor_;
729 };
730
731 // Wrapper dispatching rtc::VideoSinkInterface to a Java VideoRenderer
732 // instance.
733 class JavaVideoRendererWrapper
734 : public rtc::VideoSinkInterface<cricket::VideoFrame> {
735 public:
736 JavaVideoRendererWrapper(JNIEnv* jni, jobject j_callbacks)
737 : j_callbacks_(jni, j_callbacks),
738 j_render_frame_id_(GetMethodID(
739 jni, GetObjectClass(jni, j_callbacks), "renderFrame",
740 "(Lorg/webrtc/VideoRenderer$I420Frame;)V")),
741 j_frame_class_(jni,
742 FindClass(jni, "org/webrtc/VideoRenderer$I420Frame")),
743 j_i420_frame_ctor_id_(GetMethodID(
744 jni, *j_frame_class_, "<init>", "(III[I[Ljava/nio/ByteBuffer;J)V")),
745 j_texture_frame_ctor_id_(GetMethodID(
746 jni, *j_frame_class_, "<init>",
747 "(IIII[FJ)V")),
748 j_byte_buffer_class_(jni, FindClass(jni, "java/nio/ByteBuffer")) {
749 CHECK_EXCEPTION(jni);
750 }
751
752 virtual ~JavaVideoRendererWrapper() {}
753
754 void OnFrame(const cricket::VideoFrame& video_frame) override {
755 ScopedLocalRefFrame local_ref_frame(jni());
756 jobject j_frame =
757 (video_frame.video_frame_buffer()->native_handle() != nullptr)
758 ? CricketToJavaTextureFrame(&video_frame)
759 : CricketToJavaI420Frame(&video_frame);
760 // |j_callbacks_| is responsible for releasing |j_frame| with
761 // VideoRenderer.renderFrameDone().
762 jni()->CallVoidMethod(*j_callbacks_, j_render_frame_id_, j_frame);
763 CHECK_EXCEPTION(jni());
764 }
765
766 private:
767 // Make a shallow copy of |frame| to be used with Java. The callee has
768 // ownership of the frame, and the frame should be released with
769 // VideoRenderer.releaseNativeFrame().
770 static jlong javaShallowCopy(const cricket::VideoFrame* frame) {
771 return jlongFromPointer(frame->Copy());
772 }
773
774 // Return a VideoRenderer.I420Frame referring to the data in |frame|.
775 jobject CricketToJavaI420Frame(const cricket::VideoFrame* frame) {
776 jintArray strides = jni()->NewIntArray(3);
777 jint* strides_array = jni()->GetIntArrayElements(strides, NULL);
778 strides_array[0] = frame->video_frame_buffer()->StrideY();
779 strides_array[1] = frame->video_frame_buffer()->StrideU();
780 strides_array[2] = frame->video_frame_buffer()->StrideV();
781 jni()->ReleaseIntArrayElements(strides, strides_array, 0);
782 jobjectArray planes = jni()->NewObjectArray(3, *j_byte_buffer_class_, NULL);
783 jobject y_buffer = jni()->NewDirectByteBuffer(
784 const_cast<uint8_t*>(frame->video_frame_buffer()->DataY()),
785 frame->video_frame_buffer()->StrideY() *
786 frame->video_frame_buffer()->height());
787 size_t chroma_height = (frame->height() + 1) / 2;
788 jobject u_buffer = jni()->NewDirectByteBuffer(
789 const_cast<uint8_t*>(frame->video_frame_buffer()->DataU()),
790 frame->video_frame_buffer()->StrideU() * chroma_height);
791 jobject v_buffer = jni()->NewDirectByteBuffer(
792 const_cast<uint8_t*>(frame->video_frame_buffer()->DataV()),
793 frame->video_frame_buffer()->StrideV() * chroma_height);
794
795 jni()->SetObjectArrayElement(planes, 0, y_buffer);
796 jni()->SetObjectArrayElement(planes, 1, u_buffer);
797 jni()->SetObjectArrayElement(planes, 2, v_buffer);
798 return jni()->NewObject(
799 *j_frame_class_, j_i420_frame_ctor_id_,
800 frame->width(), frame->height(),
801 static_cast<int>(frame->rotation()),
802 strides, planes, javaShallowCopy(frame));
803 }
804
805 // Return a VideoRenderer.I420Frame referring texture object in |frame|.
806 jobject CricketToJavaTextureFrame(const cricket::VideoFrame* frame) {
807 NativeHandleImpl* handle = reinterpret_cast<NativeHandleImpl*>(
808 frame->video_frame_buffer()->native_handle());
809 jfloatArray sampling_matrix = handle->sampling_matrix.ToJava(jni());
810
811 return jni()->NewObject(
812 *j_frame_class_, j_texture_frame_ctor_id_,
813 frame->width(), frame->height(),
814 static_cast<int>(frame->rotation()),
815 handle->oes_texture_id, sampling_matrix, javaShallowCopy(frame));
816 }
817
818 JNIEnv* jni() {
819 return AttachCurrentThreadIfNeeded();
820 }
821
822 ScopedGlobalRef<jobject> j_callbacks_;
823 jmethodID j_render_frame_id_;
824 ScopedGlobalRef<jclass> j_frame_class_;
825 jmethodID j_i420_frame_ctor_id_;
826 jmethodID j_texture_frame_ctor_id_;
827 ScopedGlobalRef<jclass> j_byte_buffer_class_;
828 };
829
830
831 static DataChannelInterface* ExtractNativeDC(JNIEnv* jni, jobject j_dc) {
832 jfieldID native_dc_id = GetFieldID(jni,
833 GetObjectClass(jni, j_dc), "nativeDataChannel", "J");
834 jlong j_d = GetLongField(jni, j_dc, native_dc_id);
835 return reinterpret_cast<DataChannelInterface*>(j_d);
836 }
837
838 JOW(jlong, DataChannel_registerObserverNative)(
839 JNIEnv* jni, jobject j_dc, jobject j_observer) {
840 std::unique_ptr<DataChannelObserverWrapper> observer(
841 new DataChannelObserverWrapper(jni, j_observer));
842 ExtractNativeDC(jni, j_dc)->RegisterObserver(observer.get());
843 return jlongFromPointer(observer.release());
844 }
845
846 JOW(void, DataChannel_unregisterObserverNative)(
847 JNIEnv* jni, jobject j_dc, jlong native_observer) {
848 ExtractNativeDC(jni, j_dc)->UnregisterObserver();
849 delete reinterpret_cast<DataChannelObserverWrapper*>(native_observer);
850 }
851
852 JOW(jstring, DataChannel_label)(JNIEnv* jni, jobject j_dc) {
853 return JavaStringFromStdString(jni, ExtractNativeDC(jni, j_dc)->label());
854 }
855
856 JOW(jobject, DataChannel_state)(JNIEnv* jni, jobject j_dc) {
857 return JavaEnumFromIndex(
858 jni, "DataChannel$State", ExtractNativeDC(jni, j_dc)->state());
859 }
860
861 JOW(jlong, DataChannel_bufferedAmount)(JNIEnv* jni, jobject j_dc) {
862 uint64_t buffered_amount = ExtractNativeDC(jni, j_dc)->buffered_amount();
863 RTC_CHECK_LE(buffered_amount, std::numeric_limits<int64_t>::max())
864 << "buffered_amount overflowed jlong!";
865 return static_cast<jlong>(buffered_amount);
866 }
867
868 JOW(void, DataChannel_close)(JNIEnv* jni, jobject j_dc) {
869 ExtractNativeDC(jni, j_dc)->Close();
870 }
871
872 JOW(jboolean, DataChannel_sendNative)(JNIEnv* jni, jobject j_dc,
873 jbyteArray data, jboolean binary) {
874 jbyte* bytes = jni->GetByteArrayElements(data, NULL);
875 bool ret = ExtractNativeDC(jni, j_dc)->Send(DataBuffer(
876 rtc::CopyOnWriteBuffer(bytes, jni->GetArrayLength(data)),
877 binary));
878 jni->ReleaseByteArrayElements(data, bytes, JNI_ABORT);
879 return ret;
880 }
881
882 JOW(void, DataChannel_dispose)(JNIEnv* jni, jobject j_dc) {
883 CHECK_RELEASE(ExtractNativeDC(jni, j_dc));
884 }
885
886 JOW(void, Logging_nativeEnableTracing)(
887 JNIEnv* jni, jclass, jstring j_path, jint nativeLevels) {
888 std::string path = JavaToStdString(jni, j_path);
889 if (nativeLevels != webrtc::kTraceNone) {
890 webrtc::Trace::set_level_filter(nativeLevels);
891 if (path != "logcat:") {
892 RTC_CHECK_EQ(0, webrtc::Trace::SetTraceFile(path.c_str(), false))
893 << "SetTraceFile failed";
894 } else {
895 // Intentionally leak this to avoid needing to reason about its lifecycle.
896 // It keeps no state and functions only as a dispatch point.
897 static LogcatTraceContext* g_trace_callback = new LogcatTraceContext();
898 }
899 }
900 }
901
902 JOW(void, Logging_nativeEnableLogToDebugOutput)
903 (JNIEnv *jni, jclass, jint nativeSeverity) {
904 if (nativeSeverity >= rtc::LS_SENSITIVE && nativeSeverity <= rtc::LS_NONE) {
905 rtc::LogMessage::LogToDebug(
906 static_cast<rtc::LoggingSeverity>(nativeSeverity));
907 }
908 }
909
910 JOW(void, Logging_nativeEnableLogThreads)(JNIEnv* jni, jclass) {
911 rtc::LogMessage::LogThreads(true);
912 }
913
914 JOW(void, Logging_nativeEnableLogTimeStamps)(JNIEnv* jni, jclass) {
915 rtc::LogMessage::LogTimestamps(true);
916 }
917
918 JOW(void, Logging_nativeLog)(
919 JNIEnv* jni, jclass, jint j_severity, jstring j_tag, jstring j_message) {
920 std::string message = JavaToStdString(jni, j_message);
921 std::string tag = JavaToStdString(jni, j_tag);
922 LOG_TAG(static_cast<rtc::LoggingSeverity>(j_severity), tag) << message;
923 }
924
925 JOW(void, PeerConnection_freePeerConnection)(JNIEnv*, jclass, jlong j_p) {
926 CHECK_RELEASE(reinterpret_cast<PeerConnectionInterface*>(j_p));
927 }
928
929 JOW(void, PeerConnection_freeObserver)(JNIEnv*, jclass, jlong j_p) {
930 PCOJava* p = reinterpret_cast<PCOJava*>(j_p);
931 delete p;
932 }
933
934 JOW(void, MediaSource_free)(JNIEnv*, jclass, jlong j_p) {
935 CHECK_RELEASE(reinterpret_cast<MediaSourceInterface*>(j_p));
936 }
937
938 JOW(void, VideoRenderer_freeWrappedVideoRenderer)(JNIEnv*, jclass, jlong j_p) {
939 delete reinterpret_cast<JavaVideoRendererWrapper*>(j_p);
940 }
941
942 JOW(void, VideoRenderer_releaseNativeFrame)(
943 JNIEnv* jni, jclass, jlong j_frame_ptr) {
944 delete reinterpret_cast<const cricket::VideoFrame*>(j_frame_ptr);
945 }
946
947 JOW(void, MediaStreamTrack_free)(JNIEnv*, jclass, jlong j_p) {
948 reinterpret_cast<MediaStreamTrackInterface*>(j_p)->Release();
949 }
950
951 JOW(jboolean, MediaStream_nativeAddAudioTrack)(
952 JNIEnv* jni, jclass, jlong pointer, jlong j_audio_track_pointer) {
953 return reinterpret_cast<MediaStreamInterface*>(pointer)->AddTrack(
954 reinterpret_cast<AudioTrackInterface*>(j_audio_track_pointer));
955 }
956
957 JOW(jboolean, MediaStream_nativeAddVideoTrack)(
958 JNIEnv* jni, jclass, jlong pointer, jlong j_video_track_pointer) {
959 return reinterpret_cast<MediaStreamInterface*>(pointer)
960 ->AddTrack(reinterpret_cast<VideoTrackInterface*>(j_video_track_pointer));
961 }
962
963 JOW(jboolean, MediaStream_nativeRemoveAudioTrack)(
964 JNIEnv* jni, jclass, jlong pointer, jlong j_audio_track_pointer) {
965 return reinterpret_cast<MediaStreamInterface*>(pointer)->RemoveTrack(
966 reinterpret_cast<AudioTrackInterface*>(j_audio_track_pointer));
967 }
968
969 JOW(jboolean, MediaStream_nativeRemoveVideoTrack)(
970 JNIEnv* jni, jclass, jlong pointer, jlong j_video_track_pointer) {
971 return reinterpret_cast<MediaStreamInterface*>(pointer)->RemoveTrack(
972 reinterpret_cast<VideoTrackInterface*>(j_video_track_pointer));
973 }
974
975 JOW(jstring, MediaStream_nativeLabel)(JNIEnv* jni, jclass, jlong j_p) {
976 return JavaStringFromStdString(
977 jni, reinterpret_cast<MediaStreamInterface*>(j_p)->label());
978 }
979
980 JOW(void, MediaStream_free)(JNIEnv*, jclass, jlong j_p) {
981 CHECK_RELEASE(reinterpret_cast<MediaStreamInterface*>(j_p));
982 }
983
984 JOW(jlong, PeerConnectionFactory_nativeCreateObserver)(
985 JNIEnv * jni, jclass, jobject j_observer) {
986 return (jlong)new PCOJava(jni, j_observer);
987 }
988
989 JOW(jboolean, PeerConnectionFactory_initializeAndroidGlobals)(
990 JNIEnv* jni, jclass, jobject context,
991 jboolean initialize_audio, jboolean initialize_video,
992 jboolean video_hw_acceleration) {
993 bool failure = false;
994 video_hw_acceleration_enabled = video_hw_acceleration;
995 AndroidNetworkMonitor::SetAndroidContext(jni, context);
996 if (!factory_static_initialized) {
997 if (initialize_video) {
998 failure |= AndroidVideoCapturerJni::SetAndroidObjects(jni, context);
999 }
1000 if (initialize_audio)
1001 failure |= webrtc::VoiceEngine::SetAndroidObjects(GetJVM(), context);
1002 factory_static_initialized = true;
1003 }
1004 return !failure;
1005 }
1006
1007 JOW(void, PeerConnectionFactory_initializeFieldTrials)(
1008 JNIEnv* jni, jclass, jstring j_trials_init_string) {
1009 field_trials_init_string = NULL;
1010 if (j_trials_init_string != NULL) {
1011 const char* init_string =
1012 jni->GetStringUTFChars(j_trials_init_string, NULL);
1013 int init_string_length = jni->GetStringUTFLength(j_trials_init_string);
1014 field_trials_init_string = new char[init_string_length + 1];
1015 rtc::strcpyn(field_trials_init_string, init_string_length + 1, init_string);
1016 jni->ReleaseStringUTFChars(j_trials_init_string, init_string);
1017 LOG(LS_INFO) << "initializeFieldTrials: " << field_trials_init_string;
1018 }
1019 webrtc::field_trial::InitFieldTrialsFromString(field_trials_init_string);
1020 }
1021
1022 JOW(void, PeerConnectionFactory_initializeInternalTracer)(JNIEnv* jni, jclass) {
1023 rtc::tracing::SetupInternalTracer();
1024 }
1025
1026 JOW(jboolean, PeerConnectionFactory_startInternalTracingCapture)(
1027 JNIEnv* jni, jclass, jstring j_event_tracing_filename) {
1028 if (!j_event_tracing_filename)
1029 return false;
1030
1031 const char* init_string =
1032 jni->GetStringUTFChars(j_event_tracing_filename, NULL);
1033 LOG(LS_INFO) << "Starting internal tracing to: " << init_string;
1034 bool ret = rtc::tracing::StartInternalCapture(init_string);
1035 jni->ReleaseStringUTFChars(j_event_tracing_filename, init_string);
1036 return ret;
1037 }
1038
1039 JOW(void, PeerConnectionFactory_stopInternalTracingCapture)(
1040 JNIEnv* jni, jclass) {
1041 rtc::tracing::StopInternalCapture();
1042 }
1043
1044 JOW(void, PeerConnectionFactory_shutdownInternalTracer)(JNIEnv* jni, jclass) {
1045 rtc::tracing::ShutdownInternalTracer();
1046 }
1047
1048 // Helper struct for working around the fact that CreatePeerConnectionFactory()
1049 // comes in two flavors: either entirely automagical (constructing its own
1050 // threads and deleting them on teardown, but no external codec factory support)
1051 // or entirely manual (requires caller to delete threads after factory
1052 // teardown). This struct takes ownership of its ctor's arguments to present a
1053 // single thing for Java to hold and eventually free.
1054 class OwnedFactoryAndThreads {
1055 public:
1056 OwnedFactoryAndThreads(std::unique_ptr<Thread> network_thread,
1057 std::unique_ptr<Thread> worker_thread,
1058 std::unique_ptr<Thread> signaling_thread,
1059 WebRtcVideoEncoderFactory* encoder_factory,
1060 WebRtcVideoDecoderFactory* decoder_factory,
1061 rtc::NetworkMonitorFactory* network_monitor_factory,
1062 PeerConnectionFactoryInterface* factory)
1063 : network_thread_(std::move(network_thread)),
1064 worker_thread_(std::move(worker_thread)),
1065 signaling_thread_(std::move(signaling_thread)),
1066 encoder_factory_(encoder_factory),
1067 decoder_factory_(decoder_factory),
1068 network_monitor_factory_(network_monitor_factory),
1069 factory_(factory) {}
1070
1071 ~OwnedFactoryAndThreads() {
1072 CHECK_RELEASE(factory_);
1073 if (network_monitor_factory_ != nullptr) {
1074 rtc::NetworkMonitorFactory::ReleaseFactory(network_monitor_factory_);
1075 }
1076 }
1077
1078 PeerConnectionFactoryInterface* factory() { return factory_; }
1079 WebRtcVideoEncoderFactory* encoder_factory() { return encoder_factory_; }
1080 WebRtcVideoDecoderFactory* decoder_factory() { return decoder_factory_; }
1081 rtc::NetworkMonitorFactory* network_monitor_factory() {
1082 return network_monitor_factory_;
1083 }
1084 void clear_network_monitor_factory() { network_monitor_factory_ = nullptr; }
1085 void InvokeJavaCallbacksOnFactoryThreads();
1086
1087 private:
1088 void JavaCallbackOnFactoryThreads();
1089
1090 const std::unique_ptr<Thread> network_thread_;
1091 const std::unique_ptr<Thread> worker_thread_;
1092 const std::unique_ptr<Thread> signaling_thread_;
1093 WebRtcVideoEncoderFactory* encoder_factory_;
1094 WebRtcVideoDecoderFactory* decoder_factory_;
1095 rtc::NetworkMonitorFactory* network_monitor_factory_;
1096 PeerConnectionFactoryInterface* factory_; // Const after ctor except dtor.
1097 };
1098
1099 void OwnedFactoryAndThreads::JavaCallbackOnFactoryThreads() {
1100 JNIEnv* jni = AttachCurrentThreadIfNeeded();
1101 ScopedLocalRefFrame local_ref_frame(jni);
1102 jclass j_factory_class = FindClass(jni, "org/webrtc/PeerConnectionFactory");
1103 jmethodID m = nullptr;
1104 if (network_thread_->IsCurrent()) {
1105 LOG(LS_INFO) << "Network thread JavaCallback";
1106 m = GetStaticMethodID(jni, j_factory_class, "onNetworkThreadReady", "()V");
1107 }
1108 if (worker_thread_->IsCurrent()) {
1109 LOG(LS_INFO) << "Worker thread JavaCallback";
1110 m = GetStaticMethodID(jni, j_factory_class, "onWorkerThreadReady", "()V");
1111 }
1112 if (signaling_thread_->IsCurrent()) {
1113 LOG(LS_INFO) << "Signaling thread JavaCallback";
1114 m = GetStaticMethodID(
1115 jni, j_factory_class, "onSignalingThreadReady", "()V");
1116 }
1117 if (m != nullptr) {
1118 jni->CallStaticVoidMethod(j_factory_class, m);
1119 CHECK_EXCEPTION(jni) << "error during JavaCallback::CallStaticVoidMethod";
1120 }
1121 }
1122
1123 void OwnedFactoryAndThreads::InvokeJavaCallbacksOnFactoryThreads() {
1124 LOG(LS_INFO) << "InvokeJavaCallbacksOnFactoryThreads.";
1125 network_thread_->Invoke<void>(RTC_FROM_HERE,
1126 [this] { JavaCallbackOnFactoryThreads(); });
1127 worker_thread_->Invoke<void>(RTC_FROM_HERE,
1128 [this] { JavaCallbackOnFactoryThreads(); });
1129 signaling_thread_->Invoke<void>(RTC_FROM_HERE,
1130 [this] { JavaCallbackOnFactoryThreads(); });
1131 }
1132
1133 PeerConnectionFactoryInterface::Options ParseOptionsFromJava(JNIEnv* jni,
1134 jobject options) {
1135 jclass options_class = jni->GetObjectClass(options);
1136 jfieldID network_ignore_mask_field =
1137 jni->GetFieldID(options_class, "networkIgnoreMask", "I");
1138 int network_ignore_mask =
1139 jni->GetIntField(options, network_ignore_mask_field);
1140
1141 jfieldID disable_encryption_field =
1142 jni->GetFieldID(options_class, "disableEncryption", "Z");
1143 bool disable_encryption =
1144 jni->GetBooleanField(options, disable_encryption_field);
1145
1146 jfieldID disable_network_monitor_field =
1147 jni->GetFieldID(options_class, "disableNetworkMonitor", "Z");
1148 bool disable_network_monitor =
1149 jni->GetBooleanField(options, disable_network_monitor_field);
1150
1151 PeerConnectionFactoryInterface::Options native_options;
1152
1153 // This doesn't necessarily match the c++ version of this struct; feel free
1154 // to add more parameters as necessary.
1155 native_options.network_ignore_mask = network_ignore_mask;
1156 native_options.disable_encryption = disable_encryption;
1157 native_options.disable_network_monitor = disable_network_monitor;
1158 return native_options;
1159 }
1160
1161 JOW(jlong, PeerConnectionFactory_nativeCreatePeerConnectionFactory)(
1162 JNIEnv* jni, jclass, jobject joptions) {
1163 // talk/ assumes pretty widely that the current Thread is ThreadManager'd, but
1164 // ThreadManager only WrapCurrentThread()s the thread where it is first
1165 // created. Since the semantics around when auto-wrapping happens in
1166 // webrtc/base/ are convoluted, we simply wrap here to avoid having to think
1167 // about ramifications of auto-wrapping there.
1168 rtc::ThreadManager::Instance()->WrapCurrentThread();
1169 webrtc::Trace::CreateTrace();
1170
1171 std::unique_ptr<Thread> network_thread =
1172 rtc::Thread::CreateWithSocketServer();
1173 network_thread->SetName("network_thread", nullptr);
1174 RTC_CHECK(network_thread->Start()) << "Failed to start thread";
1175
1176 std::unique_ptr<Thread> worker_thread = rtc::Thread::Create();
1177 worker_thread->SetName("worker_thread", nullptr);
1178 RTC_CHECK(worker_thread->Start()) << "Failed to start thread";
1179
1180 std::unique_ptr<Thread> signaling_thread = rtc::Thread::Create();
1181 signaling_thread->SetName("signaling_thread", NULL);
1182 RTC_CHECK(signaling_thread->Start()) << "Failed to start thread";
1183
1184 WebRtcVideoEncoderFactory* encoder_factory = nullptr;
1185 WebRtcVideoDecoderFactory* decoder_factory = nullptr;
1186 rtc::NetworkMonitorFactory* network_monitor_factory = nullptr;
1187
1188 PeerConnectionFactoryInterface::Options options;
1189 bool has_options = joptions != NULL;
1190 if (has_options) {
1191 options = ParseOptionsFromJava(jni, joptions);
1192 }
1193
1194 if (video_hw_acceleration_enabled) {
1195 encoder_factory = new MediaCodecVideoEncoderFactory();
1196 decoder_factory = new MediaCodecVideoDecoderFactory();
1197 }
1198 // Do not create network_monitor_factory only if the options are
1199 // provided and disable_network_monitor therein is set to true.
1200 if (!(has_options && options.disable_network_monitor)) {
1201 network_monitor_factory = new AndroidNetworkMonitorFactory();
1202 rtc::NetworkMonitorFactory::SetFactory(network_monitor_factory);
1203 }
1204
1205 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1206 webrtc::CreatePeerConnectionFactory(
1207 network_thread.get(), worker_thread.get(), signaling_thread.get(),
1208 nullptr, encoder_factory, decoder_factory));
1209 RTC_CHECK(factory) << "Failed to create the peer connection factory; "
1210 << "WebRTC/libjingle init likely failed on this device";
1211 // TODO(honghaiz): Maybe put the options as the argument of
1212 // CreatePeerConnectionFactory.
1213 if (has_options) {
1214 factory->SetOptions(options);
1215 }
1216 OwnedFactoryAndThreads* owned_factory = new OwnedFactoryAndThreads(
1217 std::move(network_thread), std::move(worker_thread),
1218 std::move(signaling_thread), encoder_factory, decoder_factory,
1219 network_monitor_factory, factory.release());
1220 owned_factory->InvokeJavaCallbacksOnFactoryThreads();
1221 return jlongFromPointer(owned_factory);
1222 }
1223
1224 JOW(void, PeerConnectionFactory_nativeFreeFactory)(JNIEnv*, jclass, jlong j_p) {
1225 delete reinterpret_cast<OwnedFactoryAndThreads*>(j_p);
1226 if (field_trials_init_string) {
1227 webrtc::field_trial::InitFieldTrialsFromString(NULL);
1228 delete field_trials_init_string;
1229 field_trials_init_string = NULL;
1230 }
1231 webrtc::Trace::ReturnTrace();
1232 }
1233
1234 static PeerConnectionFactoryInterface* factoryFromJava(jlong j_p) {
1235 return reinterpret_cast<OwnedFactoryAndThreads*>(j_p)->factory();
1236 }
1237
1238 JOW(void, PeerConnectionFactory_nativeThreadsCallbacks)(
1239 JNIEnv*, jclass, jlong j_p) {
1240 OwnedFactoryAndThreads *factory =
1241 reinterpret_cast<OwnedFactoryAndThreads*>(j_p);
1242 factory->InvokeJavaCallbacksOnFactoryThreads();
1243 }
1244
1245 JOW(jlong, PeerConnectionFactory_nativeCreateLocalMediaStream)(
1246 JNIEnv* jni, jclass, jlong native_factory, jstring label) {
1247 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1248 factoryFromJava(native_factory));
1249 rtc::scoped_refptr<MediaStreamInterface> stream(
1250 factory->CreateLocalMediaStream(JavaToStdString(jni, label)));
1251 return (jlong)stream.release();
1252 }
1253
1254 JOW(jlong, PeerConnectionFactory_nativeCreateVideoSource)(
1255 JNIEnv* jni, jclass, jlong native_factory, jobject j_egl_context,
1256 jobject j_video_capturer, jobject j_constraints) {
1257 // Create a cricket::VideoCapturer from |j_video_capturer|.
1258 rtc::scoped_refptr<webrtc::AndroidVideoCapturerDelegate> delegate =
1259 new rtc::RefCountedObject<AndroidVideoCapturerJni>(
1260 jni, j_video_capturer, j_egl_context);
1261 std::unique_ptr<cricket::VideoCapturer> capturer(
1262 new webrtc::AndroidVideoCapturer(delegate));
1263 // Create a webrtc::VideoTrackSourceInterface from the cricket::VideoCapturer,
1264 // native factory and constraints.
1265 std::unique_ptr<ConstraintsWrapper> constraints(
1266 new ConstraintsWrapper(jni, j_constraints));
1267 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1268 factoryFromJava(native_factory));
1269 rtc::scoped_refptr<VideoTrackSourceInterface> source(
1270 factory->CreateVideoSource(capturer.release(), constraints.get()));
1271 return (jlong)source.release();
1272 }
1273
1274 JOW(jlong, PeerConnectionFactory_nativeCreateVideoTrack)(
1275 JNIEnv* jni, jclass, jlong native_factory, jstring id,
1276 jlong native_source) {
1277 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1278 factoryFromJava(native_factory));
1279 rtc::scoped_refptr<VideoTrackInterface> track(factory->CreateVideoTrack(
1280 JavaToStdString(jni, id),
1281 reinterpret_cast<VideoTrackSourceInterface*>(native_source)));
1282 return (jlong)track.release();
1283 }
1284
1285 JOW(jlong, PeerConnectionFactory_nativeCreateAudioSource)(
1286 JNIEnv* jni, jclass, jlong native_factory, jobject j_constraints) {
1287 std::unique_ptr<ConstraintsWrapper> constraints(
1288 new ConstraintsWrapper(jni, j_constraints));
1289 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1290 factoryFromJava(native_factory));
1291 rtc::scoped_refptr<AudioSourceInterface> source(
1292 factory->CreateAudioSource(constraints.get()));
1293 return (jlong)source.release();
1294 }
1295
1296 JOW(jlong, PeerConnectionFactory_nativeCreateAudioTrack)(
1297 JNIEnv* jni, jclass, jlong native_factory, jstring id,
1298 jlong native_source) {
1299 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1300 factoryFromJava(native_factory));
1301 rtc::scoped_refptr<AudioTrackInterface> track(factory->CreateAudioTrack(
1302 JavaToStdString(jni, id),
1303 reinterpret_cast<AudioSourceInterface*>(native_source)));
1304 return (jlong)track.release();
1305 }
1306
1307 JOW(jboolean, PeerConnectionFactory_nativeStartAecDump)(
1308 JNIEnv* jni, jclass, jlong native_factory, jint file,
1309 jint filesize_limit_bytes) {
1310 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1311 factoryFromJava(native_factory));
1312 return factory->StartAecDump(file, filesize_limit_bytes);
1313 }
1314
1315 JOW(void, PeerConnectionFactory_nativeStopAecDump)(
1316 JNIEnv* jni, jclass, jlong native_factory) {
1317 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1318 factoryFromJava(native_factory));
1319 factory->StopAecDump();
1320 }
1321
1322 JOW(jboolean, PeerConnectionFactory_nativeStartRtcEventLog)
1323 (JNIEnv* jni,
1324 jclass,
1325 jlong native_factory,
1326 jint file,
1327 jint filesize_limit_bytes) {
1328 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1329 factoryFromJava(native_factory));
1330 return factory->StartRtcEventLog(file, filesize_limit_bytes);
1331 }
1332
1333 JOW(void, PeerConnectionFactory_nativeStopRtcEventLog)(
1334 JNIEnv* jni, jclass, jlong native_factory) {
1335 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1336 factoryFromJava(native_factory));
1337 factory->StopRtcEventLog();
1338 }
1339
1340 JOW(void, PeerConnectionFactory_nativeSetOptions)(
1341 JNIEnv* jni, jclass, jlong native_factory, jobject options) {
1342 rtc::scoped_refptr<PeerConnectionFactoryInterface> factory(
1343 factoryFromJava(native_factory));
1344 PeerConnectionFactoryInterface::Options options_to_set =
1345 ParseOptionsFromJava(jni, options);
1346 factory->SetOptions(options_to_set);
1347
1348 if (options_to_set.disable_network_monitor) {
1349 OwnedFactoryAndThreads* owner =
1350 reinterpret_cast<OwnedFactoryAndThreads*>(native_factory);
1351 if (owner->network_monitor_factory()) {
1352 rtc::NetworkMonitorFactory::ReleaseFactory(
1353 owner->network_monitor_factory());
1354 owner->clear_network_monitor_factory();
1355 }
1356 }
1357 }
1358
1359 JOW(void, PeerConnectionFactory_nativeSetVideoHwAccelerationOptions)(
1360 JNIEnv* jni, jclass, jlong native_factory, jobject local_egl_context,
1361 jobject remote_egl_context) {
1362 OwnedFactoryAndThreads* owned_factory =
1363 reinterpret_cast<OwnedFactoryAndThreads*>(native_factory);
1364
1365 jclass j_eglbase14_context_class =
1366 FindClass(jni, "org/webrtc/EglBase14$Context");
1367
1368 MediaCodecVideoEncoderFactory* encoder_factory =
1369 static_cast<MediaCodecVideoEncoderFactory*>
1370 (owned_factory->encoder_factory());
1371 if (encoder_factory &&
1372 jni->IsInstanceOf(local_egl_context, j_eglbase14_context_class)) {
1373 LOG(LS_INFO) << "Set EGL context for HW encoding.";
1374 encoder_factory->SetEGLContext(jni, local_egl_context);
1375 }
1376
1377 MediaCodecVideoDecoderFactory* decoder_factory =
1378 static_cast<MediaCodecVideoDecoderFactory*>
1379 (owned_factory->decoder_factory());
1380 if (decoder_factory) {
1381 LOG(LS_INFO) << "Set EGL context for HW decoding.";
1382 decoder_factory->SetEGLContext(jni, remote_egl_context);
1383 }
1384 }
1385
1386 static PeerConnectionInterface::IceTransportsType
1387 JavaIceTransportsTypeToNativeType(JNIEnv* jni, jobject j_ice_transports_type) {
1388 std::string enum_name = GetJavaEnumName(
1389 jni, "org/webrtc/PeerConnection$IceTransportsType",
1390 j_ice_transports_type);
1391
1392 if (enum_name == "ALL")
1393 return PeerConnectionInterface::kAll;
1394
1395 if (enum_name == "RELAY")
1396 return PeerConnectionInterface::kRelay;
1397
1398 if (enum_name == "NOHOST")
1399 return PeerConnectionInterface::kNoHost;
1400
1401 if (enum_name == "NONE")
1402 return PeerConnectionInterface::kNone;
1403
1404 RTC_CHECK(false) << "Unexpected IceTransportsType enum_name " << enum_name;
1405 return PeerConnectionInterface::kAll;
1406 }
1407
1408 static PeerConnectionInterface::BundlePolicy
1409 JavaBundlePolicyToNativeType(JNIEnv* jni, jobject j_bundle_policy) {
1410 std::string enum_name = GetJavaEnumName(
1411 jni, "org/webrtc/PeerConnection$BundlePolicy",
1412 j_bundle_policy);
1413
1414 if (enum_name == "BALANCED")
1415 return PeerConnectionInterface::kBundlePolicyBalanced;
1416
1417 if (enum_name == "MAXBUNDLE")
1418 return PeerConnectionInterface::kBundlePolicyMaxBundle;
1419
1420 if (enum_name == "MAXCOMPAT")
1421 return PeerConnectionInterface::kBundlePolicyMaxCompat;
1422
1423 RTC_CHECK(false) << "Unexpected BundlePolicy enum_name " << enum_name;
1424 return PeerConnectionInterface::kBundlePolicyBalanced;
1425 }
1426
1427 static PeerConnectionInterface::RtcpMuxPolicy
1428 JavaRtcpMuxPolicyToNativeType(JNIEnv* jni, jobject j_rtcp_mux_policy) {
1429 std::string enum_name = GetJavaEnumName(
1430 jni, "org/webrtc/PeerConnection$RtcpMuxPolicy",
1431 j_rtcp_mux_policy);
1432
1433 if (enum_name == "NEGOTIATE")
1434 return PeerConnectionInterface::kRtcpMuxPolicyNegotiate;
1435
1436 if (enum_name == "REQUIRE")
1437 return PeerConnectionInterface::kRtcpMuxPolicyRequire;
1438
1439 RTC_CHECK(false) << "Unexpected RtcpMuxPolicy enum_name " << enum_name;
1440 return PeerConnectionInterface::kRtcpMuxPolicyNegotiate;
1441 }
1442
1443 static PeerConnectionInterface::TcpCandidatePolicy
1444 JavaTcpCandidatePolicyToNativeType(
1445 JNIEnv* jni, jobject j_tcp_candidate_policy) {
1446 std::string enum_name = GetJavaEnumName(
1447 jni, "org/webrtc/PeerConnection$TcpCandidatePolicy",
1448 j_tcp_candidate_policy);
1449
1450 if (enum_name == "ENABLED")
1451 return PeerConnectionInterface::kTcpCandidatePolicyEnabled;
1452
1453 if (enum_name == "DISABLED")
1454 return PeerConnectionInterface::kTcpCandidatePolicyDisabled;
1455
1456 RTC_CHECK(false) << "Unexpected TcpCandidatePolicy enum_name " << enum_name;
1457 return PeerConnectionInterface::kTcpCandidatePolicyEnabled;
1458 }
1459
1460 static PeerConnectionInterface::CandidateNetworkPolicy
1461 JavaCandidateNetworkPolicyToNativeType(JNIEnv* jni,
1462 jobject j_candidate_network_policy) {
1463 std::string enum_name =
1464 GetJavaEnumName(jni, "org/webrtc/PeerConnection$CandidateNetworkPolicy",
1465 j_candidate_network_policy);
1466
1467 if (enum_name == "ALL")
1468 return PeerConnectionInterface::kCandidateNetworkPolicyAll;
1469
1470 if (enum_name == "LOW_COST")
1471 return PeerConnectionInterface::kCandidateNetworkPolicyLowCost;
1472
1473 RTC_CHECK(false) << "Unexpected CandidateNetworkPolicy enum_name "
1474 << enum_name;
1475 return PeerConnectionInterface::kCandidateNetworkPolicyAll;
1476 }
1477
1478 static rtc::KeyType JavaKeyTypeToNativeType(JNIEnv* jni, jobject j_key_type) {
1479 std::string enum_name = GetJavaEnumName(
1480 jni, "org/webrtc/PeerConnection$KeyType", j_key_type);
1481
1482 if (enum_name == "RSA")
1483 return rtc::KT_RSA;
1484 if (enum_name == "ECDSA")
1485 return rtc::KT_ECDSA;
1486
1487 RTC_CHECK(false) << "Unexpected KeyType enum_name " << enum_name;
1488 return rtc::KT_ECDSA;
1489 }
1490
1491 static PeerConnectionInterface::ContinualGatheringPolicy
1492 JavaContinualGatheringPolicyToNativeType(
1493 JNIEnv* jni, jobject j_gathering_policy) {
1494 std::string enum_name = GetJavaEnumName(
1495 jni, "org/webrtc/PeerConnection$ContinualGatheringPolicy",
1496 j_gathering_policy);
1497 if (enum_name == "GATHER_ONCE")
1498 return PeerConnectionInterface::GATHER_ONCE;
1499
1500 if (enum_name == "GATHER_CONTINUALLY")
1501 return PeerConnectionInterface::GATHER_CONTINUALLY;
1502
1503 RTC_CHECK(false) << "Unexpected ContinualGatheringPolicy enum name "
1504 << enum_name;
1505 return PeerConnectionInterface::GATHER_ONCE;
1506 }
1507
1508 static void JavaIceServersToJsepIceServers(
1509 JNIEnv* jni, jobject j_ice_servers,
1510 PeerConnectionInterface::IceServers* ice_servers) {
1511 for (jobject j_ice_server : Iterable(jni, j_ice_servers)) {
1512 jclass j_ice_server_class = GetObjectClass(jni, j_ice_server);
1513 jfieldID j_ice_server_uri_id =
1514 GetFieldID(jni, j_ice_server_class, "uri", "Ljava/lang/String;");
1515 jfieldID j_ice_server_username_id =
1516 GetFieldID(jni, j_ice_server_class, "username", "Ljava/lang/String;");
1517 jfieldID j_ice_server_password_id =
1518 GetFieldID(jni, j_ice_server_class, "password", "Ljava/lang/String;");
1519 jstring uri = reinterpret_cast<jstring>(
1520 GetObjectField(jni, j_ice_server, j_ice_server_uri_id));
1521 jstring username = reinterpret_cast<jstring>(
1522 GetObjectField(jni, j_ice_server, j_ice_server_username_id));
1523 jstring password = reinterpret_cast<jstring>(
1524 GetObjectField(jni, j_ice_server, j_ice_server_password_id));
1525 PeerConnectionInterface::IceServer server;
1526 server.uri = JavaToStdString(jni, uri);
1527 server.username = JavaToStdString(jni, username);
1528 server.password = JavaToStdString(jni, password);
1529 ice_servers->push_back(server);
1530 }
1531 }
1532
1533 static void JavaRTCConfigurationToJsepRTCConfiguration(
1534 JNIEnv* jni,
1535 jobject j_rtc_config,
1536 PeerConnectionInterface::RTCConfiguration* rtc_config) {
1537 jclass j_rtc_config_class = GetObjectClass(jni, j_rtc_config);
1538
1539 jfieldID j_ice_transports_type_id = GetFieldID(
1540 jni, j_rtc_config_class, "iceTransportsType",
1541 "Lorg/webrtc/PeerConnection$IceTransportsType;");
1542 jobject j_ice_transports_type = GetObjectField(
1543 jni, j_rtc_config, j_ice_transports_type_id);
1544
1545 jfieldID j_bundle_policy_id = GetFieldID(
1546 jni, j_rtc_config_class, "bundlePolicy",
1547 "Lorg/webrtc/PeerConnection$BundlePolicy;");
1548 jobject j_bundle_policy = GetObjectField(
1549 jni, j_rtc_config, j_bundle_policy_id);
1550
1551 jfieldID j_rtcp_mux_policy_id = GetFieldID(
1552 jni, j_rtc_config_class, "rtcpMuxPolicy",
1553 "Lorg/webrtc/PeerConnection$RtcpMuxPolicy;");
1554 jobject j_rtcp_mux_policy = GetObjectField(
1555 jni, j_rtc_config, j_rtcp_mux_policy_id);
1556
1557 jfieldID j_tcp_candidate_policy_id = GetFieldID(
1558 jni, j_rtc_config_class, "tcpCandidatePolicy",
1559 "Lorg/webrtc/PeerConnection$TcpCandidatePolicy;");
1560 jobject j_tcp_candidate_policy = GetObjectField(
1561 jni, j_rtc_config, j_tcp_candidate_policy_id);
1562
1563 jfieldID j_candidate_network_policy_id = GetFieldID(
1564 jni, j_rtc_config_class, "candidateNetworkPolicy",
1565 "Lorg/webrtc/PeerConnection$CandidateNetworkPolicy;");
1566 jobject j_candidate_network_policy = GetObjectField(
1567 jni, j_rtc_config, j_candidate_network_policy_id);
1568
1569 jfieldID j_ice_servers_id = GetFieldID(
1570 jni, j_rtc_config_class, "iceServers", "Ljava/util/List;");
1571 jobject j_ice_servers = GetObjectField(jni, j_rtc_config, j_ice_servers_id);
1572
1573 jfieldID j_audio_jitter_buffer_max_packets_id =
1574 GetFieldID(jni, j_rtc_config_class, "audioJitterBufferMaxPackets", "I");
1575 jfieldID j_audio_jitter_buffer_fast_accelerate_id = GetFieldID(
1576 jni, j_rtc_config_class, "audioJitterBufferFastAccelerate", "Z");
1577
1578 jfieldID j_ice_connection_receiving_timeout_id =
1579 GetFieldID(jni, j_rtc_config_class, "iceConnectionReceivingTimeout", "I");
1580
1581 jfieldID j_ice_backup_candidate_pair_ping_interval_id = GetFieldID(
1582 jni, j_rtc_config_class, "iceBackupCandidatePairPingInterval", "I");
1583
1584 jfieldID j_continual_gathering_policy_id =
1585 GetFieldID(jni, j_rtc_config_class, "continualGatheringPolicy",
1586 "Lorg/webrtc/PeerConnection$ContinualGatheringPolicy;");
1587 jobject j_continual_gathering_policy =
1588 GetObjectField(jni, j_rtc_config, j_continual_gathering_policy_id);
1589
1590 jfieldID j_ice_candidate_pool_size_id =
1591 GetFieldID(jni, j_rtc_config_class, "iceCandidatePoolSize", "I");
1592
1593 rtc_config->type =
1594 JavaIceTransportsTypeToNativeType(jni, j_ice_transports_type);
1595 rtc_config->bundle_policy =
1596 JavaBundlePolicyToNativeType(jni, j_bundle_policy);
1597 rtc_config->rtcp_mux_policy =
1598 JavaRtcpMuxPolicyToNativeType(jni, j_rtcp_mux_policy);
1599 rtc_config->tcp_candidate_policy =
1600 JavaTcpCandidatePolicyToNativeType(jni, j_tcp_candidate_policy);
1601 rtc_config->candidate_network_policy =
1602 JavaCandidateNetworkPolicyToNativeType(jni, j_candidate_network_policy);
1603 JavaIceServersToJsepIceServers(jni, j_ice_servers, &rtc_config->servers);
1604 rtc_config->audio_jitter_buffer_max_packets =
1605 GetIntField(jni, j_rtc_config, j_audio_jitter_buffer_max_packets_id);
1606 rtc_config->audio_jitter_buffer_fast_accelerate = GetBooleanField(
1607 jni, j_rtc_config, j_audio_jitter_buffer_fast_accelerate_id);
1608 rtc_config->ice_connection_receiving_timeout =
1609 GetIntField(jni, j_rtc_config, j_ice_connection_receiving_timeout_id);
1610 rtc_config->ice_backup_candidate_pair_ping_interval = GetIntField(
1611 jni, j_rtc_config, j_ice_backup_candidate_pair_ping_interval_id);
1612 rtc_config->continual_gathering_policy =
1613 JavaContinualGatheringPolicyToNativeType(
1614 jni, j_continual_gathering_policy);
1615 rtc_config->ice_candidate_pool_size =
1616 GetIntField(jni, j_rtc_config, j_ice_candidate_pool_size_id);
1617 }
1618
1619 JOW(jlong, PeerConnectionFactory_nativeCreatePeerConnection)(
1620 JNIEnv *jni, jclass, jlong factory, jobject j_rtc_config,
1621 jobject j_constraints, jlong observer_p) {
1622 rtc::scoped_refptr<PeerConnectionFactoryInterface> f(
1623 reinterpret_cast<PeerConnectionFactoryInterface*>(
1624 factoryFromJava(factory)));
1625
1626 PeerConnectionInterface::RTCConfiguration rtc_config;
1627 JavaRTCConfigurationToJsepRTCConfiguration(jni, j_rtc_config, &rtc_config);
1628
1629 jclass j_rtc_config_class = GetObjectClass(jni, j_rtc_config);
1630 jfieldID j_key_type_id = GetFieldID(jni, j_rtc_config_class, "keyType",
1631 "Lorg/webrtc/PeerConnection$KeyType;");
1632 jobject j_key_type = GetObjectField(jni, j_rtc_config, j_key_type_id);
1633
1634 // Generate non-default certificate.
1635 rtc::KeyType key_type = JavaKeyTypeToNativeType(jni, j_key_type);
1636 if (key_type != rtc::KT_DEFAULT) {
1637 rtc::scoped_refptr<rtc::RTCCertificate> certificate =
1638 rtc::RTCCertificateGenerator::GenerateCertificate(
1639 rtc::KeyParams(key_type), rtc::Optional<uint64_t>());
1640 if (!certificate) {
1641 LOG(LS_ERROR) << "Failed to generate certificate. KeyType: " << key_type;
1642 return 0;
1643 }
1644 rtc_config.certificates.push_back(certificate);
1645 }
1646
1647 PCOJava* observer = reinterpret_cast<PCOJava*>(observer_p);
1648 observer->SetConstraints(new ConstraintsWrapper(jni, j_constraints));
1649 rtc::scoped_refptr<PeerConnectionInterface> pc(f->CreatePeerConnection(
1650 rtc_config, observer->constraints(), NULL, NULL, observer));
1651 return (jlong)pc.release();
1652 }
1653
1654 static rtc::scoped_refptr<PeerConnectionInterface> ExtractNativePC(
1655 JNIEnv* jni, jobject j_pc) {
1656 jfieldID native_pc_id = GetFieldID(jni,
1657 GetObjectClass(jni, j_pc), "nativePeerConnection", "J");
1658 jlong j_p = GetLongField(jni, j_pc, native_pc_id);
1659 return rtc::scoped_refptr<PeerConnectionInterface>(
1660 reinterpret_cast<PeerConnectionInterface*>(j_p));
1661 }
1662
1663 JOW(jobject, PeerConnection_getLocalDescription)(JNIEnv* jni, jobject j_pc) {
1664 const SessionDescriptionInterface* sdp =
1665 ExtractNativePC(jni, j_pc)->local_description();
1666 return sdp ? JavaSdpFromNativeSdp(jni, sdp) : NULL;
1667 }
1668
1669 JOW(jobject, PeerConnection_getRemoteDescription)(JNIEnv* jni, jobject j_pc) {
1670 const SessionDescriptionInterface* sdp =
1671 ExtractNativePC(jni, j_pc)->remote_description();
1672 return sdp ? JavaSdpFromNativeSdp(jni, sdp) : NULL;
1673 }
1674
1675 JOW(jobject, PeerConnection_createDataChannel)(
1676 JNIEnv* jni, jobject j_pc, jstring j_label, jobject j_init) {
1677 DataChannelInit init = JavaDataChannelInitToNative(jni, j_init);
1678 rtc::scoped_refptr<DataChannelInterface> channel(
1679 ExtractNativePC(jni, j_pc)->CreateDataChannel(
1680 JavaToStdString(jni, j_label), &init));
1681 // Mustn't pass channel.get() directly through NewObject to avoid reading its
1682 // vararg parameter as 64-bit and reading memory that doesn't belong to the
1683 // 32-bit parameter.
1684 jlong nativeChannelPtr = jlongFromPointer(channel.get());
1685 RTC_CHECK(nativeChannelPtr) << "Failed to create DataChannel";
1686 jclass j_data_channel_class = FindClass(jni, "org/webrtc/DataChannel");
1687 jmethodID j_data_channel_ctor = GetMethodID(
1688 jni, j_data_channel_class, "<init>", "(J)V");
1689 jobject j_channel = jni->NewObject(
1690 j_data_channel_class, j_data_channel_ctor, nativeChannelPtr);
1691 CHECK_EXCEPTION(jni) << "error during NewObject";
1692 // Channel is now owned by Java object, and will be freed from there.
1693 int bumped_count = channel->AddRef();
1694 RTC_CHECK(bumped_count == 2) << "Unexpected refcount";
1695 return j_channel;
1696 }
1697
1698 JOW(void, PeerConnection_createOffer)(
1699 JNIEnv* jni, jobject j_pc, jobject j_observer, jobject j_constraints) {
1700 ConstraintsWrapper* constraints =
1701 new ConstraintsWrapper(jni, j_constraints);
1702 rtc::scoped_refptr<CreateSdpObserverWrapper> observer(
1703 new rtc::RefCountedObject<CreateSdpObserverWrapper>(
1704 jni, j_observer, constraints));
1705 ExtractNativePC(jni, j_pc)->CreateOffer(observer, constraints);
1706 }
1707
1708 JOW(void, PeerConnection_createAnswer)(
1709 JNIEnv* jni, jobject j_pc, jobject j_observer, jobject j_constraints) {
1710 ConstraintsWrapper* constraints =
1711 new ConstraintsWrapper(jni, j_constraints);
1712 rtc::scoped_refptr<CreateSdpObserverWrapper> observer(
1713 new rtc::RefCountedObject<CreateSdpObserverWrapper>(
1714 jni, j_observer, constraints));
1715 ExtractNativePC(jni, j_pc)->CreateAnswer(observer, constraints);
1716 }
1717
1718 // Helper to create a SessionDescriptionInterface from a SessionDescription.
1719 static SessionDescriptionInterface* JavaSdpToNativeSdp(
1720 JNIEnv* jni, jobject j_sdp) {
1721 jfieldID j_type_id = GetFieldID(
1722 jni, GetObjectClass(jni, j_sdp), "type",
1723 "Lorg/webrtc/SessionDescription$Type;");
1724 jobject j_type = GetObjectField(jni, j_sdp, j_type_id);
1725 jmethodID j_canonical_form_id = GetMethodID(
1726 jni, GetObjectClass(jni, j_type), "canonicalForm",
1727 "()Ljava/lang/String;");
1728 jstring j_type_string = (jstring)jni->CallObjectMethod(
1729 j_type, j_canonical_form_id);
1730 CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
1731 std::string std_type = JavaToStdString(jni, j_type_string);
1732
1733 jfieldID j_description_id = GetFieldID(
1734 jni, GetObjectClass(jni, j_sdp), "description", "Ljava/lang/String;");
1735 jstring j_description = (jstring)GetObjectField(jni, j_sdp, j_description_id);
1736 std::string std_description = JavaToStdString(jni, j_description);
1737
1738 return webrtc::CreateSessionDescription(
1739 std_type, std_description, NULL);
1740 }
1741
1742 JOW(void, PeerConnection_setLocalDescription)(
1743 JNIEnv* jni, jobject j_pc,
1744 jobject j_observer, jobject j_sdp) {
1745 rtc::scoped_refptr<SetSdpObserverWrapper> observer(
1746 new rtc::RefCountedObject<SetSdpObserverWrapper>(
1747 jni, j_observer, reinterpret_cast<ConstraintsWrapper*>(NULL)));
1748 ExtractNativePC(jni, j_pc)->SetLocalDescription(
1749 observer, JavaSdpToNativeSdp(jni, j_sdp));
1750 }
1751
1752 JOW(void, PeerConnection_setRemoteDescription)(
1753 JNIEnv* jni, jobject j_pc,
1754 jobject j_observer, jobject j_sdp) {
1755 rtc::scoped_refptr<SetSdpObserverWrapper> observer(
1756 new rtc::RefCountedObject<SetSdpObserverWrapper>(
1757 jni, j_observer, reinterpret_cast<ConstraintsWrapper*>(NULL)));
1758 ExtractNativePC(jni, j_pc)->SetRemoteDescription(
1759 observer, JavaSdpToNativeSdp(jni, j_sdp));
1760 }
1761
1762 JOW(jboolean, PeerConnection_setConfiguration)(
1763 JNIEnv* jni, jobject j_pc, jobject j_rtc_config) {
1764 PeerConnectionInterface::RTCConfiguration rtc_config;
1765 JavaRTCConfigurationToJsepRTCConfiguration(jni, j_rtc_config, &rtc_config);
1766 return ExtractNativePC(jni, j_pc)->SetConfiguration(rtc_config);
1767 }
1768
1769 JOW(jboolean, PeerConnection_nativeAddIceCandidate)(
1770 JNIEnv* jni, jobject j_pc, jstring j_sdp_mid,
1771 jint j_sdp_mline_index, jstring j_candidate_sdp) {
1772 std::string sdp_mid = JavaToStdString(jni, j_sdp_mid);
1773 std::string sdp = JavaToStdString(jni, j_candidate_sdp);
1774 std::unique_ptr<IceCandidateInterface> candidate(
1775 webrtc::CreateIceCandidate(sdp_mid, j_sdp_mline_index, sdp, NULL));
1776 return ExtractNativePC(jni, j_pc)->AddIceCandidate(candidate.get());
1777 }
1778
1779 static cricket::Candidate GetCandidateFromJava(JNIEnv* jni,
1780 jobject j_candidate) {
1781 jclass j_candidate_class = GetObjectClass(jni, j_candidate);
1782 jfieldID j_sdp_mid_id =
1783 GetFieldID(jni, j_candidate_class, "sdpMid", "Ljava/lang/String;");
1784 std::string sdp_mid =
1785 JavaToStdString(jni, GetStringField(jni, j_candidate, j_sdp_mid_id));
1786 jfieldID j_sdp_id =
1787 GetFieldID(jni, j_candidate_class, "sdp", "Ljava/lang/String;");
1788 std::string sdp =
1789 JavaToStdString(jni, GetStringField(jni, j_candidate, j_sdp_id));
1790 cricket::Candidate candidate;
1791 if (!webrtc::SdpDeserializeCandidate(sdp_mid, sdp, &candidate, NULL)) {
1792 LOG(LS_ERROR) << "SdpDescrializeCandidate failed with sdp " << sdp;
1793 }
1794 return candidate;
1795 }
1796
1797 JOW(jboolean, PeerConnection_nativeRemoveIceCandidates)
1798 (JNIEnv* jni, jobject j_pc, jobjectArray j_candidates) {
1799 std::vector<cricket::Candidate> candidates;
1800 size_t num_candidates = jni->GetArrayLength(j_candidates);
1801 for (size_t i = 0; i < num_candidates; ++i) {
1802 jobject j_candidate = jni->GetObjectArrayElement(j_candidates, i);
1803 candidates.push_back(GetCandidateFromJava(jni, j_candidate));
1804 }
1805 return ExtractNativePC(jni, j_pc)->RemoveIceCandidates(candidates);
1806 }
1807
1808 JOW(jboolean, PeerConnection_nativeAddLocalStream)(
1809 JNIEnv* jni, jobject j_pc, jlong native_stream) {
1810 return ExtractNativePC(jni, j_pc)->AddStream(
1811 reinterpret_cast<MediaStreamInterface*>(native_stream));
1812 }
1813
1814 JOW(void, PeerConnection_nativeRemoveLocalStream)(
1815 JNIEnv* jni, jobject j_pc, jlong native_stream) {
1816 ExtractNativePC(jni, j_pc)->RemoveStream(
1817 reinterpret_cast<MediaStreamInterface*>(native_stream));
1818 }
1819
1820 JOW(jobject, PeerConnection_nativeCreateSender)(
1821 JNIEnv* jni, jobject j_pc, jstring j_kind, jstring j_stream_id) {
1822 jclass j_rtp_sender_class = FindClass(jni, "org/webrtc/RtpSender");
1823 jmethodID j_rtp_sender_ctor =
1824 GetMethodID(jni, j_rtp_sender_class, "<init>", "(J)V");
1825
1826 std::string kind = JavaToStdString(jni, j_kind);
1827 std::string stream_id = JavaToStdString(jni, j_stream_id);
1828 rtc::scoped_refptr<RtpSenderInterface> sender =
1829 ExtractNativePC(jni, j_pc)->CreateSender(kind, stream_id);
1830 if (!sender.get()) {
1831 return nullptr;
1832 }
1833 jlong nativeSenderPtr = jlongFromPointer(sender.get());
1834 jobject j_sender =
1835 jni->NewObject(j_rtp_sender_class, j_rtp_sender_ctor, nativeSenderPtr);
1836 CHECK_EXCEPTION(jni) << "error during NewObject";
1837 // Sender is now owned by the Java object, and will be freed from
1838 // RtpSender.dispose(), called by PeerConnection.dispose() or getSenders().
1839 sender->AddRef();
1840 return j_sender;
1841 }
1842
1843 JOW(jobject, PeerConnection_nativeGetSenders)(JNIEnv* jni, jobject j_pc) {
1844 jclass j_array_list_class = FindClass(jni, "java/util/ArrayList");
1845 jmethodID j_array_list_ctor =
1846 GetMethodID(jni, j_array_list_class, "<init>", "()V");
1847 jmethodID j_array_list_add =
1848 GetMethodID(jni, j_array_list_class, "add", "(Ljava/lang/Object;)Z");
1849 jobject j_senders = jni->NewObject(j_array_list_class, j_array_list_ctor);
1850 CHECK_EXCEPTION(jni) << "error during NewObject";
1851
1852 jclass j_rtp_sender_class = FindClass(jni, "org/webrtc/RtpSender");
1853 jmethodID j_rtp_sender_ctor =
1854 GetMethodID(jni, j_rtp_sender_class, "<init>", "(J)V");
1855
1856 auto senders = ExtractNativePC(jni, j_pc)->GetSenders();
1857 for (const auto& sender : senders) {
1858 jlong nativeSenderPtr = jlongFromPointer(sender.get());
1859 jobject j_sender =
1860 jni->NewObject(j_rtp_sender_class, j_rtp_sender_ctor, nativeSenderPtr);
1861 CHECK_EXCEPTION(jni) << "error during NewObject";
1862 // Sender is now owned by the Java object, and will be freed from
1863 // RtpSender.dispose(), called by PeerConnection.dispose() or getSenders().
1864 sender->AddRef();
1865 jni->CallBooleanMethod(j_senders, j_array_list_add, j_sender);
1866 CHECK_EXCEPTION(jni) << "error during CallBooleanMethod";
1867 }
1868 return j_senders;
1869 }
1870
1871 JOW(jobject, PeerConnection_nativeGetReceivers)(JNIEnv* jni, jobject j_pc) {
1872 jclass j_array_list_class = FindClass(jni, "java/util/ArrayList");
1873 jmethodID j_array_list_ctor =
1874 GetMethodID(jni, j_array_list_class, "<init>", "()V");
1875 jmethodID j_array_list_add =
1876 GetMethodID(jni, j_array_list_class, "add", "(Ljava/lang/Object;)Z");
1877 jobject j_receivers = jni->NewObject(j_array_list_class, j_array_list_ctor);
1878 CHECK_EXCEPTION(jni) << "error during NewObject";
1879
1880 jclass j_rtp_receiver_class = FindClass(jni, "org/webrtc/RtpReceiver");
1881 jmethodID j_rtp_receiver_ctor =
1882 GetMethodID(jni, j_rtp_receiver_class, "<init>", "(J)V");
1883
1884 auto receivers = ExtractNativePC(jni, j_pc)->GetReceivers();
1885 for (const auto& receiver : receivers) {
1886 jlong nativeReceiverPtr = jlongFromPointer(receiver.get());
1887 jobject j_receiver = jni->NewObject(j_rtp_receiver_class,
1888 j_rtp_receiver_ctor, nativeReceiverPtr);
1889 CHECK_EXCEPTION(jni) << "error during NewObject";
1890 // Receiver is now owned by Java object, and will be freed from there.
1891 receiver->AddRef();
1892 jni->CallBooleanMethod(j_receivers, j_array_list_add, j_receiver);
1893 CHECK_EXCEPTION(jni) << "error during CallBooleanMethod";
1894 }
1895 return j_receivers;
1896 }
1897
1898 JOW(bool, PeerConnection_nativeGetStats)(
1899 JNIEnv* jni, jobject j_pc, jobject j_observer, jlong native_track) {
1900 rtc::scoped_refptr<StatsObserverWrapper> observer(
1901 new rtc::RefCountedObject<StatsObserverWrapper>(jni, j_observer));
1902 return ExtractNativePC(jni, j_pc)->GetStats(
1903 observer,
1904 reinterpret_cast<MediaStreamTrackInterface*>(native_track),
1905 PeerConnectionInterface::kStatsOutputLevelStandard);
1906 }
1907
1908 JOW(jobject, PeerConnection_signalingState)(JNIEnv* jni, jobject j_pc) {
1909 PeerConnectionInterface::SignalingState state =
1910 ExtractNativePC(jni, j_pc)->signaling_state();
1911 return JavaEnumFromIndex(jni, "PeerConnection$SignalingState", state);
1912 }
1913
1914 JOW(jobject, PeerConnection_iceConnectionState)(JNIEnv* jni, jobject j_pc) {
1915 PeerConnectionInterface::IceConnectionState state =
1916 ExtractNativePC(jni, j_pc)->ice_connection_state();
1917 return JavaEnumFromIndex(jni, "PeerConnection$IceConnectionState", state);
1918 }
1919
1920 JOW(jobject, PeerConnection_iceGatheringState)(JNIEnv* jni, jobject j_pc) {
1921 PeerConnectionInterface::IceGatheringState state =
1922 ExtractNativePC(jni, j_pc)->ice_gathering_state();
1923 return JavaEnumFromIndex(jni, "PeerConnection$IceGatheringState", state);
1924 }
1925
1926 JOW(void, PeerConnection_close)(JNIEnv* jni, jobject j_pc) {
1927 ExtractNativePC(jni, j_pc)->Close();
1928 return;
1929 }
1930
1931 JOW(jobject, MediaSource_nativeState)(JNIEnv* jni, jclass, jlong j_p) {
1932 rtc::scoped_refptr<MediaSourceInterface> p(
1933 reinterpret_cast<MediaSourceInterface*>(j_p));
1934 return JavaEnumFromIndex(jni, "MediaSource$State", p->state());
1935 }
1936
1937 JOW(jlong, VideoRenderer_nativeWrapVideoRenderer)(
1938 JNIEnv* jni, jclass, jobject j_callbacks) {
1939 std::unique_ptr<JavaVideoRendererWrapper> renderer(
1940 new JavaVideoRendererWrapper(jni, j_callbacks));
1941 return (jlong)renderer.release();
1942 }
1943
1944 JOW(void, VideoRenderer_nativeCopyPlane)(
1945 JNIEnv *jni, jclass, jobject j_src_buffer, jint width, jint height,
1946 jint src_stride, jobject j_dst_buffer, jint dst_stride) {
1947 size_t src_size = jni->GetDirectBufferCapacity(j_src_buffer);
1948 size_t dst_size = jni->GetDirectBufferCapacity(j_dst_buffer);
1949 RTC_CHECK(src_stride >= width) << "Wrong source stride " << src_stride;
1950 RTC_CHECK(dst_stride >= width) << "Wrong destination stride " << dst_stride;
1951 RTC_CHECK(src_size >= src_stride * height)
1952 << "Insufficient source buffer capacity " << src_size;
1953 RTC_CHECK(dst_size >= dst_stride * height)
1954 << "Insufficient destination buffer capacity " << dst_size;
1955 uint8_t *src =
1956 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_src_buffer));
1957 uint8_t *dst =
1958 reinterpret_cast<uint8_t*>(jni->GetDirectBufferAddress(j_dst_buffer));
1959 if (src_stride == dst_stride) {
1960 memcpy(dst, src, src_stride * height);
1961 } else {
1962 for (int i = 0; i < height; i++) {
1963 memcpy(dst, src, width);
1964 src += src_stride;
1965 dst += dst_stride;
1966 }
1967 }
1968 }
1969
1970 JOW(void, VideoSource_stop)(JNIEnv* jni, jclass, jlong j_p) {
1971 reinterpret_cast<VideoTrackSourceInterface*>(j_p)->Stop();
1972 }
1973
1974 JOW(void, VideoSource_restart)(
1975 JNIEnv* jni, jclass, jlong j_p_source, jlong j_p_format) {
1976 reinterpret_cast<VideoTrackSourceInterface*>(j_p_source)->Restart();
1977 }
1978
1979 JOW(jstring, MediaStreamTrack_nativeId)(JNIEnv* jni, jclass, jlong j_p) {
1980 return JavaStringFromStdString(
1981 jni, reinterpret_cast<MediaStreamTrackInterface*>(j_p)->id());
1982 }
1983
1984 JOW(jstring, MediaStreamTrack_nativeKind)(JNIEnv* jni, jclass, jlong j_p) {
1985 return JavaStringFromStdString(
1986 jni, reinterpret_cast<MediaStreamTrackInterface*>(j_p)->kind());
1987 }
1988
1989 JOW(jboolean, MediaStreamTrack_nativeEnabled)(JNIEnv* jni, jclass, jlong j_p) {
1990 return reinterpret_cast<MediaStreamTrackInterface*>(j_p)->enabled();
1991 }
1992
1993 JOW(jobject, MediaStreamTrack_nativeState)(JNIEnv* jni, jclass, jlong j_p) {
1994 return JavaEnumFromIndex(
1995 jni,
1996 "MediaStreamTrack$State",
1997 reinterpret_cast<MediaStreamTrackInterface*>(j_p)->state());
1998 }
1999
2000 JOW(jboolean, MediaStreamTrack_nativeSetEnabled)(
2001 JNIEnv* jni, jclass, jlong j_p, jboolean enabled) {
2002 return reinterpret_cast<MediaStreamTrackInterface*>(j_p)
2003 ->set_enabled(enabled);
2004 }
2005
2006 JOW(void, VideoTrack_nativeAddRenderer)(
2007 JNIEnv* jni, jclass,
2008 jlong j_video_track_pointer, jlong j_renderer_pointer) {
2009 reinterpret_cast<VideoTrackInterface*>(j_video_track_pointer)
2010 ->AddOrUpdateSink(
2011 reinterpret_cast<rtc::VideoSinkInterface<cricket::VideoFrame>*>(
2012 j_renderer_pointer),
2013 rtc::VideoSinkWants());
2014 }
2015
2016 JOW(void, VideoTrack_nativeRemoveRenderer)(
2017 JNIEnv* jni, jclass,
2018 jlong j_video_track_pointer, jlong j_renderer_pointer) {
2019 reinterpret_cast<VideoTrackInterface*>(j_video_track_pointer)
2020 ->RemoveSink(
2021 reinterpret_cast<rtc::VideoSinkInterface<cricket::VideoFrame>*>(
2022 j_renderer_pointer));
2023 }
2024
2025 JOW(jlong, CallSessionFileRotatingLogSink_nativeAddSink)(
2026 JNIEnv* jni, jclass,
2027 jstring j_dirPath, jint j_maxFileSize, jint j_severity) {
2028 std::string dir_path = JavaToStdString(jni, j_dirPath);
2029 rtc::CallSessionFileRotatingLogSink* sink =
2030 new rtc::CallSessionFileRotatingLogSink(dir_path, j_maxFileSize);
2031 if (!sink->Init()) {
2032 LOG_V(rtc::LoggingSeverity::LS_WARNING) <<
2033 "Failed to init CallSessionFileRotatingLogSink for path " << dir_path;
2034 delete sink;
2035 return 0;
2036 }
2037 rtc::LogMessage::AddLogToStream(
2038 sink, static_cast<rtc::LoggingSeverity>(j_severity));
2039 return (jlong) sink;
2040 }
2041
2042 JOW(void, CallSessionFileRotatingLogSink_nativeDeleteSink)(
2043 JNIEnv* jni, jclass, jlong j_sink) {
2044 rtc::CallSessionFileRotatingLogSink* sink =
2045 reinterpret_cast<rtc::CallSessionFileRotatingLogSink*>(j_sink);
2046 rtc::LogMessage::RemoveLogToStream(sink);
2047 delete sink;
2048 }
2049
2050 JOW(jbyteArray, CallSessionFileRotatingLogSink_nativeGetLogData)(
2051 JNIEnv* jni, jclass, jstring j_dirPath) {
2052 std::string dir_path = JavaToStdString(jni, j_dirPath);
2053 std::unique_ptr<rtc::CallSessionFileRotatingStream> stream(
2054 new rtc::CallSessionFileRotatingStream(dir_path));
2055 if (!stream->Open()) {
2056 LOG_V(rtc::LoggingSeverity::LS_WARNING) <<
2057 "Failed to open CallSessionFileRotatingStream for path " << dir_path;
2058 return jni->NewByteArray(0);
2059 }
2060 size_t log_size = 0;
2061 if (!stream->GetSize(&log_size) || log_size == 0) {
2062 LOG_V(rtc::LoggingSeverity::LS_WARNING) <<
2063 "CallSessionFileRotatingStream returns 0 size for path " << dir_path;
2064 return jni->NewByteArray(0);
2065 }
2066
2067 size_t read = 0;
2068 std::unique_ptr<jbyte> buffer(static_cast<jbyte*>(malloc(log_size)));
2069 stream->ReadAll(buffer.get(), log_size, &read, nullptr);
2070
2071 jbyteArray result = jni->NewByteArray(read);
2072 jni->SetByteArrayRegion(result, 0, read, buffer.get());
2073
2074 return result;
2075 }
2076
2077 JOW(jboolean, RtpSender_nativeSetTrack)(JNIEnv* jni,
2078 jclass,
2079 jlong j_rtp_sender_pointer,
2080 jlong j_track_pointer) {
2081 return reinterpret_cast<RtpSenderInterface*>(j_rtp_sender_pointer)
2082 ->SetTrack(reinterpret_cast<MediaStreamTrackInterface*>(j_track_pointer));
2083 }
2084
2085 JOW(jlong, RtpSender_nativeGetTrack)(JNIEnv* jni,
2086 jclass,
2087 jlong j_rtp_sender_pointer,
2088 jlong j_track_pointer) {
2089 return jlongFromPointer(
2090 reinterpret_cast<RtpSenderInterface*>(j_rtp_sender_pointer)
2091 ->track()
2092 .release());
2093 }
2094
2095 static void JavaRtpParametersToJsepRtpParameters(
2096 JNIEnv* jni,
2097 jobject j_parameters,
2098 webrtc::RtpParameters* parameters) {
2099 RTC_CHECK(parameters != nullptr);
2100 jclass parameters_class = jni->FindClass("org/webrtc/RtpParameters");
2101 jfieldID encodings_id =
2102 GetFieldID(jni, parameters_class, "encodings", "Ljava/util/LinkedList;");
2103 jfieldID codecs_id =
2104 GetFieldID(jni, parameters_class, "codecs", "Ljava/util/LinkedList;");
2105
2106 // Convert encodings.
2107 jobject j_encodings = GetObjectField(jni, j_parameters, encodings_id);
2108 const int kBitrateUnlimited = -1;
2109 jclass j_encoding_parameters_class =
2110 jni->FindClass("org/webrtc/RtpParameters$Encoding");
2111 jfieldID active_id =
2112 GetFieldID(jni, j_encoding_parameters_class, "active", "Z");
2113 jfieldID bitrate_id = GetFieldID(jni, j_encoding_parameters_class,
2114 "maxBitrateBps", "Ljava/lang/Integer;");
2115 jclass j_integer_class = jni->FindClass("java/lang/Integer");
2116 jmethodID int_value_id = GetMethodID(jni, j_integer_class, "intValue", "()I");
2117
2118 for (jobject j_encoding_parameters : Iterable(jni, j_encodings)) {
2119 webrtc::RtpEncodingParameters encoding;
2120 encoding.active = GetBooleanField(jni, j_encoding_parameters, active_id);
2121 jobject j_bitrate =
2122 GetNullableObjectField(jni, j_encoding_parameters, bitrate_id);
2123 if (!IsNull(jni, j_bitrate)) {
2124 int bitrate_value = jni->CallIntMethod(j_bitrate, int_value_id);
2125 CHECK_EXCEPTION(jni) << "error during CallIntMethod";
2126 encoding.max_bitrate_bps = bitrate_value;
2127 } else {
2128 encoding.max_bitrate_bps = kBitrateUnlimited;
2129 }
2130 parameters->encodings.push_back(encoding);
2131 }
2132
2133 // Convert codecs.
2134 jobject j_codecs = GetObjectField(jni, j_parameters, codecs_id);
2135 jclass codec_class = jni->FindClass("org/webrtc/RtpParameters$Codec");
2136 jfieldID payload_type_id = GetFieldID(jni, codec_class, "payloadType", "I");
2137 jfieldID mime_type_id =
2138 GetFieldID(jni, codec_class, "mimeType", "Ljava/lang/String;");
2139 jfieldID clock_rate_id = GetFieldID(jni, codec_class, "clockRate", "I");
2140 jfieldID channels_id = GetFieldID(jni, codec_class, "channels", "I");
2141
2142 for (jobject j_codec : Iterable(jni, j_codecs)) {
2143 webrtc::RtpCodecParameters codec;
2144 codec.payload_type = GetIntField(jni, j_codec, payload_type_id);
2145 codec.mime_type =
2146 JavaToStdString(jni, GetStringField(jni, j_codec, mime_type_id));
2147 codec.clock_rate = GetIntField(jni, j_codec, clock_rate_id);
2148 codec.channels = GetIntField(jni, j_codec, channels_id);
2149 parameters->codecs.push_back(codec);
2150 }
2151 }
2152
2153 static jobject JsepRtpParametersToJavaRtpParameters(
2154 JNIEnv* jni,
2155 const webrtc::RtpParameters& parameters) {
2156 jclass parameters_class = jni->FindClass("org/webrtc/RtpParameters");
2157 jmethodID parameters_ctor =
2158 GetMethodID(jni, parameters_class, "<init>", "()V");
2159 jobject j_parameters = jni->NewObject(parameters_class, parameters_ctor);
2160 CHECK_EXCEPTION(jni) << "error during NewObject";
2161
2162 // Add encodings.
2163 jclass encoding_class = jni->FindClass("org/webrtc/RtpParameters$Encoding");
2164 jmethodID encoding_ctor = GetMethodID(jni, encoding_class, "<init>", "()V");
2165 jfieldID encodings_id =
2166 GetFieldID(jni, parameters_class, "encodings", "Ljava/util/LinkedList;");
2167 jobject j_encodings = GetObjectField(jni, j_parameters, encodings_id);
2168 jmethodID encodings_add = GetMethodID(jni, GetObjectClass(jni, j_encodings),
2169 "add", "(Ljava/lang/Object;)Z");
2170 jfieldID active_id =
2171 GetFieldID(jni, encoding_class, "active", "Z");
2172 jfieldID bitrate_id =
2173 GetFieldID(jni, encoding_class, "maxBitrateBps", "Ljava/lang/Integer;");
2174
2175 jclass integer_class = jni->FindClass("java/lang/Integer");
2176 jmethodID integer_ctor = GetMethodID(jni, integer_class, "<init>", "(I)V");
2177
2178 for (const webrtc::RtpEncodingParameters& encoding : parameters.encodings) {
2179 jobject j_encoding_parameters =
2180 jni->NewObject(encoding_class, encoding_ctor);
2181 CHECK_EXCEPTION(jni) << "error during NewObject";
2182 jni->SetBooleanField(j_encoding_parameters, active_id, encoding.active);
2183 CHECK_EXCEPTION(jni) << "error during SetBooleanField";
2184 if (encoding.max_bitrate_bps > 0) {
2185 jobject j_bitrate_value =
2186 jni->NewObject(integer_class, integer_ctor, encoding.max_bitrate_bps);
2187 CHECK_EXCEPTION(jni) << "error during NewObject";
2188 jni->SetObjectField(j_encoding_parameters, bitrate_id, j_bitrate_value);
2189 CHECK_EXCEPTION(jni) << "error during SetObjectField";
2190 }
2191 jboolean added = jni->CallBooleanMethod(j_encodings, encodings_add,
2192 j_encoding_parameters);
2193 CHECK_EXCEPTION(jni) << "error during CallBooleanMethod";
2194 RTC_CHECK(added);
2195 }
2196
2197 // Add codecs.
2198 jclass codec_class = jni->FindClass("org/webrtc/RtpParameters$Codec");
2199 jmethodID codec_ctor = GetMethodID(jni, codec_class, "<init>", "()V");
2200 jfieldID codecs_id =
2201 GetFieldID(jni, parameters_class, "codecs", "Ljava/util/LinkedList;");
2202 jobject j_codecs = GetObjectField(jni, j_parameters, codecs_id);
2203 jmethodID codecs_add = GetMethodID(jni, GetObjectClass(jni, j_codecs),
2204 "add", "(Ljava/lang/Object;)Z");
2205 jfieldID payload_type_id = GetFieldID(jni, codec_class, "payloadType", "I");
2206 jfieldID mime_type_id =
2207 GetFieldID(jni, codec_class, "mimeType", "Ljava/lang/String;");
2208 jfieldID clock_rate_id = GetFieldID(jni, codec_class, "clockRate", "I");
2209 jfieldID channels_id = GetFieldID(jni, codec_class, "channels", "I");
2210
2211 for (const webrtc::RtpCodecParameters& codec : parameters.codecs) {
2212 jobject j_codec = jni->NewObject(codec_class, codec_ctor);
2213 CHECK_EXCEPTION(jni) << "error during NewObject";
2214 jni->SetIntField(j_codec, payload_type_id, codec.payload_type);
2215 CHECK_EXCEPTION(jni) << "error during SetIntField";
2216 jni->SetObjectField(j_codec, mime_type_id,
2217 JavaStringFromStdString(jni, codec.mime_type));
2218 CHECK_EXCEPTION(jni) << "error during SetObjectField";
2219 jni->SetIntField(j_codec, clock_rate_id, codec.clock_rate);
2220 CHECK_EXCEPTION(jni) << "error during SetIntField";
2221 jni->SetIntField(j_codec, channels_id, codec.channels);
2222 CHECK_EXCEPTION(jni) << "error during SetIntField";
2223 jboolean added = jni->CallBooleanMethod(j_codecs, codecs_add, j_codec);
2224 CHECK_EXCEPTION(jni) << "error during CallBooleanMethod";
2225 RTC_CHECK(added);
2226 }
2227
2228 return j_parameters;
2229 }
2230
2231 JOW(jboolean, RtpSender_nativeSetParameters)
2232 (JNIEnv* jni, jclass, jlong j_rtp_sender_pointer, jobject j_parameters) {
2233 if (IsNull(jni, j_parameters)) {
2234 return false;
2235 }
2236 webrtc::RtpParameters parameters;
2237 JavaRtpParametersToJsepRtpParameters(jni, j_parameters, &parameters);
2238 return reinterpret_cast<RtpSenderInterface*>(j_rtp_sender_pointer)
2239 ->SetParameters(parameters);
2240 }
2241
2242 JOW(jobject, RtpSender_nativeGetParameters)
2243 (JNIEnv* jni, jclass, jlong j_rtp_sender_pointer) {
2244 webrtc::RtpParameters parameters =
2245 reinterpret_cast<RtpSenderInterface*>(j_rtp_sender_pointer)
2246 ->GetParameters();
2247 return JsepRtpParametersToJavaRtpParameters(jni, parameters);
2248 }
2249
2250 JOW(jstring, RtpSender_nativeId)(
2251 JNIEnv* jni, jclass, jlong j_rtp_sender_pointer) {
2252 return JavaStringFromStdString(
2253 jni, reinterpret_cast<RtpSenderInterface*>(j_rtp_sender_pointer)->id());
2254 }
2255
2256 JOW(void, RtpSender_free)(JNIEnv* jni, jclass, jlong j_rtp_sender_pointer) {
2257 reinterpret_cast<RtpSenderInterface*>(j_rtp_sender_pointer)->Release();
2258 }
2259
2260 JOW(jlong, RtpReceiver_nativeGetTrack)(JNIEnv* jni,
2261 jclass,
2262 jlong j_rtp_receiver_pointer,
2263 jlong j_track_pointer) {
2264 return jlongFromPointer(
2265 reinterpret_cast<RtpReceiverInterface*>(j_rtp_receiver_pointer)
2266 ->track()
2267 .release());
2268 }
2269
2270 JOW(jboolean, RtpReceiver_nativeSetParameters)
2271 (JNIEnv* jni, jclass, jlong j_rtp_sender_pointer, jobject j_parameters) {
2272 if (IsNull(jni, j_parameters)) {
2273 return false;
2274 }
2275 webrtc::RtpParameters parameters;
2276 JavaRtpParametersToJsepRtpParameters(jni, j_parameters, &parameters);
2277 return reinterpret_cast<RtpReceiverInterface*>(j_rtp_sender_pointer)
2278 ->SetParameters(parameters);
2279 }
2280
2281 JOW(jobject, RtpReceiver_nativeGetParameters)
2282 (JNIEnv* jni, jclass, jlong j_rtp_sender_pointer) {
2283 webrtc::RtpParameters parameters =
2284 reinterpret_cast<RtpReceiverInterface*>(j_rtp_sender_pointer)
2285 ->GetParameters();
2286 return JsepRtpParametersToJavaRtpParameters(jni, parameters);
2287 }
2288
2289 JOW(jstring, RtpReceiver_nativeId)(
2290 JNIEnv* jni, jclass, jlong j_rtp_receiver_pointer) {
2291 return JavaStringFromStdString(
2292 jni,
2293 reinterpret_cast<RtpReceiverInterface*>(j_rtp_receiver_pointer)->id());
2294 }
2295
2296 JOW(void, RtpReceiver_free)(JNIEnv* jni, jclass, jlong j_rtp_receiver_pointer) {
2297 reinterpret_cast<RtpReceiverInterface*>(j_rtp_receiver_pointer)->Release();
2298 }
2299
2300 } // namespace webrtc_jni
OLDNEW
« no previous file with comments | « webrtc/api/android/jni/native_handle_impl.cc ('k') | webrtc/api/android/jni/surfacetexturehelper_jni.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698