blob: 128ca76881a129e384fa568f9622e65466fc6e4f [file] [log] [blame]
gyzhouad7cad82017-05-11 16:10:03 -07001/*
2 * Copyright (c) 2017 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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "examples/unityplugin/simple_peer_connection.h"
gyzhouad7cad82017-05-11 16:10:03 -070012
13#include <utility>
14
Karl Wiberg918f50c2018-07-05 11:40:33 +020015#include "absl/memory/memory.h"
Qiang Chen51e20462017-12-05 11:11:21 -080016#include "api/audio_codecs/builtin_audio_decoder_factory.h"
17#include "api/audio_codecs/builtin_audio_encoder_factory.h"
Mirko Bonadei2ff3f492018-11-22 09:00:13 +010018#include "api/create_peerconnection_factory.h"
Steve Anton10542f22019-01-11 09:11:00 -080019#include "media/engine/internal_decoder_factory.h"
20#include "media/engine/internal_encoder_factory.h"
21#include "media/engine/multiplex_codec_factory.h"
Qiang Chen43fb9122017-12-20 10:47:36 -080022#include "modules/audio_device/include/audio_device.h"
23#include "modules/audio_processing/include/audio_processing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "modules/video_capture/video_capture_factory.h"
Steve Anton10542f22019-01-11 09:11:00 -080025#include "pc/video_track_source.h"
Niels Möller0a595352019-01-02 15:12:38 +010026#include "test/vcm_capturer.h"
gyzhouad7cad82017-05-11 16:10:03 -070027
qiangchen42f96d52017-08-08 17:08:03 -070028#if defined(WEBRTC_ANDROID)
Steve Anton10542f22019-01-11 09:11:00 -080029#include "examples/unityplugin/class_reference_holder.h"
George Zhou2770c3d2018-03-07 09:58:54 -080030#include "modules/utility/include/helpers_android.h"
Steve Anton10542f22019-01-11 09:11:00 -080031#include "sdk/android/src/jni/android_video_track_source.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "sdk/android/src/jni/jni_helpers.h"
qiangchen42f96d52017-08-08 17:08:03 -070033#endif
34
Seth Hampson513449e2018-03-06 09:35:56 -080035// Names used for media stream ids.
gyzhouad7cad82017-05-11 16:10:03 -070036const char kAudioLabel[] = "audio_label";
37const char kVideoLabel[] = "video_label";
Seth Hampson513449e2018-03-06 09:35:56 -080038const char kStreamId[] = "stream_id";
gyzhouad7cad82017-05-11 16:10:03 -070039
40namespace {
41static int g_peer_count = 0;
42static std::unique_ptr<rtc::Thread> g_worker_thread;
43static std::unique_ptr<rtc::Thread> g_signaling_thread;
44static rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
45 g_peer_connection_factory;
qiangchen42f96d52017-08-08 17:08:03 -070046#if defined(WEBRTC_ANDROID)
47// Android case: the video track does not own the capturer, and it
48// relies on the app to dispose the capturer when the peerconnection
49// shuts down.
50static jobject g_camera = nullptr;
Niels Möller0a595352019-01-02 15:12:38 +010051#else
52class CapturerTrackSource : public webrtc::VideoTrackSource {
53 public:
54 static rtc::scoped_refptr<CapturerTrackSource> Create() {
55 const size_t kWidth = 640;
56 const size_t kHeight = 480;
57 const size_t kFps = 30;
58 const size_t kDeviceIndex = 0;
59 std::unique_ptr<webrtc::test::VcmCapturer> capturer = absl::WrapUnique(
60 webrtc::test::VcmCapturer::Create(kWidth, kHeight, kFps, kDeviceIndex));
61 if (!capturer) {
62 return nullptr;
63 }
64 return new rtc::RefCountedObject<CapturerTrackSource>(std::move(capturer));
65 }
66
67 protected:
68 explicit CapturerTrackSource(
69 std::unique_ptr<webrtc::test::VcmCapturer> capturer)
70 : VideoTrackSource(/*remote=*/false), capturer_(std::move(capturer)) {}
71
72 private:
73 rtc::VideoSourceInterface<webrtc::VideoFrame>* source() override {
74 return capturer_.get();
75 }
76 std::unique_ptr<webrtc::test::VcmCapturer> capturer_;
77};
78
qiangchen42f96d52017-08-08 17:08:03 -070079#endif
gyzhouad7cad82017-05-11 16:10:03 -070080
81std::string GetEnvVarOrDefault(const char* env_var_name,
82 const char* default_value) {
83 std::string value;
84 const char* env_var = getenv(env_var_name);
85 if (env_var)
86 value = env_var;
87
88 if (value.empty())
89 value = default_value;
90
91 return value;
92}
93
94std::string GetPeerConnectionString() {
95 return GetEnvVarOrDefault("WEBRTC_CONNECT", "stun:stun.l.google.com:19302");
96}
97
98class DummySetSessionDescriptionObserver
99 : public webrtc::SetSessionDescriptionObserver {
100 public:
101 static DummySetSessionDescriptionObserver* Create() {
102 return new rtc::RefCountedObject<DummySetSessionDescriptionObserver>();
103 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100104 virtual void OnSuccess() { RTC_LOG(INFO) << __FUNCTION__; }
Harald Alvestrand73771a82018-05-24 10:53:49 +0200105 virtual void OnFailure(webrtc::RTCError error) {
106 RTC_LOG(INFO) << __FUNCTION__ << " " << ToString(error.type()) << ": "
107 << error.message();
gyzhouad7cad82017-05-11 16:10:03 -0700108 }
109
110 protected:
111 DummySetSessionDescriptionObserver() {}
112 ~DummySetSessionDescriptionObserver() {}
113};
114
115} // namespace
116
gyzhoub38f3862017-07-25 16:04:31 -0700117bool SimplePeerConnection::InitializePeerConnection(const char** turn_urls,
118 const int no_of_urls,
119 const char* username,
120 const char* credential,
121 bool is_receiver) {
gyzhouad7cad82017-05-11 16:10:03 -0700122 RTC_DCHECK(peer_connection_.get() == nullptr);
123
124 if (g_peer_connection_factory == nullptr) {
Niels Möller5a96a0e2019-04-30 11:45:58 +0200125 g_worker_thread = rtc::Thread::Create();
gyzhouad7cad82017-05-11 16:10:03 -0700126 g_worker_thread->Start();
Niels Möller5a96a0e2019-04-30 11:45:58 +0200127 g_signaling_thread = rtc::Thread::Create();
gyzhouad7cad82017-05-11 16:10:03 -0700128 g_signaling_thread->Start();
129
130 g_peer_connection_factory = webrtc::CreatePeerConnectionFactory(
131 g_worker_thread.get(), g_worker_thread.get(), g_signaling_thread.get(),
Qiang Chen51e20462017-12-05 11:11:21 -0800132 nullptr, webrtc::CreateBuiltinAudioEncoderFactory(),
Qiang Chen43fb9122017-12-20 10:47:36 -0800133 webrtc::CreateBuiltinAudioDecoderFactory(),
134 std::unique_ptr<webrtc::VideoEncoderFactory>(
Anders Carlssondd8c1652018-01-30 10:32:13 +0100135 new webrtc::MultiplexEncoderFactory(
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200136 std::make_unique<webrtc::InternalEncoderFactory>())),
Qiang Chen43fb9122017-12-20 10:47:36 -0800137 std::unique_ptr<webrtc::VideoDecoderFactory>(
Anders Carlssondd8c1652018-01-30 10:32:13 +0100138 new webrtc::MultiplexDecoderFactory(
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200139 std::make_unique<webrtc::InternalDecoderFactory>())),
Qiang Chen43fb9122017-12-20 10:47:36 -0800140 nullptr, nullptr);
gyzhouad7cad82017-05-11 16:10:03 -0700141 }
142 if (!g_peer_connection_factory.get()) {
143 DeletePeerConnection();
144 return false;
145 }
146
147 g_peer_count++;
Qiang Chen51e20462017-12-05 11:11:21 -0800148 if (!CreatePeerConnection(turn_urls, no_of_urls, username, credential)) {
gyzhouad7cad82017-05-11 16:10:03 -0700149 DeletePeerConnection();
150 return false;
151 }
Qiang Chen51e20462017-12-05 11:11:21 -0800152
153 mandatory_receive_ = is_receiver;
gyzhouad7cad82017-05-11 16:10:03 -0700154 return peer_connection_.get() != nullptr;
155}
156
gyzhoub38f3862017-07-25 16:04:31 -0700157bool SimplePeerConnection::CreatePeerConnection(const char** turn_urls,
158 const int no_of_urls,
159 const char* username,
Qiang Chen51e20462017-12-05 11:11:21 -0800160 const char* credential) {
gyzhouad7cad82017-05-11 16:10:03 -0700161 RTC_DCHECK(g_peer_connection_factory.get() != nullptr);
162 RTC_DCHECK(peer_connection_.get() == nullptr);
163
gyzhoub38f3862017-07-25 16:04:31 -0700164 local_video_observer_.reset(new VideoObserver());
165 remote_video_observer_.reset(new VideoObserver());
166
167 // Add the turn server.
168 if (turn_urls != nullptr) {
169 if (no_of_urls > 0) {
170 webrtc::PeerConnectionInterface::IceServer turn_server;
171 for (int i = 0; i < no_of_urls; i++) {
172 std::string url(turn_urls[i]);
173 if (url.length() > 0)
174 turn_server.urls.push_back(turn_urls[i]);
175 }
176
177 std::string user_name(username);
178 if (user_name.length() > 0)
179 turn_server.username = username;
180
181 std::string password(credential);
182 if (password.length() > 0)
183 turn_server.password = credential;
184
185 config_.servers.push_back(turn_server);
186 }
187 }
188
189 // Add the stun server.
190 webrtc::PeerConnectionInterface::IceServer stun_server;
191 stun_server.uri = GetPeerConnectionString();
192 config_.servers.push_back(stun_server);
Niels Möllerf06f9232018-08-07 12:32:18 +0200193 config_.enable_dtls_srtp = false;
gyzhouad7cad82017-05-11 16:10:03 -0700194
Harald Alvestrandf33f7a22021-05-09 14:58:57 +0000195 auto result = g_peer_connection_factory->CreatePeerConnectionOrError(
196 config_, webrtc::PeerConnectionDependencies(this));
197 if (!result.ok()) {
198 peer_connection_ = nullptr;
199 return false;
200 }
201 peer_connection_ = result.MoveValue();
202 return true;
gyzhouad7cad82017-05-11 16:10:03 -0700203}
204
205void SimplePeerConnection::DeletePeerConnection() {
206 g_peer_count--;
207
qiangchen42f96d52017-08-08 17:08:03 -0700208#if defined(WEBRTC_ANDROID)
209 if (g_camera) {
magjeda3d4f682017-08-28 16:24:06 -0700210 JNIEnv* env = webrtc::jni::GetEnv();
qiangchen42f96d52017-08-08 17:08:03 -0700211 jclass pc_factory_class =
212 unity_plugin::FindClass(env, "org/webrtc/UnityUtility");
George Zhou2770c3d2018-03-07 09:58:54 -0800213 jmethodID stop_camera_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700214 env, pc_factory_class, "StopCamera", "(Lorg/webrtc/VideoCapturer;)V");
215
216 env->CallStaticVoidMethod(pc_factory_class, stop_camera_method, g_camera);
217 CHECK_EXCEPTION(env);
218
219 g_camera = nullptr;
220 }
221#endif
222
gyzhouad7cad82017-05-11 16:10:03 -0700223 CloseDataChannel();
224 peer_connection_ = nullptr;
225 active_streams_.clear();
226
227 if (g_peer_count == 0) {
228 g_peer_connection_factory = nullptr;
229 g_signaling_thread.reset();
230 g_worker_thread.reset();
231 }
232}
233
234bool SimplePeerConnection::CreateOffer() {
235 if (!peer_connection_.get())
236 return false;
237
Niels Möllerf06f9232018-08-07 12:32:18 +0200238 webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
Qiang Chen51e20462017-12-05 11:11:21 -0800239 if (mandatory_receive_) {
Niels Möllerf06f9232018-08-07 12:32:18 +0200240 options.offer_to_receive_audio = true;
241 options.offer_to_receive_video = true;
Qiang Chen51e20462017-12-05 11:11:21 -0800242 }
Niels Möllerf06f9232018-08-07 12:32:18 +0200243 peer_connection_->CreateOffer(this, options);
gyzhouad7cad82017-05-11 16:10:03 -0700244 return true;
245}
246
247bool SimplePeerConnection::CreateAnswer() {
248 if (!peer_connection_.get())
249 return false;
250
Niels Möllerf06f9232018-08-07 12:32:18 +0200251 webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
Qiang Chen51e20462017-12-05 11:11:21 -0800252 if (mandatory_receive_) {
Niels Möllerf06f9232018-08-07 12:32:18 +0200253 options.offer_to_receive_audio = true;
254 options.offer_to_receive_video = true;
Qiang Chen51e20462017-12-05 11:11:21 -0800255 }
Niels Möllerf06f9232018-08-07 12:32:18 +0200256 peer_connection_->CreateAnswer(this, options);
gyzhouad7cad82017-05-11 16:10:03 -0700257 return true;
258}
259
260void SimplePeerConnection::OnSuccess(
261 webrtc::SessionDescriptionInterface* desc) {
262 peer_connection_->SetLocalDescription(
263 DummySetSessionDescriptionObserver::Create(), desc);
264
265 std::string sdp;
266 desc->ToString(&sdp);
267
gyzhouad7cad82017-05-11 16:10:03 -0700268 if (OnLocalSdpReady)
gyzhoub38f3862017-07-25 16:04:31 -0700269 OnLocalSdpReady(desc->type().c_str(), sdp.c_str());
gyzhouad7cad82017-05-11 16:10:03 -0700270}
271
Harald Alvestrand73771a82018-05-24 10:53:49 +0200272void SimplePeerConnection::OnFailure(webrtc::RTCError error) {
273 RTC_LOG(LERROR) << ToString(error.type()) << ": " << error.message();
gyzhouad7cad82017-05-11 16:10:03 -0700274
Harald Alvestrand73771a82018-05-24 10:53:49 +0200275 // TODO(hta): include error.type in the message
gyzhouad7cad82017-05-11 16:10:03 -0700276 if (OnFailureMessage)
Harald Alvestrand73771a82018-05-24 10:53:49 +0200277 OnFailureMessage(error.message());
gyzhouad7cad82017-05-11 16:10:03 -0700278}
279
280void SimplePeerConnection::OnIceCandidate(
281 const webrtc::IceCandidateInterface* candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100282 RTC_LOG(INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index();
gyzhouad7cad82017-05-11 16:10:03 -0700283
gyzhouad7cad82017-05-11 16:10:03 -0700284 std::string sdp;
285 if (!candidate->ToString(&sdp)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100286 RTC_LOG(LS_ERROR) << "Failed to serialize candidate";
gyzhouad7cad82017-05-11 16:10:03 -0700287 return;
288 }
gyzhouad7cad82017-05-11 16:10:03 -0700289
290 if (OnIceCandiateReady)
gyzhoub38f3862017-07-25 16:04:31 -0700291 OnIceCandiateReady(sdp.c_str(), candidate->sdp_mline_index(),
292 candidate->sdp_mid().c_str());
gyzhouad7cad82017-05-11 16:10:03 -0700293}
294
gyzhoub38f3862017-07-25 16:04:31 -0700295void SimplePeerConnection::RegisterOnLocalI420FrameReady(
296 I420FRAMEREADY_CALLBACK callback) {
297 if (local_video_observer_)
298 local_video_observer_->SetVideoCallback(callback);
299}
300
301void SimplePeerConnection::RegisterOnRemoteI420FrameReady(
302 I420FRAMEREADY_CALLBACK callback) {
303 if (remote_video_observer_)
304 remote_video_observer_->SetVideoCallback(callback);
gyzhouad7cad82017-05-11 16:10:03 -0700305}
306
307void SimplePeerConnection::RegisterOnLocalDataChannelReady(
308 LOCALDATACHANNELREADY_CALLBACK callback) {
309 OnLocalDataChannelReady = callback;
310}
311
312void SimplePeerConnection::RegisterOnDataFromDataChannelReady(
313 DATAFROMEDATECHANNELREADY_CALLBACK callback) {
314 OnDataFromDataChannelReady = callback;
315}
316
317void SimplePeerConnection::RegisterOnFailure(FAILURE_CALLBACK callback) {
318 OnFailureMessage = callback;
319}
320
321void SimplePeerConnection::RegisterOnAudioBusReady(
322 AUDIOBUSREADY_CALLBACK callback) {
323 OnAudioReady = callback;
324}
325
326void SimplePeerConnection::RegisterOnLocalSdpReadytoSend(
327 LOCALSDPREADYTOSEND_CALLBACK callback) {
328 OnLocalSdpReady = callback;
329}
330
331void SimplePeerConnection::RegisterOnIceCandiateReadytoSend(
332 ICECANDIDATEREADYTOSEND_CALLBACK callback) {
333 OnIceCandiateReady = callback;
334}
335
gyzhoub38f3862017-07-25 16:04:31 -0700336bool SimplePeerConnection::SetRemoteDescription(const char* type,
337 const char* sdp) {
gyzhouad7cad82017-05-11 16:10:03 -0700338 if (!peer_connection_)
339 return false;
340
gyzhoub38f3862017-07-25 16:04:31 -0700341 std::string remote_desc(sdp);
Philipp Hanckedd680632020-09-10 17:22:16 +0200342 std::string desc_type(type);
gyzhouad7cad82017-05-11 16:10:03 -0700343 webrtc::SdpParseError error;
344 webrtc::SessionDescriptionInterface* session_description(
Philipp Hanckedd680632020-09-10 17:22:16 +0200345 webrtc::CreateSessionDescription(desc_type, remote_desc, &error));
gyzhouad7cad82017-05-11 16:10:03 -0700346 if (!session_description) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100347 RTC_LOG(WARNING) << "Can't parse received session description message. "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100348 "SdpParseError was: "
349 << error.description;
gyzhouad7cad82017-05-11 16:10:03 -0700350 return false;
351 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100352 RTC_LOG(INFO) << " Received session description :" << remote_desc;
gyzhouad7cad82017-05-11 16:10:03 -0700353 peer_connection_->SetRemoteDescription(
354 DummySetSessionDescriptionObserver::Create(), session_description);
355
356 return true;
357}
358
gyzhoub38f3862017-07-25 16:04:31 -0700359bool SimplePeerConnection::AddIceCandidate(const char* candidate,
360 const int sdp_mlineindex,
361 const char* sdp_mid) {
gyzhouad7cad82017-05-11 16:10:03 -0700362 if (!peer_connection_)
363 return false;
364
gyzhouad7cad82017-05-11 16:10:03 -0700365 webrtc::SdpParseError error;
gyzhoub38f3862017-07-25 16:04:31 -0700366 std::unique_ptr<webrtc::IceCandidateInterface> ice_candidate(
367 webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, candidate, &error));
368 if (!ice_candidate.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100369 RTC_LOG(WARNING) << "Can't parse received candidate message. "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100370 "SdpParseError was: "
371 << error.description;
gyzhouad7cad82017-05-11 16:10:03 -0700372 return false;
373 }
gyzhoub38f3862017-07-25 16:04:31 -0700374 if (!peer_connection_->AddIceCandidate(ice_candidate.get())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100375 RTC_LOG(WARNING) << "Failed to apply the received candidate";
gyzhouad7cad82017-05-11 16:10:03 -0700376 return false;
377 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100378 RTC_LOG(INFO) << " Received candidate :" << candidate;
gyzhouad7cad82017-05-11 16:10:03 -0700379 return true;
380}
381
382void SimplePeerConnection::SetAudioControl(bool is_mute, bool is_record) {
383 is_mute_audio_ = is_mute;
384 is_record_audio_ = is_record;
385
386 SetAudioControl();
387}
388
389void SimplePeerConnection::SetAudioControl() {
390 if (!remote_stream_)
391 return;
392 webrtc::AudioTrackVector tracks = remote_stream_->GetAudioTracks();
393 if (tracks.empty())
394 return;
395
396 webrtc::AudioTrackInterface* audio_track = tracks[0];
397 std::string id = audio_track->id();
398 if (is_record_audio_)
399 audio_track->AddSink(this);
400 else
401 audio_track->RemoveSink(this);
402
403 for (auto& track : tracks) {
404 if (is_mute_audio_)
405 track->set_enabled(false);
406 else
407 track->set_enabled(true);
408 }
409}
410
411void SimplePeerConnection::OnAddStream(
412 rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
Seth Hampson13b8bad2018-03-13 16:05:28 -0700413 RTC_LOG(INFO) << __FUNCTION__ << " " << stream->id();
gyzhouad7cad82017-05-11 16:10:03 -0700414 remote_stream_ = stream;
gyzhoub38f3862017-07-25 16:04:31 -0700415 if (remote_video_observer_ && !remote_stream_->GetVideoTracks().empty()) {
416 remote_stream_->GetVideoTracks()[0]->AddOrUpdateSink(
417 remote_video_observer_.get(), rtc::VideoSinkWants());
418 }
gyzhouad7cad82017-05-11 16:10:03 -0700419 SetAudioControl();
420}
421
gyzhouad7cad82017-05-11 16:10:03 -0700422void SimplePeerConnection::AddStreams(bool audio_only) {
Seth Hampson513449e2018-03-06 09:35:56 -0800423 if (active_streams_.find(kStreamId) != active_streams_.end())
gyzhouad7cad82017-05-11 16:10:03 -0700424 return; // Already added.
425
426 rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
Seth Hampson513449e2018-03-06 09:35:56 -0800427 g_peer_connection_factory->CreateLocalMediaStream(kStreamId);
gyzhouad7cad82017-05-11 16:10:03 -0700428
429 rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
430 g_peer_connection_factory->CreateAudioTrack(
Niels Möller2d02e082018-05-21 11:23:35 +0200431 kAudioLabel, g_peer_connection_factory->CreateAudioSource(
432 cricket::AudioOptions())));
gyzhouad7cad82017-05-11 16:10:03 -0700433 std::string id = audio_track->id();
434 stream->AddTrack(audio_track);
435
436 if (!audio_only) {
qiangchen42f96d52017-08-08 17:08:03 -0700437#if defined(WEBRTC_ANDROID)
magjeda3d4f682017-08-28 16:24:06 -0700438 JNIEnv* env = webrtc::jni::GetEnv();
qiangchen42f96d52017-08-08 17:08:03 -0700439 jclass pc_factory_class =
440 unity_plugin::FindClass(env, "org/webrtc/UnityUtility");
George Zhou2770c3d2018-03-07 09:58:54 -0800441 jmethodID load_texture_helper_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700442 env, pc_factory_class, "LoadSurfaceTextureHelper",
443 "()Lorg/webrtc/SurfaceTextureHelper;");
444 jobject texture_helper = env->CallStaticObjectMethod(
445 pc_factory_class, load_texture_helper_method);
446 CHECK_EXCEPTION(env);
447 RTC_DCHECK(texture_helper != nullptr)
448 << "Cannot get the Surface Texture Helper.";
449
Qiang Chen51e20462017-12-05 11:11:21 -0800450 rtc::scoped_refptr<webrtc::jni::AndroidVideoTrackSource> source(
451 new rtc::RefCountedObject<webrtc::jni::AndroidVideoTrackSource>(
Magnus Jedvert95140712018-11-15 12:07:32 +0100452 g_signaling_thread.get(), env, /* is_screencast= */ false,
453 /* align_timestamps= */ true));
qiangchen42f96d52017-08-08 17:08:03 -0700454
455 // link with VideoCapturer (Camera);
George Zhou2770c3d2018-03-07 09:58:54 -0800456 jmethodID link_camera_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700457 env, pc_factory_class, "LinkCamera",
458 "(JLorg/webrtc/SurfaceTextureHelper;)Lorg/webrtc/VideoCapturer;");
459 jobject camera_tmp =
460 env->CallStaticObjectMethod(pc_factory_class, link_camera_method,
Magnus Jedvert167316b2019-01-31 13:23:46 +0100461 (jlong)source.get(), texture_helper);
qiangchen42f96d52017-08-08 17:08:03 -0700462 CHECK_EXCEPTION(env);
463 g_camera = (jobject)env->NewGlobalRef(camera_tmp);
464
465 rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
466 g_peer_connection_factory->CreateVideoTrack(kVideoLabel,
Magnus Jedvert167316b2019-01-31 13:23:46 +0100467 source.release()));
qiangchen42f96d52017-08-08 17:08:03 -0700468 stream->AddTrack(video_track);
469#else
Niels Möller0a595352019-01-02 15:12:38 +0100470 rtc::scoped_refptr<CapturerTrackSource> video_device =
471 CapturerTrackSource::Create();
472 if (video_device) {
gyzhouad7cad82017-05-11 16:10:03 -0700473 rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
Niels Möller0a595352019-01-02 15:12:38 +0100474 g_peer_connection_factory->CreateVideoTrack(kVideoLabel,
475 video_device));
gyzhouad7cad82017-05-11 16:10:03 -0700476
477 stream->AddTrack(video_track);
qiangchen42f96d52017-08-08 17:08:03 -0700478 }
479#endif
480 if (local_video_observer_ && !stream->GetVideoTracks().empty()) {
481 stream->GetVideoTracks()[0]->AddOrUpdateSink(local_video_observer_.get(),
482 rtc::VideoSinkWants());
gyzhouad7cad82017-05-11 16:10:03 -0700483 }
484 }
485
486 if (!peer_connection_->AddStream(stream)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100487 RTC_LOG(LS_ERROR) << "Adding stream to PeerConnection failed";
gyzhouad7cad82017-05-11 16:10:03 -0700488 }
489
490 typedef std::pair<std::string,
491 rtc::scoped_refptr<webrtc::MediaStreamInterface>>
492 MediaStreamPair;
Seth Hampson13b8bad2018-03-13 16:05:28 -0700493 active_streams_.insert(MediaStreamPair(stream->id(), stream));
gyzhouad7cad82017-05-11 16:10:03 -0700494}
495
496bool SimplePeerConnection::CreateDataChannel() {
497 struct webrtc::DataChannelInit init;
498 init.ordered = true;
499 init.reliable = true;
500 data_channel_ = peer_connection_->CreateDataChannel("Hello", &init);
501 if (data_channel_.get()) {
502 data_channel_->RegisterObserver(this);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_INFO) << "Succeeds to create data channel";
gyzhouad7cad82017-05-11 16:10:03 -0700504 return true;
505 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100506 RTC_LOG(LS_INFO) << "Fails to create data channel";
gyzhouad7cad82017-05-11 16:10:03 -0700507 return false;
508 }
509}
510
511void SimplePeerConnection::CloseDataChannel() {
512 if (data_channel_.get()) {
513 data_channel_->UnregisterObserver();
514 data_channel_->Close();
515 }
516 data_channel_ = nullptr;
517}
518
519bool SimplePeerConnection::SendDataViaDataChannel(const std::string& data) {
520 if (!data_channel_.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100521 RTC_LOG(LS_INFO) << "Data channel is not established";
gyzhouad7cad82017-05-11 16:10:03 -0700522 return false;
523 }
524 webrtc::DataBuffer buffer(data);
525 data_channel_->Send(buffer);
526 return true;
527}
528
529// Peerconnection observer
530void SimplePeerConnection::OnDataChannel(
531 rtc::scoped_refptr<webrtc::DataChannelInterface> channel) {
532 channel->RegisterObserver(this);
533}
534
535void SimplePeerConnection::OnStateChange() {
536 if (data_channel_) {
537 webrtc::DataChannelInterface::DataState state = data_channel_->state();
538 if (state == webrtc::DataChannelInterface::kOpen) {
539 if (OnLocalDataChannelReady)
540 OnLocalDataChannelReady();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100541 RTC_LOG(LS_INFO) << "Data channel is open";
gyzhouad7cad82017-05-11 16:10:03 -0700542 }
543 }
544}
545
546// A data buffer was successfully received.
547void SimplePeerConnection::OnMessage(const webrtc::DataBuffer& buffer) {
548 size_t size = buffer.data.size();
549 char* msg = new char[size + 1];
550 memcpy(msg, buffer.data.data(), size);
551 msg[size] = 0;
552 if (OnDataFromDataChannelReady)
553 OnDataFromDataChannelReady(msg);
554 delete[] msg;
555}
556
557// AudioTrackSinkInterface implementation.
558void SimplePeerConnection::OnData(const void* audio_data,
559 int bits_per_sample,
560 int sample_rate,
561 size_t number_of_channels,
562 size_t number_of_frames) {
563 if (OnAudioReady)
564 OnAudioReady(audio_data, bits_per_sample, sample_rate,
565 static_cast<int>(number_of_channels),
566 static_cast<int>(number_of_frames));
567}
568
569std::vector<uint32_t> SimplePeerConnection::GetRemoteAudioTrackSsrcs() {
570 std::vector<rtc::scoped_refptr<webrtc::RtpReceiverInterface>> receivers =
571 peer_connection_->GetReceivers();
572
573 std::vector<uint32_t> ssrcs;
574 for (const auto& receiver : receivers) {
575 if (receiver->media_type() != cricket::MEDIA_TYPE_AUDIO)
576 continue;
577
578 std::vector<webrtc::RtpEncodingParameters> params =
579 receiver->GetParameters().encodings;
580
581 for (const auto& param : params) {
582 uint32_t ssrc = param.ssrc.value_or(0);
583 if (ssrc > 0)
584 ssrcs.push_back(ssrc);
585 }
586 }
587
588 return ssrcs;
589}