blob: 657bce2df6132d70cb02333a1269169d4aa5bcbe [file] [log] [blame]
Sami Kalliomäki3e77afd2018-03-08 16:43:16 +01001/*
2 * Copyright 2018 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "examples/androidnativeapi/jni/androidcallclient.h"
12
13#include <utility>
14
15#include "api/audio_codecs/builtin_audio_decoder_factory.h"
16#include "api/audio_codecs/builtin_audio_encoder_factory.h"
17#include "api/peerconnectioninterface.h"
18#include "examples/androidnativeapi/generated_jni/jni/CallClient_jni.h"
19#include "media/engine/internaldecoderfactory.h"
20#include "media/engine/internalencoderfactory.h"
21#include "media/engine/webrtcmediaengine.h"
22#include "modules/audio_processing/include/audio_processing.h"
23#include "pc/test/fakeperiodicvideocapturer.h"
24#include "rtc_base/ptr_util.h"
25#include "sdk/android/native_api/jni/java_types.h"
26#include "sdk/android/native_api/video/wrapper.h"
27
28namespace webrtc_examples {
29
30class AndroidCallClient::PCObserver : public webrtc::PeerConnectionObserver {
31 public:
32 explicit PCObserver(AndroidCallClient* client);
33
34 void OnSignalingChange(
35 webrtc::PeerConnectionInterface::SignalingState new_state) override;
36 void OnDataChannel(
37 rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) override;
38 void OnRenegotiationNeeded() override;
39 void OnIceConnectionChange(
40 webrtc::PeerConnectionInterface::IceConnectionState new_state) override;
41 void OnIceGatheringChange(
42 webrtc::PeerConnectionInterface::IceGatheringState new_state) override;
43 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override;
44
45 private:
46 const AndroidCallClient* client_;
47};
48
49namespace {
50
51class CreateOfferObserver : public webrtc::CreateSessionDescriptionObserver {
52 public:
53 explicit CreateOfferObserver(
54 rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc);
55
56 void OnSuccess(webrtc::SessionDescriptionInterface* desc) override;
57 void OnFailure(const std::string& error) override;
58
59 private:
60 const rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc_;
61};
62
63class SetRemoteSessionDescriptionObserver
64 : public webrtc::SetRemoteDescriptionObserverInterface {
65 public:
66 void OnSetRemoteDescriptionComplete(webrtc::RTCError error) override;
67};
68
69class SetLocalSessionDescriptionObserver
70 : public webrtc::SetSessionDescriptionObserver {
71 public:
72 void OnSuccess() override;
73 void OnFailure(const std::string& error) override;
74};
75
76} // namespace
77
78AndroidCallClient::AndroidCallClient()
79 : call_started_(false), pc_observer_(rtc::MakeUnique<PCObserver>(this)) {
80 thread_checker_.DetachFromThread();
81 CreatePeerConnectionFactory();
82}
83
84void AndroidCallClient::Call(JNIEnv* env,
85 const webrtc::JavaRef<jobject>& cls,
86 const webrtc::JavaRef<jobject>& local_sink,
87 const webrtc::JavaRef<jobject>& remote_sink) {
88 RTC_DCHECK_RUN_ON(&thread_checker_);
89
90 rtc::CritScope lock(&pc_mutex_);
91 if (call_started_) {
92 RTC_LOG(LS_WARNING) << "Call already started.";
93 return;
94 }
95 call_started_ = true;
96
97 local_sink_ = webrtc::JavaToNativeVideoSink(env, local_sink.obj());
98 remote_sink_ = webrtc::JavaToNativeVideoSink(env, remote_sink.obj());
99
100 // The fake video source wants to be created on the same thread as it is
101 // destroyed. It is destroyed on the signaling thread so we have to invoke
102 // here.
103 // TODO(sakal): Get picture from camera?
104 video_source_ = pcf_->CreateVideoSource(
105 signaling_thread_
106 ->Invoke<std::unique_ptr<webrtc::FakePeriodicVideoCapturer>>(
107 RTC_FROM_HERE, [&] {
108 return rtc::MakeUnique<webrtc::FakePeriodicVideoCapturer>();
109 }));
110
111 CreatePeerConnection();
112 Connect();
113}
114
115void AndroidCallClient::Hangup(JNIEnv* env,
116 const webrtc::JavaRef<jobject>& cls) {
117 RTC_DCHECK_RUN_ON(&thread_checker_);
118
119 call_started_ = false;
120
121 {
122 rtc::CritScope lock(&pc_mutex_);
123 if (pc_ != nullptr) {
124 pc_->Close();
125 pc_ = nullptr;
126 }
127 }
128
129 local_sink_ = nullptr;
130 remote_sink_ = nullptr;
131 video_source_ = nullptr;
132}
133
134void AndroidCallClient::Delete(JNIEnv* env,
135 const webrtc::JavaRef<jobject>& cls) {
136 RTC_DCHECK_RUN_ON(&thread_checker_);
137
138 delete this;
139}
140
141void AndroidCallClient::CreatePeerConnectionFactory() {
142 network_thread_ = rtc::Thread::CreateWithSocketServer();
143 network_thread_->SetName("network_thread", nullptr);
144 RTC_CHECK(network_thread_->Start()) << "Failed to start thread";
145
146 worker_thread_ = rtc::Thread::Create();
147 worker_thread_->SetName("worker_thread", nullptr);
148 RTC_CHECK(worker_thread_->Start()) << "Failed to start thread";
149
150 signaling_thread_ = rtc::Thread::Create();
151 signaling_thread_->SetName("signaling_thread", nullptr);
152 RTC_CHECK(signaling_thread_->Start()) << "Failed to start thread";
153
154 std::unique_ptr<cricket::MediaEngineInterface> media_engine =
155 cricket::WebRtcMediaEngineFactory::Create(
156 nullptr /* adm */, webrtc::CreateBuiltinAudioEncoderFactory(),
157 webrtc::CreateBuiltinAudioDecoderFactory(),
158 rtc::MakeUnique<webrtc::InternalEncoderFactory>(),
159 rtc::MakeUnique<webrtc::InternalDecoderFactory>(),
160 nullptr /* audio_mixer */, webrtc::AudioProcessingBuilder().Create());
161 RTC_LOG(LS_INFO) << "Media engine created: " << media_engine.get();
162
163 pcf_ = CreateModularPeerConnectionFactory(
164 network_thread_.get(), worker_thread_.get(), signaling_thread_.get(),
165 std::move(media_engine), webrtc::CreateCallFactory(),
166 webrtc::CreateRtcEventLogFactory());
167 RTC_LOG(LS_INFO) << "PeerConnectionFactory created: " << pcf_;
168}
169
170void AndroidCallClient::CreatePeerConnection() {
171 rtc::CritScope lock(&pc_mutex_);
172 webrtc::PeerConnectionInterface::RTCConfiguration config;
173 config.sdp_semantics = webrtc::SdpSemantics::kUnifiedPlan;
174 // DTLS SRTP has to be disabled for loopback to work.
175 config.enable_dtls_srtp = false;
176 pc_ = pcf_->CreatePeerConnection(config, nullptr /* port_allocator */,
177 nullptr /* cert_generator */,
178 pc_observer_.get());
179 RTC_LOG(LS_INFO) << "PeerConnection created: " << pc_;
180
181 rtc::scoped_refptr<webrtc::VideoTrackInterface> local_video_track =
182 pcf_->CreateVideoTrack("video", video_source_);
183 local_video_track->AddOrUpdateSink(local_sink_.get(), rtc::VideoSinkWants());
184 pc_->AddTransceiver(local_video_track);
185 RTC_LOG(LS_INFO) << "Local video sink set up: " << local_video_track;
186
187 for (const rtc::scoped_refptr<webrtc::RtpTransceiverInterface>& tranceiver :
188 pc_->GetTransceivers()) {
189 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track =
190 tranceiver->receiver()->track();
191 if (track &&
192 track->kind() == webrtc::MediaStreamTrackInterface::kVideoKind) {
193 static_cast<webrtc::VideoTrackInterface*>(track.get())
194 ->AddOrUpdateSink(remote_sink_.get(), rtc::VideoSinkWants());
195 RTC_LOG(LS_INFO) << "Remote video sink set up: " << track;
196 break;
197 }
198 }
199}
200
201void AndroidCallClient::Connect() {
202 rtc::CritScope lock(&pc_mutex_);
203 pc_->CreateOffer(new rtc::RefCountedObject<CreateOfferObserver>(pc_),
204 webrtc::PeerConnectionInterface::RTCOfferAnswerOptions());
205}
206
207AndroidCallClient::PCObserver::PCObserver(AndroidCallClient* client)
208 : client_(client) {}
209
210void AndroidCallClient::PCObserver::OnSignalingChange(
211 webrtc::PeerConnectionInterface::SignalingState new_state) {
212 RTC_LOG(LS_INFO) << "OnSignalingChange: " << new_state;
213}
214
215void AndroidCallClient::PCObserver::OnDataChannel(
216 rtc::scoped_refptr<webrtc::DataChannelInterface> data_channel) {
217 RTC_LOG(LS_INFO) << "OnDataChannel";
218}
219
220void AndroidCallClient::PCObserver::OnRenegotiationNeeded() {
221 RTC_LOG(LS_INFO) << "OnRenegotiationNeeded";
222}
223
224void AndroidCallClient::PCObserver::OnIceConnectionChange(
225 webrtc::PeerConnectionInterface::IceConnectionState new_state) {
226 RTC_LOG(LS_INFO) << "OnIceConnectionChange: " << new_state;
227}
228
229void AndroidCallClient::PCObserver::OnIceGatheringChange(
230 webrtc::PeerConnectionInterface::IceGatheringState new_state) {
231 RTC_LOG(LS_INFO) << "OnIceGatheringChange: " << new_state;
232}
233
234void AndroidCallClient::PCObserver::OnIceCandidate(
235 const webrtc::IceCandidateInterface* candidate) {
236 RTC_LOG(LS_INFO) << "OnIceCandidate: " << candidate->server_url();
237 rtc::CritScope lock(&client_->pc_mutex_);
238 RTC_DCHECK(client_->pc_ != nullptr);
239 client_->pc_->AddIceCandidate(candidate);
240}
241
242CreateOfferObserver::CreateOfferObserver(
243 rtc::scoped_refptr<webrtc::PeerConnectionInterface> pc)
244 : pc_(pc) {}
245
246void CreateOfferObserver::OnSuccess(webrtc::SessionDescriptionInterface* desc) {
247 std::string sdp;
248 desc->ToString(&sdp);
249 RTC_LOG(LS_INFO) << "Created offer: " << sdp;
250
251 // Ownership of desc was transferred to us, now we transfer it forward.
252 pc_->SetLocalDescription(
253 new rtc::RefCountedObject<SetLocalSessionDescriptionObserver>(), desc);
254
255 // Generate a fake answer.
256 std::unique_ptr<webrtc::SessionDescriptionInterface> answer(
257 webrtc::CreateSessionDescription(webrtc::SdpType::kAnswer, sdp));
258 pc_->SetRemoteDescription(
259 std::move(answer),
260 new rtc::RefCountedObject<SetRemoteSessionDescriptionObserver>());
261}
262
263void CreateOfferObserver::OnFailure(const std::string& error) {
264 RTC_LOG(LS_INFO) << "Failed to create offer: " << error;
265}
266
267void SetRemoteSessionDescriptionObserver::OnSetRemoteDescriptionComplete(
268 webrtc::RTCError error) {
269 RTC_LOG(LS_INFO) << "Set remote description: " << error.message();
270}
271
272void SetLocalSessionDescriptionObserver::OnSuccess() {
273 RTC_LOG(LS_INFO) << "Set local description success!";
274}
275
276void SetLocalSessionDescriptionObserver::OnFailure(const std::string& error) {
277 RTC_LOG(LS_INFO) << "Set local description failure: " << error;
278}
279
280} // namespace webrtc_examples
281
282static jlong JNI_CallClient_CreateClient(
283 JNIEnv* env,
284 const webrtc::JavaParamRef<jclass>& cls) {
285 return webrtc::NativeToJavaPointer(new webrtc_examples::AndroidCallClient());
286}