blob: 23e4d7b86997230fa0e801619775fe297a6ff2dc [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
gyzhouad7cad82017-05-11 16:10:03 -0700195 peer_connection_ = g_peer_connection_factory->CreatePeerConnection(
Niels Möllerf06f9232018-08-07 12:32:18 +0200196 config_, nullptr, nullptr, this);
gyzhouad7cad82017-05-11 16:10:03 -0700197
198 return peer_connection_.get() != nullptr;
199}
200
201void SimplePeerConnection::DeletePeerConnection() {
202 g_peer_count--;
203
qiangchen42f96d52017-08-08 17:08:03 -0700204#if defined(WEBRTC_ANDROID)
205 if (g_camera) {
magjeda3d4f682017-08-28 16:24:06 -0700206 JNIEnv* env = webrtc::jni::GetEnv();
qiangchen42f96d52017-08-08 17:08:03 -0700207 jclass pc_factory_class =
208 unity_plugin::FindClass(env, "org/webrtc/UnityUtility");
George Zhou2770c3d2018-03-07 09:58:54 -0800209 jmethodID stop_camera_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700210 env, pc_factory_class, "StopCamera", "(Lorg/webrtc/VideoCapturer;)V");
211
212 env->CallStaticVoidMethod(pc_factory_class, stop_camera_method, g_camera);
213 CHECK_EXCEPTION(env);
214
215 g_camera = nullptr;
216 }
217#endif
218
gyzhouad7cad82017-05-11 16:10:03 -0700219 CloseDataChannel();
220 peer_connection_ = nullptr;
221 active_streams_.clear();
222
223 if (g_peer_count == 0) {
224 g_peer_connection_factory = nullptr;
225 g_signaling_thread.reset();
226 g_worker_thread.reset();
227 }
228}
229
230bool SimplePeerConnection::CreateOffer() {
231 if (!peer_connection_.get())
232 return false;
233
Niels Möllerf06f9232018-08-07 12:32:18 +0200234 webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
Qiang Chen51e20462017-12-05 11:11:21 -0800235 if (mandatory_receive_) {
Niels Möllerf06f9232018-08-07 12:32:18 +0200236 options.offer_to_receive_audio = true;
237 options.offer_to_receive_video = true;
Qiang Chen51e20462017-12-05 11:11:21 -0800238 }
Niels Möllerf06f9232018-08-07 12:32:18 +0200239 peer_connection_->CreateOffer(this, options);
gyzhouad7cad82017-05-11 16:10:03 -0700240 return true;
241}
242
243bool SimplePeerConnection::CreateAnswer() {
244 if (!peer_connection_.get())
245 return false;
246
Niels Möllerf06f9232018-08-07 12:32:18 +0200247 webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
Qiang Chen51e20462017-12-05 11:11:21 -0800248 if (mandatory_receive_) {
Niels Möllerf06f9232018-08-07 12:32:18 +0200249 options.offer_to_receive_audio = true;
250 options.offer_to_receive_video = true;
Qiang Chen51e20462017-12-05 11:11:21 -0800251 }
Niels Möllerf06f9232018-08-07 12:32:18 +0200252 peer_connection_->CreateAnswer(this, options);
gyzhouad7cad82017-05-11 16:10:03 -0700253 return true;
254}
255
256void SimplePeerConnection::OnSuccess(
257 webrtc::SessionDescriptionInterface* desc) {
258 peer_connection_->SetLocalDescription(
259 DummySetSessionDescriptionObserver::Create(), desc);
260
261 std::string sdp;
262 desc->ToString(&sdp);
263
gyzhouad7cad82017-05-11 16:10:03 -0700264 if (OnLocalSdpReady)
gyzhoub38f3862017-07-25 16:04:31 -0700265 OnLocalSdpReady(desc->type().c_str(), sdp.c_str());
gyzhouad7cad82017-05-11 16:10:03 -0700266}
267
Harald Alvestrand73771a82018-05-24 10:53:49 +0200268void SimplePeerConnection::OnFailure(webrtc::RTCError error) {
269 RTC_LOG(LERROR) << ToString(error.type()) << ": " << error.message();
gyzhouad7cad82017-05-11 16:10:03 -0700270
Harald Alvestrand73771a82018-05-24 10:53:49 +0200271 // TODO(hta): include error.type in the message
gyzhouad7cad82017-05-11 16:10:03 -0700272 if (OnFailureMessage)
Harald Alvestrand73771a82018-05-24 10:53:49 +0200273 OnFailureMessage(error.message());
gyzhouad7cad82017-05-11 16:10:03 -0700274}
275
276void SimplePeerConnection::OnIceCandidate(
277 const webrtc::IceCandidateInterface* candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100278 RTC_LOG(INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index();
gyzhouad7cad82017-05-11 16:10:03 -0700279
gyzhouad7cad82017-05-11 16:10:03 -0700280 std::string sdp;
281 if (!candidate->ToString(&sdp)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100282 RTC_LOG(LS_ERROR) << "Failed to serialize candidate";
gyzhouad7cad82017-05-11 16:10:03 -0700283 return;
284 }
gyzhouad7cad82017-05-11 16:10:03 -0700285
286 if (OnIceCandiateReady)
gyzhoub38f3862017-07-25 16:04:31 -0700287 OnIceCandiateReady(sdp.c_str(), candidate->sdp_mline_index(),
288 candidate->sdp_mid().c_str());
gyzhouad7cad82017-05-11 16:10:03 -0700289}
290
gyzhoub38f3862017-07-25 16:04:31 -0700291void SimplePeerConnection::RegisterOnLocalI420FrameReady(
292 I420FRAMEREADY_CALLBACK callback) {
293 if (local_video_observer_)
294 local_video_observer_->SetVideoCallback(callback);
295}
296
297void SimplePeerConnection::RegisterOnRemoteI420FrameReady(
298 I420FRAMEREADY_CALLBACK callback) {
299 if (remote_video_observer_)
300 remote_video_observer_->SetVideoCallback(callback);
gyzhouad7cad82017-05-11 16:10:03 -0700301}
302
303void SimplePeerConnection::RegisterOnLocalDataChannelReady(
304 LOCALDATACHANNELREADY_CALLBACK callback) {
305 OnLocalDataChannelReady = callback;
306}
307
308void SimplePeerConnection::RegisterOnDataFromDataChannelReady(
309 DATAFROMEDATECHANNELREADY_CALLBACK callback) {
310 OnDataFromDataChannelReady = callback;
311}
312
313void SimplePeerConnection::RegisterOnFailure(FAILURE_CALLBACK callback) {
314 OnFailureMessage = callback;
315}
316
317void SimplePeerConnection::RegisterOnAudioBusReady(
318 AUDIOBUSREADY_CALLBACK callback) {
319 OnAudioReady = callback;
320}
321
322void SimplePeerConnection::RegisterOnLocalSdpReadytoSend(
323 LOCALSDPREADYTOSEND_CALLBACK callback) {
324 OnLocalSdpReady = callback;
325}
326
327void SimplePeerConnection::RegisterOnIceCandiateReadytoSend(
328 ICECANDIDATEREADYTOSEND_CALLBACK callback) {
329 OnIceCandiateReady = callback;
330}
331
gyzhoub38f3862017-07-25 16:04:31 -0700332bool SimplePeerConnection::SetRemoteDescription(const char* type,
333 const char* sdp) {
gyzhouad7cad82017-05-11 16:10:03 -0700334 if (!peer_connection_)
335 return false;
336
gyzhoub38f3862017-07-25 16:04:31 -0700337 std::string remote_desc(sdp);
Philipp Hanckedd680632020-09-10 17:22:16 +0200338 std::string desc_type(type);
gyzhouad7cad82017-05-11 16:10:03 -0700339 webrtc::SdpParseError error;
340 webrtc::SessionDescriptionInterface* session_description(
Philipp Hanckedd680632020-09-10 17:22:16 +0200341 webrtc::CreateSessionDescription(desc_type, remote_desc, &error));
gyzhouad7cad82017-05-11 16:10:03 -0700342 if (!session_description) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100343 RTC_LOG(WARNING) << "Can't parse received session description message. "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100344 "SdpParseError was: "
345 << error.description;
gyzhouad7cad82017-05-11 16:10:03 -0700346 return false;
347 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100348 RTC_LOG(INFO) << " Received session description :" << remote_desc;
gyzhouad7cad82017-05-11 16:10:03 -0700349 peer_connection_->SetRemoteDescription(
350 DummySetSessionDescriptionObserver::Create(), session_description);
351
352 return true;
353}
354
gyzhoub38f3862017-07-25 16:04:31 -0700355bool SimplePeerConnection::AddIceCandidate(const char* candidate,
356 const int sdp_mlineindex,
357 const char* sdp_mid) {
gyzhouad7cad82017-05-11 16:10:03 -0700358 if (!peer_connection_)
359 return false;
360
gyzhouad7cad82017-05-11 16:10:03 -0700361 webrtc::SdpParseError error;
gyzhoub38f3862017-07-25 16:04:31 -0700362 std::unique_ptr<webrtc::IceCandidateInterface> ice_candidate(
363 webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, candidate, &error));
364 if (!ice_candidate.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100365 RTC_LOG(WARNING) << "Can't parse received candidate message. "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100366 "SdpParseError was: "
367 << error.description;
gyzhouad7cad82017-05-11 16:10:03 -0700368 return false;
369 }
gyzhoub38f3862017-07-25 16:04:31 -0700370 if (!peer_connection_->AddIceCandidate(ice_candidate.get())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100371 RTC_LOG(WARNING) << "Failed to apply the received candidate";
gyzhouad7cad82017-05-11 16:10:03 -0700372 return false;
373 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100374 RTC_LOG(INFO) << " Received candidate :" << candidate;
gyzhouad7cad82017-05-11 16:10:03 -0700375 return true;
376}
377
378void SimplePeerConnection::SetAudioControl(bool is_mute, bool is_record) {
379 is_mute_audio_ = is_mute;
380 is_record_audio_ = is_record;
381
382 SetAudioControl();
383}
384
385void SimplePeerConnection::SetAudioControl() {
386 if (!remote_stream_)
387 return;
388 webrtc::AudioTrackVector tracks = remote_stream_->GetAudioTracks();
389 if (tracks.empty())
390 return;
391
392 webrtc::AudioTrackInterface* audio_track = tracks[0];
393 std::string id = audio_track->id();
394 if (is_record_audio_)
395 audio_track->AddSink(this);
396 else
397 audio_track->RemoveSink(this);
398
399 for (auto& track : tracks) {
400 if (is_mute_audio_)
401 track->set_enabled(false);
402 else
403 track->set_enabled(true);
404 }
405}
406
407void SimplePeerConnection::OnAddStream(
408 rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
Seth Hampson13b8bad2018-03-13 16:05:28 -0700409 RTC_LOG(INFO) << __FUNCTION__ << " " << stream->id();
gyzhouad7cad82017-05-11 16:10:03 -0700410 remote_stream_ = stream;
gyzhoub38f3862017-07-25 16:04:31 -0700411 if (remote_video_observer_ && !remote_stream_->GetVideoTracks().empty()) {
412 remote_stream_->GetVideoTracks()[0]->AddOrUpdateSink(
413 remote_video_observer_.get(), rtc::VideoSinkWants());
414 }
gyzhouad7cad82017-05-11 16:10:03 -0700415 SetAudioControl();
416}
417
gyzhouad7cad82017-05-11 16:10:03 -0700418void SimplePeerConnection::AddStreams(bool audio_only) {
Seth Hampson513449e2018-03-06 09:35:56 -0800419 if (active_streams_.find(kStreamId) != active_streams_.end())
gyzhouad7cad82017-05-11 16:10:03 -0700420 return; // Already added.
421
422 rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
Seth Hampson513449e2018-03-06 09:35:56 -0800423 g_peer_connection_factory->CreateLocalMediaStream(kStreamId);
gyzhouad7cad82017-05-11 16:10:03 -0700424
425 rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
426 g_peer_connection_factory->CreateAudioTrack(
Niels Möller2d02e082018-05-21 11:23:35 +0200427 kAudioLabel, g_peer_connection_factory->CreateAudioSource(
428 cricket::AudioOptions())));
gyzhouad7cad82017-05-11 16:10:03 -0700429 std::string id = audio_track->id();
430 stream->AddTrack(audio_track);
431
432 if (!audio_only) {
qiangchen42f96d52017-08-08 17:08:03 -0700433#if defined(WEBRTC_ANDROID)
magjeda3d4f682017-08-28 16:24:06 -0700434 JNIEnv* env = webrtc::jni::GetEnv();
qiangchen42f96d52017-08-08 17:08:03 -0700435 jclass pc_factory_class =
436 unity_plugin::FindClass(env, "org/webrtc/UnityUtility");
George Zhou2770c3d2018-03-07 09:58:54 -0800437 jmethodID load_texture_helper_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700438 env, pc_factory_class, "LoadSurfaceTextureHelper",
439 "()Lorg/webrtc/SurfaceTextureHelper;");
440 jobject texture_helper = env->CallStaticObjectMethod(
441 pc_factory_class, load_texture_helper_method);
442 CHECK_EXCEPTION(env);
443 RTC_DCHECK(texture_helper != nullptr)
444 << "Cannot get the Surface Texture Helper.";
445
Qiang Chen51e20462017-12-05 11:11:21 -0800446 rtc::scoped_refptr<webrtc::jni::AndroidVideoTrackSource> source(
447 new rtc::RefCountedObject<webrtc::jni::AndroidVideoTrackSource>(
Magnus Jedvert95140712018-11-15 12:07:32 +0100448 g_signaling_thread.get(), env, /* is_screencast= */ false,
449 /* align_timestamps= */ true));
qiangchen42f96d52017-08-08 17:08:03 -0700450
451 // link with VideoCapturer (Camera);
George Zhou2770c3d2018-03-07 09:58:54 -0800452 jmethodID link_camera_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700453 env, pc_factory_class, "LinkCamera",
454 "(JLorg/webrtc/SurfaceTextureHelper;)Lorg/webrtc/VideoCapturer;");
455 jobject camera_tmp =
456 env->CallStaticObjectMethod(pc_factory_class, link_camera_method,
Magnus Jedvert167316b2019-01-31 13:23:46 +0100457 (jlong)source.get(), texture_helper);
qiangchen42f96d52017-08-08 17:08:03 -0700458 CHECK_EXCEPTION(env);
459 g_camera = (jobject)env->NewGlobalRef(camera_tmp);
460
461 rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
462 g_peer_connection_factory->CreateVideoTrack(kVideoLabel,
Magnus Jedvert167316b2019-01-31 13:23:46 +0100463 source.release()));
qiangchen42f96d52017-08-08 17:08:03 -0700464 stream->AddTrack(video_track);
465#else
Niels Möller0a595352019-01-02 15:12:38 +0100466 rtc::scoped_refptr<CapturerTrackSource> video_device =
467 CapturerTrackSource::Create();
468 if (video_device) {
gyzhouad7cad82017-05-11 16:10:03 -0700469 rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
Niels Möller0a595352019-01-02 15:12:38 +0100470 g_peer_connection_factory->CreateVideoTrack(kVideoLabel,
471 video_device));
gyzhouad7cad82017-05-11 16:10:03 -0700472
473 stream->AddTrack(video_track);
qiangchen42f96d52017-08-08 17:08:03 -0700474 }
475#endif
476 if (local_video_observer_ && !stream->GetVideoTracks().empty()) {
477 stream->GetVideoTracks()[0]->AddOrUpdateSink(local_video_observer_.get(),
478 rtc::VideoSinkWants());
gyzhouad7cad82017-05-11 16:10:03 -0700479 }
480 }
481
482 if (!peer_connection_->AddStream(stream)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100483 RTC_LOG(LS_ERROR) << "Adding stream to PeerConnection failed";
gyzhouad7cad82017-05-11 16:10:03 -0700484 }
485
486 typedef std::pair<std::string,
487 rtc::scoped_refptr<webrtc::MediaStreamInterface>>
488 MediaStreamPair;
Seth Hampson13b8bad2018-03-13 16:05:28 -0700489 active_streams_.insert(MediaStreamPair(stream->id(), stream));
gyzhouad7cad82017-05-11 16:10:03 -0700490}
491
492bool SimplePeerConnection::CreateDataChannel() {
493 struct webrtc::DataChannelInit init;
494 init.ordered = true;
495 init.reliable = true;
496 data_channel_ = peer_connection_->CreateDataChannel("Hello", &init);
497 if (data_channel_.get()) {
498 data_channel_->RegisterObserver(this);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100499 RTC_LOG(LS_INFO) << "Succeeds to create data channel";
gyzhouad7cad82017-05-11 16:10:03 -0700500 return true;
501 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100502 RTC_LOG(LS_INFO) << "Fails to create data channel";
gyzhouad7cad82017-05-11 16:10:03 -0700503 return false;
504 }
505}
506
507void SimplePeerConnection::CloseDataChannel() {
508 if (data_channel_.get()) {
509 data_channel_->UnregisterObserver();
510 data_channel_->Close();
511 }
512 data_channel_ = nullptr;
513}
514
515bool SimplePeerConnection::SendDataViaDataChannel(const std::string& data) {
516 if (!data_channel_.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100517 RTC_LOG(LS_INFO) << "Data channel is not established";
gyzhouad7cad82017-05-11 16:10:03 -0700518 return false;
519 }
520 webrtc::DataBuffer buffer(data);
521 data_channel_->Send(buffer);
522 return true;
523}
524
525// Peerconnection observer
526void SimplePeerConnection::OnDataChannel(
527 rtc::scoped_refptr<webrtc::DataChannelInterface> channel) {
528 channel->RegisterObserver(this);
529}
530
531void SimplePeerConnection::OnStateChange() {
532 if (data_channel_) {
533 webrtc::DataChannelInterface::DataState state = data_channel_->state();
534 if (state == webrtc::DataChannelInterface::kOpen) {
535 if (OnLocalDataChannelReady)
536 OnLocalDataChannelReady();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100537 RTC_LOG(LS_INFO) << "Data channel is open";
gyzhouad7cad82017-05-11 16:10:03 -0700538 }
539 }
540}
541
542// A data buffer was successfully received.
543void SimplePeerConnection::OnMessage(const webrtc::DataBuffer& buffer) {
544 size_t size = buffer.data.size();
545 char* msg = new char[size + 1];
546 memcpy(msg, buffer.data.data(), size);
547 msg[size] = 0;
548 if (OnDataFromDataChannelReady)
549 OnDataFromDataChannelReady(msg);
550 delete[] msg;
551}
552
553// AudioTrackSinkInterface implementation.
554void SimplePeerConnection::OnData(const void* audio_data,
555 int bits_per_sample,
556 int sample_rate,
557 size_t number_of_channels,
558 size_t number_of_frames) {
559 if (OnAudioReady)
560 OnAudioReady(audio_data, bits_per_sample, sample_rate,
561 static_cast<int>(number_of_channels),
562 static_cast<int>(number_of_frames));
563}
564
565std::vector<uint32_t> SimplePeerConnection::GetRemoteAudioTrackSsrcs() {
566 std::vector<rtc::scoped_refptr<webrtc::RtpReceiverInterface>> receivers =
567 peer_connection_->GetReceivers();
568
569 std::vector<uint32_t> ssrcs;
570 for (const auto& receiver : receivers) {
571 if (receiver->media_type() != cricket::MEDIA_TYPE_AUDIO)
572 continue;
573
574 std::vector<webrtc::RtpEncodingParameters> params =
575 receiver->GetParameters().encodings;
576
577 for (const auto& param : params) {
578 uint32_t ssrc = param.ssrc.value_or(0);
579 if (ssrc > 0)
580 ssrcs.push_back(ssrc);
581 }
582 }
583
584 return ssrcs;
585}