blob: 536bf86a014644ecc9173f5681b74fa1570ea986 [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) {
Erik Språng6e70f182019-05-16 10:27:17 +0000125 g_worker_thread.reset(new rtc::Thread());
gyzhouad7cad82017-05-11 16:10:03 -0700126 g_worker_thread->Start();
Erik Språng6e70f182019-05-16 10:27:17 +0000127 g_signaling_thread.reset(new rtc::Thread());
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(
Karl Wiberg918f50c2018-07-05 11:40:33 +0200136 absl::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(
Karl Wiberg918f50c2018-07-05 11:40:33 +0200139 absl::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);
339 std::string sdp_type(type);
gyzhouad7cad82017-05-11 16:10:03 -0700340 webrtc::SdpParseError error;
341 webrtc::SessionDescriptionInterface* session_description(
gyzhoub38f3862017-07-25 16:04:31 -0700342 webrtc::CreateSessionDescription(sdp_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. "
345 << "SdpParseError was: " << 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. "
366 << "SdpParseError was: " << error.description;
gyzhouad7cad82017-05-11 16:10:03 -0700367 return false;
368 }
gyzhoub38f3862017-07-25 16:04:31 -0700369 if (!peer_connection_->AddIceCandidate(ice_candidate.get())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100370 RTC_LOG(WARNING) << "Failed to apply the received candidate";
gyzhouad7cad82017-05-11 16:10:03 -0700371 return false;
372 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100373 RTC_LOG(INFO) << " Received candidate :" << candidate;
gyzhouad7cad82017-05-11 16:10:03 -0700374 return true;
375}
376
377void SimplePeerConnection::SetAudioControl(bool is_mute, bool is_record) {
378 is_mute_audio_ = is_mute;
379 is_record_audio_ = is_record;
380
381 SetAudioControl();
382}
383
384void SimplePeerConnection::SetAudioControl() {
385 if (!remote_stream_)
386 return;
387 webrtc::AudioTrackVector tracks = remote_stream_->GetAudioTracks();
388 if (tracks.empty())
389 return;
390
391 webrtc::AudioTrackInterface* audio_track = tracks[0];
392 std::string id = audio_track->id();
393 if (is_record_audio_)
394 audio_track->AddSink(this);
395 else
396 audio_track->RemoveSink(this);
397
398 for (auto& track : tracks) {
399 if (is_mute_audio_)
400 track->set_enabled(false);
401 else
402 track->set_enabled(true);
403 }
404}
405
406void SimplePeerConnection::OnAddStream(
407 rtc::scoped_refptr<webrtc::MediaStreamInterface> stream) {
Seth Hampson13b8bad2018-03-13 16:05:28 -0700408 RTC_LOG(INFO) << __FUNCTION__ << " " << stream->id();
gyzhouad7cad82017-05-11 16:10:03 -0700409 remote_stream_ = stream;
gyzhoub38f3862017-07-25 16:04:31 -0700410 if (remote_video_observer_ && !remote_stream_->GetVideoTracks().empty()) {
411 remote_stream_->GetVideoTracks()[0]->AddOrUpdateSink(
412 remote_video_observer_.get(), rtc::VideoSinkWants());
413 }
gyzhouad7cad82017-05-11 16:10:03 -0700414 SetAudioControl();
415}
416
gyzhouad7cad82017-05-11 16:10:03 -0700417void SimplePeerConnection::AddStreams(bool audio_only) {
Seth Hampson513449e2018-03-06 09:35:56 -0800418 if (active_streams_.find(kStreamId) != active_streams_.end())
gyzhouad7cad82017-05-11 16:10:03 -0700419 return; // Already added.
420
421 rtc::scoped_refptr<webrtc::MediaStreamInterface> stream =
Seth Hampson513449e2018-03-06 09:35:56 -0800422 g_peer_connection_factory->CreateLocalMediaStream(kStreamId);
gyzhouad7cad82017-05-11 16:10:03 -0700423
424 rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(
425 g_peer_connection_factory->CreateAudioTrack(
Niels Möller2d02e082018-05-21 11:23:35 +0200426 kAudioLabel, g_peer_connection_factory->CreateAudioSource(
427 cricket::AudioOptions())));
gyzhouad7cad82017-05-11 16:10:03 -0700428 std::string id = audio_track->id();
429 stream->AddTrack(audio_track);
430
431 if (!audio_only) {
qiangchen42f96d52017-08-08 17:08:03 -0700432#if defined(WEBRTC_ANDROID)
magjeda3d4f682017-08-28 16:24:06 -0700433 JNIEnv* env = webrtc::jni::GetEnv();
qiangchen42f96d52017-08-08 17:08:03 -0700434 jclass pc_factory_class =
435 unity_plugin::FindClass(env, "org/webrtc/UnityUtility");
George Zhou2770c3d2018-03-07 09:58:54 -0800436 jmethodID load_texture_helper_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700437 env, pc_factory_class, "LoadSurfaceTextureHelper",
438 "()Lorg/webrtc/SurfaceTextureHelper;");
439 jobject texture_helper = env->CallStaticObjectMethod(
440 pc_factory_class, load_texture_helper_method);
441 CHECK_EXCEPTION(env);
442 RTC_DCHECK(texture_helper != nullptr)
443 << "Cannot get the Surface Texture Helper.";
444
Qiang Chen51e20462017-12-05 11:11:21 -0800445 rtc::scoped_refptr<webrtc::jni::AndroidVideoTrackSource> source(
446 new rtc::RefCountedObject<webrtc::jni::AndroidVideoTrackSource>(
Magnus Jedvert95140712018-11-15 12:07:32 +0100447 g_signaling_thread.get(), env, /* is_screencast= */ false,
448 /* align_timestamps= */ true));
qiangchen42f96d52017-08-08 17:08:03 -0700449
450 // link with VideoCapturer (Camera);
George Zhou2770c3d2018-03-07 09:58:54 -0800451 jmethodID link_camera_method = webrtc::GetStaticMethodID(
qiangchen42f96d52017-08-08 17:08:03 -0700452 env, pc_factory_class, "LinkCamera",
453 "(JLorg/webrtc/SurfaceTextureHelper;)Lorg/webrtc/VideoCapturer;");
454 jobject camera_tmp =
455 env->CallStaticObjectMethod(pc_factory_class, link_camera_method,
Magnus Jedvert167316b2019-01-31 13:23:46 +0100456 (jlong)source.get(), texture_helper);
qiangchen42f96d52017-08-08 17:08:03 -0700457 CHECK_EXCEPTION(env);
458 g_camera = (jobject)env->NewGlobalRef(camera_tmp);
459
460 rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
461 g_peer_connection_factory->CreateVideoTrack(kVideoLabel,
Magnus Jedvert167316b2019-01-31 13:23:46 +0100462 source.release()));
qiangchen42f96d52017-08-08 17:08:03 -0700463 stream->AddTrack(video_track);
464#else
Niels Möller0a595352019-01-02 15:12:38 +0100465 rtc::scoped_refptr<CapturerTrackSource> video_device =
466 CapturerTrackSource::Create();
467 if (video_device) {
gyzhouad7cad82017-05-11 16:10:03 -0700468 rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(
Niels Möller0a595352019-01-02 15:12:38 +0100469 g_peer_connection_factory->CreateVideoTrack(kVideoLabel,
470 video_device));
gyzhouad7cad82017-05-11 16:10:03 -0700471
472 stream->AddTrack(video_track);
qiangchen42f96d52017-08-08 17:08:03 -0700473 }
474#endif
475 if (local_video_observer_ && !stream->GetVideoTracks().empty()) {
476 stream->GetVideoTracks()[0]->AddOrUpdateSink(local_video_observer_.get(),
477 rtc::VideoSinkWants());
gyzhouad7cad82017-05-11 16:10:03 -0700478 }
479 }
480
481 if (!peer_connection_->AddStream(stream)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100482 RTC_LOG(LS_ERROR) << "Adding stream to PeerConnection failed";
gyzhouad7cad82017-05-11 16:10:03 -0700483 }
484
485 typedef std::pair<std::string,
486 rtc::scoped_refptr<webrtc::MediaStreamInterface>>
487 MediaStreamPair;
Seth Hampson13b8bad2018-03-13 16:05:28 -0700488 active_streams_.insert(MediaStreamPair(stream->id(), stream));
gyzhouad7cad82017-05-11 16:10:03 -0700489}
490
491bool SimplePeerConnection::CreateDataChannel() {
492 struct webrtc::DataChannelInit init;
493 init.ordered = true;
494 init.reliable = true;
495 data_channel_ = peer_connection_->CreateDataChannel("Hello", &init);
496 if (data_channel_.get()) {
497 data_channel_->RegisterObserver(this);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_INFO) << "Succeeds to create data channel";
gyzhouad7cad82017-05-11 16:10:03 -0700499 return true;
500 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100501 RTC_LOG(LS_INFO) << "Fails to create data channel";
gyzhouad7cad82017-05-11 16:10:03 -0700502 return false;
503 }
504}
505
506void SimplePeerConnection::CloseDataChannel() {
507 if (data_channel_.get()) {
508 data_channel_->UnregisterObserver();
509 data_channel_->Close();
510 }
511 data_channel_ = nullptr;
512}
513
514bool SimplePeerConnection::SendDataViaDataChannel(const std::string& data) {
515 if (!data_channel_.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100516 RTC_LOG(LS_INFO) << "Data channel is not established";
gyzhouad7cad82017-05-11 16:10:03 -0700517 return false;
518 }
519 webrtc::DataBuffer buffer(data);
520 data_channel_->Send(buffer);
521 return true;
522}
523
524// Peerconnection observer
525void SimplePeerConnection::OnDataChannel(
526 rtc::scoped_refptr<webrtc::DataChannelInterface> channel) {
527 channel->RegisterObserver(this);
528}
529
530void SimplePeerConnection::OnStateChange() {
531 if (data_channel_) {
532 webrtc::DataChannelInterface::DataState state = data_channel_->state();
533 if (state == webrtc::DataChannelInterface::kOpen) {
534 if (OnLocalDataChannelReady)
535 OnLocalDataChannelReady();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100536 RTC_LOG(LS_INFO) << "Data channel is open";
gyzhouad7cad82017-05-11 16:10:03 -0700537 }
538 }
539}
540
541// A data buffer was successfully received.
542void SimplePeerConnection::OnMessage(const webrtc::DataBuffer& buffer) {
543 size_t size = buffer.data.size();
544 char* msg = new char[size + 1];
545 memcpy(msg, buffer.data.data(), size);
546 msg[size] = 0;
547 if (OnDataFromDataChannelReady)
548 OnDataFromDataChannelReady(msg);
549 delete[] msg;
550}
551
552// AudioTrackSinkInterface implementation.
553void SimplePeerConnection::OnData(const void* audio_data,
554 int bits_per_sample,
555 int sample_rate,
556 size_t number_of_channels,
557 size_t number_of_frames) {
558 if (OnAudioReady)
559 OnAudioReady(audio_data, bits_per_sample, sample_rate,
560 static_cast<int>(number_of_channels),
561 static_cast<int>(number_of_frames));
562}
563
564std::vector<uint32_t> SimplePeerConnection::GetRemoteAudioTrackSsrcs() {
565 std::vector<rtc::scoped_refptr<webrtc::RtpReceiverInterface>> receivers =
566 peer_connection_->GetReceivers();
567
568 std::vector<uint32_t> ssrcs;
569 for (const auto& receiver : receivers) {
570 if (receiver->media_type() != cricket::MEDIA_TYPE_AUDIO)
571 continue;
572
573 std::vector<webrtc::RtpEncodingParameters> params =
574 receiver->GetParameters().encodings;
575
576 for (const auto& param : params) {
577 uint32_t ssrc = param.ssrc.value_or(0);
578 if (ssrc > 0)
579 ssrcs.push_back(ssrc);
580 }
581 }
582
583 return ssrcs;
584}