blob: 4fd2fc359db9a840fb30ebcdf67848e91f4abef0 [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_rtp_data_channel = true;
194 config_.enable_dtls_srtp = false;
gyzhouad7cad82017-05-11 16:10:03 -0700195
gyzhouad7cad82017-05-11 16:10:03 -0700196 peer_connection_ = g_peer_connection_factory->CreatePeerConnection(
Niels Möllerf06f9232018-08-07 12:32:18 +0200197 config_, nullptr, nullptr, this);
gyzhouad7cad82017-05-11 16:10:03 -0700198
199 return peer_connection_.get() != nullptr;
200}
201
202void SimplePeerConnection::DeletePeerConnection() {
203 g_peer_count--;
204
qiangchen42f96d52017-08-08 17:08:03 -0700205#if defined(WEBRTC_ANDROID)
206 if (g_camera) {
magjeda3d4f682017-08-28 16:24:06 -0700207 JNIEnv* env = webrtc::jni::GetEnv();
qiangchen42f96d52017-08-08 17:08:03 -0700208 jclass pc_factory_class =
209 unity_plugin::FindClass(env, "org/webrtc/UnityUtility");
George Zhou2770c3d2018-03-07 09:58:54 -0800210 jmethodID stop_camera_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700211 env, pc_factory_class, "StopCamera", "(Lorg/webrtc/VideoCapturer;)V");
212
213 env->CallStaticVoidMethod(pc_factory_class, stop_camera_method, g_camera);
214 CHECK_EXCEPTION(env);
215
216 g_camera = nullptr;
217 }
218#endif
219
gyzhouad7cad82017-05-11 16:10:03 -0700220 CloseDataChannel();
221 peer_connection_ = nullptr;
222 active_streams_.clear();
223
224 if (g_peer_count == 0) {
225 g_peer_connection_factory = nullptr;
226 g_signaling_thread.reset();
227 g_worker_thread.reset();
228 }
229}
230
231bool SimplePeerConnection::CreateOffer() {
232 if (!peer_connection_.get())
233 return false;
234
Niels Möllerf06f9232018-08-07 12:32:18 +0200235 webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
Qiang Chen51e20462017-12-05 11:11:21 -0800236 if (mandatory_receive_) {
Niels Möllerf06f9232018-08-07 12:32:18 +0200237 options.offer_to_receive_audio = true;
238 options.offer_to_receive_video = true;
Qiang Chen51e20462017-12-05 11:11:21 -0800239 }
Niels Möllerf06f9232018-08-07 12:32:18 +0200240 peer_connection_->CreateOffer(this, options);
gyzhouad7cad82017-05-11 16:10:03 -0700241 return true;
242}
243
244bool SimplePeerConnection::CreateAnswer() {
245 if (!peer_connection_.get())
246 return false;
247
Niels Möllerf06f9232018-08-07 12:32:18 +0200248 webrtc::PeerConnectionInterface::RTCOfferAnswerOptions options;
Qiang Chen51e20462017-12-05 11:11:21 -0800249 if (mandatory_receive_) {
Niels Möllerf06f9232018-08-07 12:32:18 +0200250 options.offer_to_receive_audio = true;
251 options.offer_to_receive_video = true;
Qiang Chen51e20462017-12-05 11:11:21 -0800252 }
Niels Möllerf06f9232018-08-07 12:32:18 +0200253 peer_connection_->CreateAnswer(this, options);
gyzhouad7cad82017-05-11 16:10:03 -0700254 return true;
255}
256
257void SimplePeerConnection::OnSuccess(
258 webrtc::SessionDescriptionInterface* desc) {
259 peer_connection_->SetLocalDescription(
260 DummySetSessionDescriptionObserver::Create(), desc);
261
262 std::string sdp;
263 desc->ToString(&sdp);
264
gyzhouad7cad82017-05-11 16:10:03 -0700265 if (OnLocalSdpReady)
gyzhoub38f3862017-07-25 16:04:31 -0700266 OnLocalSdpReady(desc->type().c_str(), sdp.c_str());
gyzhouad7cad82017-05-11 16:10:03 -0700267}
268
Harald Alvestrand73771a82018-05-24 10:53:49 +0200269void SimplePeerConnection::OnFailure(webrtc::RTCError error) {
270 RTC_LOG(LERROR) << ToString(error.type()) << ": " << error.message();
gyzhouad7cad82017-05-11 16:10:03 -0700271
Harald Alvestrand73771a82018-05-24 10:53:49 +0200272 // TODO(hta): include error.type in the message
gyzhouad7cad82017-05-11 16:10:03 -0700273 if (OnFailureMessage)
Harald Alvestrand73771a82018-05-24 10:53:49 +0200274 OnFailureMessage(error.message());
gyzhouad7cad82017-05-11 16:10:03 -0700275}
276
277void SimplePeerConnection::OnIceCandidate(
278 const webrtc::IceCandidateInterface* candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100279 RTC_LOG(INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index();
gyzhouad7cad82017-05-11 16:10:03 -0700280
gyzhouad7cad82017-05-11 16:10:03 -0700281 std::string sdp;
282 if (!candidate->ToString(&sdp)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100283 RTC_LOG(LS_ERROR) << "Failed to serialize candidate";
gyzhouad7cad82017-05-11 16:10:03 -0700284 return;
285 }
gyzhouad7cad82017-05-11 16:10:03 -0700286
287 if (OnIceCandiateReady)
gyzhoub38f3862017-07-25 16:04:31 -0700288 OnIceCandiateReady(sdp.c_str(), candidate->sdp_mline_index(),
289 candidate->sdp_mid().c_str());
gyzhouad7cad82017-05-11 16:10:03 -0700290}
291
gyzhoub38f3862017-07-25 16:04:31 -0700292void SimplePeerConnection::RegisterOnLocalI420FrameReady(
293 I420FRAMEREADY_CALLBACK callback) {
294 if (local_video_observer_)
295 local_video_observer_->SetVideoCallback(callback);
296}
297
298void SimplePeerConnection::RegisterOnRemoteI420FrameReady(
299 I420FRAMEREADY_CALLBACK callback) {
300 if (remote_video_observer_)
301 remote_video_observer_->SetVideoCallback(callback);
gyzhouad7cad82017-05-11 16:10:03 -0700302}
303
304void SimplePeerConnection::RegisterOnLocalDataChannelReady(
305 LOCALDATACHANNELREADY_CALLBACK callback) {
306 OnLocalDataChannelReady = callback;
307}
308
309void SimplePeerConnection::RegisterOnDataFromDataChannelReady(
310 DATAFROMEDATECHANNELREADY_CALLBACK callback) {
311 OnDataFromDataChannelReady = callback;
312}
313
314void SimplePeerConnection::RegisterOnFailure(FAILURE_CALLBACK callback) {
315 OnFailureMessage = callback;
316}
317
318void SimplePeerConnection::RegisterOnAudioBusReady(
319 AUDIOBUSREADY_CALLBACK callback) {
320 OnAudioReady = callback;
321}
322
323void SimplePeerConnection::RegisterOnLocalSdpReadytoSend(
324 LOCALSDPREADYTOSEND_CALLBACK callback) {
325 OnLocalSdpReady = callback;
326}
327
328void SimplePeerConnection::RegisterOnIceCandiateReadytoSend(
329 ICECANDIDATEREADYTOSEND_CALLBACK callback) {
330 OnIceCandiateReady = callback;
331}
332
gyzhoub38f3862017-07-25 16:04:31 -0700333bool SimplePeerConnection::SetRemoteDescription(const char* type,
334 const char* sdp) {
gyzhouad7cad82017-05-11 16:10:03 -0700335 if (!peer_connection_)
336 return false;
337
gyzhoub38f3862017-07-25 16:04:31 -0700338 std::string remote_desc(sdp);
Philipp Hanckedd680632020-09-10 17:22:16 +0200339 std::string desc_type(type);
gyzhouad7cad82017-05-11 16:10:03 -0700340 webrtc::SdpParseError error;
341 webrtc::SessionDescriptionInterface* session_description(
Philipp Hanckedd680632020-09-10 17:22:16 +0200342 webrtc::CreateSessionDescription(desc_type, remote_desc, &error));
gyzhouad7cad82017-05-11 16:10:03 -0700343 if (!session_description) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100344 RTC_LOG(WARNING) << "Can't parse received session description message. "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100345 "SdpParseError was: "
346 << error.description;
gyzhouad7cad82017-05-11 16:10:03 -0700347 return false;
348 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100349 RTC_LOG(INFO) << " Received session description :" << remote_desc;
gyzhouad7cad82017-05-11 16:10:03 -0700350 peer_connection_->SetRemoteDescription(
351 DummySetSessionDescriptionObserver::Create(), session_description);
352
353 return true;
354}
355
gyzhoub38f3862017-07-25 16:04:31 -0700356bool SimplePeerConnection::AddIceCandidate(const char* candidate,
357 const int sdp_mlineindex,
358 const char* sdp_mid) {
gyzhouad7cad82017-05-11 16:10:03 -0700359 if (!peer_connection_)
360 return false;
361
gyzhouad7cad82017-05-11 16:10:03 -0700362 webrtc::SdpParseError error;
gyzhoub38f3862017-07-25 16:04:31 -0700363 std::unique_ptr<webrtc::IceCandidateInterface> ice_candidate(
364 webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, candidate, &error));
365 if (!ice_candidate.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100366 RTC_LOG(WARNING) << "Can't parse received candidate message. "
Jonas Olssonb2b20312020-01-14 12:11:31 +0100367 "SdpParseError was: "
368 << error.description;
gyzhouad7cad82017-05-11 16:10:03 -0700369 return false;
370 }
gyzhoub38f3862017-07-25 16:04:31 -0700371 if (!peer_connection_->AddIceCandidate(ice_candidate.get())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100372 RTC_LOG(WARNING) << "Failed to apply the received candidate";
gyzhouad7cad82017-05-11 16:10:03 -0700373 return false;
374 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100375 RTC_LOG(INFO) << " Received candidate :" << candidate;
gyzhouad7cad82017-05-11 16:10:03 -0700376 return true;
377}
378
379void SimplePeerConnection::SetAudioControl(bool is_mute, bool is_record) {
380 is_mute_audio_ = is_mute;
381 is_record_audio_ = is_record;
382
383 SetAudioControl();
384}
385
386void SimplePeerConnection::SetAudioControl() {
387 if (!remote_stream_)
388 return;
389 webrtc::AudioTrackVector tracks = remote_stream_->GetAudioTracks();
390 if (tracks.empty())
391 return;
392
393 webrtc::AudioTrackInterface* audio_track = tracks[0];
394 std::string id = audio_track->id();
395 if (is_record_audio_)
396 audio_track->AddSink(this);
397 else
398 audio_track->RemoveSink(this);
399
400 for (auto& track : tracks) {
401 if (is_mute_audio_)
402 track->set_enabled(false);
403 else
404 track->set_enabled(true);
405 }
406}
407
408void SimplePeerConnection::OnAddStream(
409 rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
Seth Hampson13b8bad2018-03-13 16:05:28 -0700410 RTC_LOG(INFO) << __FUNCTION__ << " " << stream->id();
gyzhouad7cad82017-05-11 16:10:03 -0700411 remote_stream_ = stream;
gyzhoub38f3862017-07-25 16:04:31 -0700412 if (remote_video_observer_ && !remote_stream_->GetVideoTracks().empty()) {
413 remote_stream_->GetVideoTracks()[0]->AddOrUpdateSink(
414 remote_video_observer_.get(), rtc::VideoSinkWants());
415 }
gyzhouad7cad82017-05-11 16:10:03 -0700416 SetAudioControl();
417}
418
gyzhouad7cad82017-05-11 16:10:03 -0700419void SimplePeerConnection::AddStreams(bool audio_only) {
Seth Hampson513449e2018-03-06 09:35:56 -0800420 if (active_streams_.find(kStreamId) != active_streams_.end())
gyzhouad7cad82017-05-11 16:10:03 -0700421 return; // Already added.
422
423 rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
Seth Hampson513449e2018-03-06 09:35:56 -0800424 g_peer_connection_factory->CreateLocalMediaStream(kStreamId);
gyzhouad7cad82017-05-11 16:10:03 -0700425
426 rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
427 g_peer_connection_factory->CreateAudioTrack(
Niels Möller2d02e082018-05-21 11:23:35 +0200428 kAudioLabel, g_peer_connection_factory->CreateAudioSource(
429 cricket::AudioOptions())));
gyzhouad7cad82017-05-11 16:10:03 -0700430 std::string id = audio_track->id();
431 stream->AddTrack(audio_track);
432
433 if (!audio_only) {
qiangchen42f96d52017-08-08 17:08:03 -0700434#if defined(WEBRTC_ANDROID)
magjeda3d4f682017-08-28 16:24:06 -0700435 JNIEnv* env = webrtc::jni::GetEnv();
qiangchen42f96d52017-08-08 17:08:03 -0700436 jclass pc_factory_class =
437 unity_plugin::FindClass(env, "org/webrtc/UnityUtility");
George Zhou2770c3d2018-03-07 09:58:54 -0800438 jmethodID load_texture_helper_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700439 env, pc_factory_class, "LoadSurfaceTextureHelper",
440 "()Lorg/webrtc/SurfaceTextureHelper;");
441 jobject texture_helper = env->CallStaticObjectMethod(
442 pc_factory_class, load_texture_helper_method);
443 CHECK_EXCEPTION(env);
444 RTC_DCHECK(texture_helper != nullptr)
445 << "Cannot get the Surface Texture Helper.";
446
Qiang Chen51e20462017-12-05 11:11:21 -0800447 rtc::scoped_refptr<webrtc::jni::AndroidVideoTrackSource> source(
448 new rtc::RefCountedObject<webrtc::jni::AndroidVideoTrackSource>(
Magnus Jedvert95140712018-11-15 12:07:32 +0100449 g_signaling_thread.get(), env, /* is_screencast= */ false,
450 /* align_timestamps= */ true));
qiangchen42f96d52017-08-08 17:08:03 -0700451
452 // link with VideoCapturer (Camera);
George Zhou2770c3d2018-03-07 09:58:54 -0800453 jmethodID link_camera_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700454 env, pc_factory_class, "LinkCamera",
455 "(JLorg/webrtc/SurfaceTextureHelper;)Lorg/webrtc/VideoCapturer;");
456 jobject camera_tmp =
457 env->CallStaticObjectMethod(pc_factory_class, link_camera_method,
Magnus Jedvert167316b2019-01-31 13:23:46 +0100458 (jlong)source.get(), texture_helper);
qiangchen42f96d52017-08-08 17:08:03 -0700459 CHECK_EXCEPTION(env);
460 g_camera = (jobject)env->NewGlobalRef(camera_tmp);
461
462 rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
463 g_peer_connection_factory->CreateVideoTrack(kVideoLabel,
Magnus Jedvert167316b2019-01-31 13:23:46 +0100464 source.release()));
qiangchen42f96d52017-08-08 17:08:03 -0700465 stream->AddTrack(video_track);
466#else
Niels Möller0a595352019-01-02 15:12:38 +0100467 rtc::scoped_refptr<CapturerTrackSource> video_device =
468 CapturerTrackSource::Create();
469 if (video_device) {
gyzhouad7cad82017-05-11 16:10:03 -0700470 rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
Niels Möller0a595352019-01-02 15:12:38 +0100471 g_peer_connection_factory->CreateVideoTrack(kVideoLabel,
472 video_device));
gyzhouad7cad82017-05-11 16:10:03 -0700473
474 stream->AddTrack(video_track);
qiangchen42f96d52017-08-08 17:08:03 -0700475 }
476#endif
477 if (local_video_observer_ && !stream->GetVideoTracks().empty()) {
478 stream->GetVideoTracks()[0]->AddOrUpdateSink(local_video_observer_.get(),
479 rtc::VideoSinkWants());
gyzhouad7cad82017-05-11 16:10:03 -0700480 }
481 }
482
483 if (!peer_connection_->AddStream(stream)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100484 RTC_LOG(LS_ERROR) << "Adding stream to PeerConnection failed";
gyzhouad7cad82017-05-11 16:10:03 -0700485 }
486
487 typedef std::pair<std::string,
488 rtc::scoped_refptr<webrtc::MediaStreamInterface>>
489 MediaStreamPair;
Seth Hampson13b8bad2018-03-13 16:05:28 -0700490 active_streams_.insert(MediaStreamPair(stream->id(), stream));
gyzhouad7cad82017-05-11 16:10:03 -0700491}
492
493bool SimplePeerConnection::CreateDataChannel() {
494 struct webrtc::DataChannelInit init;
495 init.ordered = true;
496 init.reliable = true;
497 data_channel_ = peer_connection_->CreateDataChannel("Hello", &init);
498 if (data_channel_.get()) {
499 data_channel_->RegisterObserver(this);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100500 RTC_LOG(LS_INFO) << "Succeeds to create data channel";
gyzhouad7cad82017-05-11 16:10:03 -0700501 return true;
502 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_INFO) << "Fails to create data channel";
gyzhouad7cad82017-05-11 16:10:03 -0700504 return false;
505 }
506}
507
508void SimplePeerConnection::CloseDataChannel() {
509 if (data_channel_.get()) {
510 data_channel_->UnregisterObserver();
511 data_channel_->Close();
512 }
513 data_channel_ = nullptr;
514}
515
516bool SimplePeerConnection::SendDataViaDataChannel(const std::string& data) {
517 if (!data_channel_.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100518 RTC_LOG(LS_INFO) << "Data channel is not established";
gyzhouad7cad82017-05-11 16:10:03 -0700519 return false;
520 }
521 webrtc::DataBuffer buffer(data);
522 data_channel_->Send(buffer);
523 return true;
524}
525
526// Peerconnection observer
527void SimplePeerConnection::OnDataChannel(
528 rtc::scoped_refptr<webrtc::DataChannelInterface> channel) {
529 channel->RegisterObserver(this);
530}
531
532void SimplePeerConnection::OnStateChange() {
533 if (data_channel_) {
534 webrtc::DataChannelInterface::DataState state = data_channel_->state();
535 if (state == webrtc::DataChannelInterface::kOpen) {
536 if (OnLocalDataChannelReady)
537 OnLocalDataChannelReady();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100538 RTC_LOG(LS_INFO) << "Data channel is open";
gyzhouad7cad82017-05-11 16:10:03 -0700539 }
540 }
541}
542
543// A data buffer was successfully received.
544void SimplePeerConnection::OnMessage(const webrtc::DataBuffer& buffer) {
545 size_t size = buffer.data.size();
546 char* msg = new char[size + 1];
547 memcpy(msg, buffer.data.data(), size);
548 msg[size] = 0;
549 if (OnDataFromDataChannelReady)
550 OnDataFromDataChannelReady(msg);
551 delete[] msg;
552}
553
554// AudioTrackSinkInterface implementation.
555void SimplePeerConnection::OnData(const void* audio_data,
556 int bits_per_sample,
557 int sample_rate,
558 size_t number_of_channels,
559 size_t number_of_frames) {
560 if (OnAudioReady)
561 OnAudioReady(audio_data, bits_per_sample, sample_rate,
562 static_cast<int>(number_of_channels),
563 static_cast<int>(number_of_frames));
564}
565
566std::vector<uint32_t> SimplePeerConnection::GetRemoteAudioTrackSsrcs() {
567 std::vector<rtc::scoped_refptr<webrtc::RtpReceiverInterface>> receivers =
568 peer_connection_->GetReceivers();
569
570 std::vector<uint32_t> ssrcs;
571 for (const auto& receiver : receivers) {
572 if (receiver->media_type() != cricket::MEDIA_TYPE_AUDIO)
573 continue;
574
575 std::vector<webrtc::RtpEncodingParameters> params =
576 receiver->GetParameters().encodings;
577
578 for (const auto& param : params) {
579 uint32_t ssrc = param.ssrc.value_or(0);
580 if (ssrc > 0)
581 ssrcs.push_back(ssrc);
582 }
583 }
584
585 return ssrcs;
586}