Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(164)

Side by Side Diff: webrtc/api/peerconnection_unittest.cc

Issue 2514883002: Create //webrtc/api:libjingle_peerconnection_api + refactorings. (Closed)
Patch Set: Added three headers for backwards-compatibility, specifically for building chromium. Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 * Copyright 2012 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 <stdio.h>
12
13 #include <algorithm>
14 #include <list>
15 #include <map>
16 #include <memory>
17 #include <utility>
18 #include <vector>
19
20 #include "webrtc/api/dtmfsender.h"
21 #include "webrtc/api/fakemetricsobserver.h"
22 #include "webrtc/api/localaudiosource.h"
23 #include "webrtc/api/mediastreaminterface.h"
24 #include "webrtc/api/peerconnection.h"
25 #include "webrtc/api/peerconnectionfactory.h"
26 #include "webrtc/api/peerconnectioninterface.h"
27 #include "webrtc/api/test/fakeaudiocapturemodule.h"
28 #include "webrtc/api/test/fakeconstraints.h"
29 #include "webrtc/api/test/fakeperiodicvideocapturer.h"
30 #include "webrtc/api/test/fakertccertificategenerator.h"
31 #include "webrtc/api/test/fakevideotrackrenderer.h"
32 #include "webrtc/api/test/mockpeerconnectionobservers.h"
33 #include "webrtc/base/fakenetwork.h"
34 #include "webrtc/base/gunit.h"
35 #include "webrtc/base/helpers.h"
36 #include "webrtc/base/physicalsocketserver.h"
37 #include "webrtc/base/ssladapter.h"
38 #include "webrtc/base/sslstreamadapter.h"
39 #include "webrtc/base/thread.h"
40 #include "webrtc/base/virtualsocketserver.h"
41 #include "webrtc/media/engine/fakewebrtcvideoengine.h"
42 #include "webrtc/p2p/base/p2pconstants.h"
43 #include "webrtc/p2p/base/sessiondescription.h"
44 #include "webrtc/p2p/base/testturnserver.h"
45 #include "webrtc/p2p/client/basicportallocator.h"
46 #include "webrtc/pc/mediasession.h"
47
48 #define MAYBE_SKIP_TEST(feature) \
49 if (!(feature())) { \
50 LOG(LS_INFO) << "Feature disabled... skipping"; \
51 return; \
52 }
53
54 using cricket::ContentInfo;
55 using cricket::FakeWebRtcVideoDecoder;
56 using cricket::FakeWebRtcVideoDecoderFactory;
57 using cricket::FakeWebRtcVideoEncoder;
58 using cricket::FakeWebRtcVideoEncoderFactory;
59 using cricket::MediaContentDescription;
60 using webrtc::DataBuffer;
61 using webrtc::DataChannelInterface;
62 using webrtc::DtmfSender;
63 using webrtc::DtmfSenderInterface;
64 using webrtc::DtmfSenderObserverInterface;
65 using webrtc::FakeConstraints;
66 using webrtc::MediaConstraintsInterface;
67 using webrtc::MediaStreamInterface;
68 using webrtc::MediaStreamTrackInterface;
69 using webrtc::MockCreateSessionDescriptionObserver;
70 using webrtc::MockDataChannelObserver;
71 using webrtc::MockSetSessionDescriptionObserver;
72 using webrtc::MockStatsObserver;
73 using webrtc::ObserverInterface;
74 using webrtc::PeerConnectionInterface;
75 using webrtc::PeerConnectionFactory;
76 using webrtc::SessionDescriptionInterface;
77 using webrtc::StreamCollectionInterface;
78
79 namespace {
80
81 static const int kMaxWaitMs = 10000;
82 // Disable for TSan v2, see
83 // https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
84 // This declaration is also #ifdef'd as it causes uninitialized-variable
85 // warnings.
86 #if !defined(THREAD_SANITIZER)
87 static const int kMaxWaitForStatsMs = 3000;
88 #endif
89 static const int kMaxWaitForActivationMs = 5000;
90 static const int kMaxWaitForFramesMs = 10000;
91 static const int kEndAudioFrameCount = 3;
92 static const int kEndVideoFrameCount = 3;
93
94 static const char kStreamLabelBase[] = "stream_label";
95 static const char kVideoTrackLabelBase[] = "video_track";
96 static const char kAudioTrackLabelBase[] = "audio_track";
97 static const char kDataChannelLabel[] = "data_channel";
98
99 // Disable for TSan v2, see
100 // https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
101 // This declaration is also #ifdef'd as it causes unused-variable errors.
102 #if !defined(THREAD_SANITIZER)
103 // SRTP cipher name negotiated by the tests. This must be updated if the
104 // default changes.
105 static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_32;
106 static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
107 #endif
108
109 // Used to simulate signaling ICE/SDP between two PeerConnections.
110 enum Message { MSG_SDP_MESSAGE, MSG_ICE_MESSAGE };
111
112 struct SdpMessage {
113 std::string type;
114 std::string msg;
115 };
116
117 struct IceMessage {
118 std::string sdp_mid;
119 int sdp_mline_index;
120 std::string msg;
121 };
122
123 static void RemoveLinesFromSdp(const std::string& line_start,
124 std::string* sdp) {
125 const char kSdpLineEnd[] = "\r\n";
126 size_t ssrc_pos = 0;
127 while ((ssrc_pos = sdp->find(line_start, ssrc_pos)) !=
128 std::string::npos) {
129 size_t end_ssrc = sdp->find(kSdpLineEnd, ssrc_pos);
130 sdp->erase(ssrc_pos, end_ssrc - ssrc_pos + strlen(kSdpLineEnd));
131 }
132 }
133
134 bool StreamsHaveAudioTrack(StreamCollectionInterface* streams) {
135 for (size_t idx = 0; idx < streams->count(); idx++) {
136 auto stream = streams->at(idx);
137 if (stream->GetAudioTracks().size() > 0) {
138 return true;
139 }
140 }
141 return false;
142 }
143
144 bool StreamsHaveVideoTrack(StreamCollectionInterface* streams) {
145 for (size_t idx = 0; idx < streams->count(); idx++) {
146 auto stream = streams->at(idx);
147 if (stream->GetVideoTracks().size() > 0) {
148 return true;
149 }
150 }
151 return false;
152 }
153
154 class SignalingMessageReceiver {
155 public:
156 virtual void ReceiveSdpMessage(const std::string& type,
157 std::string& msg) = 0;
158 virtual void ReceiveIceMessage(const std::string& sdp_mid,
159 int sdp_mline_index,
160 const std::string& msg) = 0;
161
162 protected:
163 SignalingMessageReceiver() {}
164 virtual ~SignalingMessageReceiver() {}
165 };
166
167 class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
168 public:
169 MockRtpReceiverObserver(cricket::MediaType media_type)
170 : expected_media_type_(media_type) {}
171
172 void OnFirstPacketReceived(cricket::MediaType media_type) override {
173 ASSERT_EQ(expected_media_type_, media_type);
174 first_packet_received_ = true;
175 }
176
177 bool first_packet_received() { return first_packet_received_; }
178
179 virtual ~MockRtpReceiverObserver() {}
180
181 private:
182 bool first_packet_received_ = false;
183 cricket::MediaType expected_media_type_;
184 };
185
186 class PeerConnectionTestClient : public webrtc::PeerConnectionObserver,
187 public SignalingMessageReceiver,
188 public ObserverInterface,
189 public rtc::MessageHandler {
190 public:
191 // We need these using declarations because there are two versions of each of
192 // the below methods and we only override one of them.
193 // TODO(deadbeef): Remove once there's only one version of the methods.
194 using PeerConnectionObserver::OnAddStream;
195 using PeerConnectionObserver::OnRemoveStream;
196 using PeerConnectionObserver::OnDataChannel;
197
198 // If |config| is not provided, uses a default constructed RTCConfiguration.
199 static PeerConnectionTestClient* CreateClientWithDtlsIdentityStore(
200 const std::string& id,
201 const MediaConstraintsInterface* constraints,
202 const PeerConnectionFactory::Options* options,
203 const PeerConnectionInterface::RTCConfiguration* config,
204 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
205 bool prefer_constraint_apis,
206 rtc::Thread* network_thread,
207 rtc::Thread* worker_thread) {
208 PeerConnectionTestClient* client(new PeerConnectionTestClient(id));
209 if (!client->Init(constraints, options, config, std::move(cert_generator),
210 prefer_constraint_apis, network_thread, worker_thread)) {
211 delete client;
212 return nullptr;
213 }
214 return client;
215 }
216
217 static PeerConnectionTestClient* CreateClient(
218 const std::string& id,
219 const MediaConstraintsInterface* constraints,
220 const PeerConnectionFactory::Options* options,
221 const PeerConnectionInterface::RTCConfiguration* config,
222 rtc::Thread* network_thread,
223 rtc::Thread* worker_thread) {
224 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
225 rtc::SSLStreamAdapter::HaveDtlsSrtp() ?
226 new FakeRTCCertificateGenerator() : nullptr);
227
228 return CreateClientWithDtlsIdentityStore(id, constraints, options, config,
229 std::move(cert_generator), true,
230 network_thread, worker_thread);
231 }
232
233 static PeerConnectionTestClient* CreateClientPreferNoConstraints(
234 const std::string& id,
235 const PeerConnectionFactory::Options* options,
236 rtc::Thread* network_thread,
237 rtc::Thread* worker_thread) {
238 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
239 rtc::SSLStreamAdapter::HaveDtlsSrtp() ?
240 new FakeRTCCertificateGenerator() : nullptr);
241
242 return CreateClientWithDtlsIdentityStore(id, nullptr, options, nullptr,
243 std::move(cert_generator), false,
244 network_thread, worker_thread);
245 }
246
247 ~PeerConnectionTestClient() {
248 }
249
250 void Negotiate() { Negotiate(true, true); }
251
252 void Negotiate(bool audio, bool video) {
253 std::unique_ptr<SessionDescriptionInterface> offer;
254 ASSERT_TRUE(DoCreateOffer(&offer));
255
256 if (offer->description()->GetContentByName("audio")) {
257 offer->description()->GetContentByName("audio")->rejected = !audio;
258 }
259 if (offer->description()->GetContentByName("video")) {
260 offer->description()->GetContentByName("video")->rejected = !video;
261 }
262
263 std::string sdp;
264 EXPECT_TRUE(offer->ToString(&sdp));
265 EXPECT_TRUE(DoSetLocalDescription(offer.release()));
266 SendSdpMessage(webrtc::SessionDescriptionInterface::kOffer, sdp);
267 }
268
269 void SendSdpMessage(const std::string& type, std::string& msg) {
270 if (signaling_delay_ms_ == 0) {
271 if (signaling_message_receiver_) {
272 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
273 }
274 } else {
275 rtc::Thread::Current()->PostDelayed(
276 RTC_FROM_HERE, signaling_delay_ms_, this, MSG_SDP_MESSAGE,
277 new rtc::TypedMessageData<SdpMessage>({type, msg}));
278 }
279 }
280
281 void SendIceMessage(const std::string& sdp_mid,
282 int sdp_mline_index,
283 const std::string& msg) {
284 if (signaling_delay_ms_ == 0) {
285 if (signaling_message_receiver_) {
286 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
287 msg);
288 }
289 } else {
290 rtc::Thread::Current()->PostDelayed(RTC_FROM_HERE, signaling_delay_ms_,
291 this, MSG_ICE_MESSAGE,
292 new rtc::TypedMessageData<IceMessage>(
293 {sdp_mid, sdp_mline_index, msg}));
294 }
295 }
296
297 // MessageHandler callback.
298 void OnMessage(rtc::Message* msg) override {
299 switch (msg->message_id) {
300 case MSG_SDP_MESSAGE: {
301 auto sdp_message =
302 static_cast<rtc::TypedMessageData<SdpMessage>*>(msg->pdata);
303 if (signaling_message_receiver_) {
304 signaling_message_receiver_->ReceiveSdpMessage(
305 sdp_message->data().type, sdp_message->data().msg);
306 }
307 delete sdp_message;
308 break;
309 }
310 case MSG_ICE_MESSAGE: {
311 auto ice_message =
312 static_cast<rtc::TypedMessageData<IceMessage>*>(msg->pdata);
313 if (signaling_message_receiver_) {
314 signaling_message_receiver_->ReceiveIceMessage(
315 ice_message->data().sdp_mid, ice_message->data().sdp_mline_index,
316 ice_message->data().msg);
317 }
318 delete ice_message;
319 break;
320 }
321 default:
322 RTC_CHECK(false);
323 }
324 }
325
326 // SignalingMessageReceiver callback.
327 void ReceiveSdpMessage(const std::string& type, std::string& msg) override {
328 FilterIncomingSdpMessage(&msg);
329 if (type == webrtc::SessionDescriptionInterface::kOffer) {
330 HandleIncomingOffer(msg);
331 } else {
332 HandleIncomingAnswer(msg);
333 }
334 }
335
336 // SignalingMessageReceiver callback.
337 void ReceiveIceMessage(const std::string& sdp_mid,
338 int sdp_mline_index,
339 const std::string& msg) override {
340 LOG(INFO) << id_ << "ReceiveIceMessage";
341 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
342 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
343 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
344 }
345
346 // PeerConnectionObserver callbacks.
347 void OnSignalingChange(
348 webrtc::PeerConnectionInterface::SignalingState new_state) override {
349 EXPECT_EQ(pc()->signaling_state(), new_state);
350 }
351 void OnAddStream(
352 rtc::scoped_refptr<MediaStreamInterface> media_stream) override {
353 media_stream->RegisterObserver(this);
354 for (size_t i = 0; i < media_stream->GetVideoTracks().size(); ++i) {
355 const std::string id = media_stream->GetVideoTracks()[i]->id();
356 ASSERT_TRUE(fake_video_renderers_.find(id) ==
357 fake_video_renderers_.end());
358 fake_video_renderers_[id].reset(new webrtc::FakeVideoTrackRenderer(
359 media_stream->GetVideoTracks()[i]));
360 }
361 }
362 void OnRemoveStream(
363 rtc::scoped_refptr<MediaStreamInterface> media_stream) override {}
364 void OnRenegotiationNeeded() override {}
365 void OnIceConnectionChange(
366 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
367 EXPECT_EQ(pc()->ice_connection_state(), new_state);
368 }
369 void OnIceGatheringChange(
370 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
371 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
372 }
373 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
374 LOG(INFO) << id_ << "OnIceCandidate";
375
376 std::string ice_sdp;
377 EXPECT_TRUE(candidate->ToString(&ice_sdp));
378 if (signaling_message_receiver_ == nullptr) {
379 // Remote party may be deleted.
380 return;
381 }
382 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
383 }
384
385 // MediaStreamInterface callback
386 void OnChanged() override {
387 // Track added or removed from MediaStream, so update our renderers.
388 rtc::scoped_refptr<StreamCollectionInterface> remote_streams =
389 pc()->remote_streams();
390 // Remove renderers for tracks that were removed.
391 for (auto it = fake_video_renderers_.begin();
392 it != fake_video_renderers_.end();) {
393 if (remote_streams->FindVideoTrack(it->first) == nullptr) {
394 auto to_remove = it++;
395 removed_fake_video_renderers_.push_back(std::move(to_remove->second));
396 fake_video_renderers_.erase(to_remove);
397 } else {
398 ++it;
399 }
400 }
401 // Create renderers for new video tracks.
402 for (size_t stream_index = 0; stream_index < remote_streams->count();
403 ++stream_index) {
404 MediaStreamInterface* remote_stream = remote_streams->at(stream_index);
405 for (size_t track_index = 0;
406 track_index < remote_stream->GetVideoTracks().size();
407 ++track_index) {
408 const std::string id =
409 remote_stream->GetVideoTracks()[track_index]->id();
410 if (fake_video_renderers_.find(id) != fake_video_renderers_.end()) {
411 continue;
412 }
413 fake_video_renderers_[id].reset(new webrtc::FakeVideoTrackRenderer(
414 remote_stream->GetVideoTracks()[track_index]));
415 }
416 }
417 }
418
419 void SetVideoConstraints(const webrtc::FakeConstraints& video_constraint) {
420 video_constraints_ = video_constraint;
421 }
422
423 void AddMediaStream(bool audio, bool video) {
424 std::string stream_label =
425 kStreamLabelBase +
426 rtc::ToString<int>(static_cast<int>(pc()->local_streams()->count()));
427 rtc::scoped_refptr<MediaStreamInterface> stream =
428 peer_connection_factory_->CreateLocalMediaStream(stream_label);
429
430 if (audio && can_receive_audio()) {
431 stream->AddTrack(CreateLocalAudioTrack(stream_label));
432 }
433 if (video && can_receive_video()) {
434 stream->AddTrack(CreateLocalVideoTrack(stream_label));
435 }
436
437 EXPECT_TRUE(pc()->AddStream(stream));
438 }
439
440 size_t NumberOfLocalMediaStreams() { return pc()->local_streams()->count(); }
441
442 bool SessionActive() {
443 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
444 }
445
446 // Automatically add a stream when receiving an offer, if we don't have one.
447 // Defaults to true.
448 void set_auto_add_stream(bool auto_add_stream) {
449 auto_add_stream_ = auto_add_stream;
450 }
451
452 void set_signaling_message_receiver(
453 SignalingMessageReceiver* signaling_message_receiver) {
454 signaling_message_receiver_ = signaling_message_receiver;
455 }
456
457 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
458
459 void EnableVideoDecoderFactory() {
460 video_decoder_factory_enabled_ = true;
461 fake_video_decoder_factory_->AddSupportedVideoCodecType(
462 webrtc::kVideoCodecVP8);
463 }
464
465 void IceRestart() {
466 offer_answer_constraints_.SetMandatoryIceRestart(true);
467 offer_answer_options_.ice_restart = true;
468 SetExpectIceRestart(true);
469 }
470
471 void SetExpectIceRestart(bool expect_restart) {
472 expect_ice_restart_ = expect_restart;
473 }
474
475 bool ExpectIceRestart() const { return expect_ice_restart_; }
476
477 void SetExpectIceRenomination(bool expect_renomination) {
478 expect_ice_renomination_ = expect_renomination;
479 }
480 void SetExpectRemoteIceRenomination(bool expect_renomination) {
481 expect_remote_ice_renomination_ = expect_renomination;
482 }
483 bool ExpectIceRenomination() { return expect_ice_renomination_; }
484 bool ExpectRemoteIceRenomination() { return expect_remote_ice_renomination_; }
485
486 // The below 3 methods assume streams will be offered.
487 // Thus they'll only set the "offer to receive" flag to true if it's
488 // currently false, not if it's just unset.
489 void SetReceiveAudioVideo(bool audio, bool video) {
490 SetReceiveAudio(audio);
491 SetReceiveVideo(video);
492 ASSERT_EQ(audio, can_receive_audio());
493 ASSERT_EQ(video, can_receive_video());
494 }
495
496 void SetReceiveAudio(bool audio) {
497 if (audio && can_receive_audio()) {
498 return;
499 }
500 offer_answer_constraints_.SetMandatoryReceiveAudio(audio);
501 offer_answer_options_.offer_to_receive_audio = audio ? 1 : 0;
502 }
503
504 void SetReceiveVideo(bool video) {
505 if (video && can_receive_video()) {
506 return;
507 }
508 offer_answer_constraints_.SetMandatoryReceiveVideo(video);
509 offer_answer_options_.offer_to_receive_video = video ? 1 : 0;
510 }
511
512 void SetOfferToReceiveAudioVideo(bool audio, bool video) {
513 offer_answer_constraints_.SetMandatoryReceiveAudio(audio);
514 offer_answer_options_.offer_to_receive_audio = audio ? 1 : 0;
515 offer_answer_constraints_.SetMandatoryReceiveVideo(video);
516 offer_answer_options_.offer_to_receive_video = video ? 1 : 0;
517 }
518
519 void RemoveMsidFromReceivedSdp(bool remove) { remove_msid_ = remove; }
520
521 void RemoveSdesCryptoFromReceivedSdp(bool remove) { remove_sdes_ = remove; }
522
523 void RemoveBundleFromReceivedSdp(bool remove) { remove_bundle_ = remove; }
524
525 void RemoveCvoFromReceivedSdp(bool remove) { remove_cvo_ = remove; }
526
527 bool can_receive_audio() {
528 bool value;
529 if (prefer_constraint_apis_) {
530 if (webrtc::FindConstraint(
531 &offer_answer_constraints_,
532 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
533 nullptr)) {
534 return value;
535 }
536 return true;
537 }
538 return offer_answer_options_.offer_to_receive_audio > 0 ||
539 offer_answer_options_.offer_to_receive_audio ==
540 PeerConnectionInterface::RTCOfferAnswerOptions::kUndefined;
541 }
542
543 bool can_receive_video() {
544 bool value;
545 if (prefer_constraint_apis_) {
546 if (webrtc::FindConstraint(
547 &offer_answer_constraints_,
548 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
549 nullptr)) {
550 return value;
551 }
552 return true;
553 }
554 return offer_answer_options_.offer_to_receive_video > 0 ||
555 offer_answer_options_.offer_to_receive_video ==
556 PeerConnectionInterface::RTCOfferAnswerOptions::kUndefined;
557 }
558
559 void OnDataChannel(
560 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
561 LOG(INFO) << id_ << "OnDataChannel";
562 data_channel_ = data_channel;
563 data_observer_.reset(new MockDataChannelObserver(data_channel));
564 }
565
566 void CreateDataChannel() { CreateDataChannel(nullptr); }
567
568 void CreateDataChannel(const webrtc::DataChannelInit* init) {
569 data_channel_ = pc()->CreateDataChannel(kDataChannelLabel, init);
570 ASSERT_TRUE(data_channel_.get() != nullptr);
571 data_observer_.reset(new MockDataChannelObserver(data_channel_));
572 }
573
574 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack(
575 const std::string& stream_label) {
576 FakeConstraints constraints;
577 // Disable highpass filter so that we can get all the test audio frames.
578 constraints.AddMandatory(MediaConstraintsInterface::kHighpassFilter, false);
579 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
580 peer_connection_factory_->CreateAudioSource(&constraints);
581 // TODO(perkj): Test audio source when it is implemented. Currently audio
582 // always use the default input.
583 std::string label = stream_label + kAudioTrackLabelBase;
584 return peer_connection_factory_->CreateAudioTrack(label, source);
585 }
586
587 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack(
588 const std::string& stream_label) {
589 // Set max frame rate to 10fps to reduce the risk of the tests to be flaky.
590 FakeConstraints source_constraints = video_constraints_;
591 source_constraints.SetMandatoryMaxFrameRate(10);
592
593 cricket::FakeVideoCapturer* fake_capturer =
594 new webrtc::FakePeriodicVideoCapturer();
595 fake_capturer->SetRotation(capture_rotation_);
596 video_capturers_.push_back(fake_capturer);
597 rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source =
598 peer_connection_factory_->CreateVideoSource(fake_capturer,
599 &source_constraints);
600 std::string label = stream_label + kVideoTrackLabelBase;
601
602 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
603 peer_connection_factory_->CreateVideoTrack(label, source));
604 if (!local_video_renderer_) {
605 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
606 }
607 return track;
608 }
609
610 DataChannelInterface* data_channel() { return data_channel_; }
611 const MockDataChannelObserver* data_observer() const {
612 return data_observer_.get();
613 }
614
615 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
616
617 void StopVideoCapturers() {
618 for (auto* capturer : video_capturers_) {
619 capturer->Stop();
620 }
621 }
622
623 void SetCaptureRotation(webrtc::VideoRotation rotation) {
624 ASSERT_TRUE(video_capturers_.empty());
625 capture_rotation_ = rotation;
626 }
627
628 bool AudioFramesReceivedCheck(int number_of_frames) const {
629 return number_of_frames <= fake_audio_capture_module_->frames_received();
630 }
631
632 int audio_frames_received() const {
633 return fake_audio_capture_module_->frames_received();
634 }
635
636 bool VideoFramesReceivedCheck(int number_of_frames) {
637 if (video_decoder_factory_enabled_) {
638 const std::vector<FakeWebRtcVideoDecoder*>& decoders
639 = fake_video_decoder_factory_->decoders();
640 if (decoders.empty()) {
641 return number_of_frames <= 0;
642 }
643 // Note - this checks that EACH decoder has the requisite number
644 // of frames. The video_frames_received() function sums them.
645 for (FakeWebRtcVideoDecoder* decoder : decoders) {
646 if (number_of_frames > decoder->GetNumFramesReceived()) {
647 return false;
648 }
649 }
650 return true;
651 } else {
652 if (fake_video_renderers_.empty()) {
653 return number_of_frames <= 0;
654 }
655
656 for (const auto& pair : fake_video_renderers_) {
657 if (number_of_frames > pair.second->num_rendered_frames()) {
658 return false;
659 }
660 }
661 return true;
662 }
663 }
664
665 int video_frames_received() const {
666 int total = 0;
667 if (video_decoder_factory_enabled_) {
668 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
669 fake_video_decoder_factory_->decoders();
670 for (const FakeWebRtcVideoDecoder* decoder : decoders) {
671 total += decoder->GetNumFramesReceived();
672 }
673 } else {
674 for (const auto& pair : fake_video_renderers_) {
675 total += pair.second->num_rendered_frames();
676 }
677 for (const auto& renderer : removed_fake_video_renderers_) {
678 total += renderer->num_rendered_frames();
679 }
680 }
681 return total;
682 }
683
684 // Verify the CreateDtmfSender interface
685 void VerifyDtmf() {
686 std::unique_ptr<DummyDtmfObserver> observer(new DummyDtmfObserver());
687 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender;
688
689 // We can't create a DTMF sender with an invalid audio track or a non local
690 // track.
691 EXPECT_TRUE(peer_connection_->CreateDtmfSender(nullptr) == nullptr);
692 rtc::scoped_refptr<webrtc::AudioTrackInterface> non_localtrack(
693 peer_connection_factory_->CreateAudioTrack("dummy_track", nullptr));
694 EXPECT_TRUE(peer_connection_->CreateDtmfSender(non_localtrack) == nullptr);
695
696 // We should be able to create a DTMF sender from a local track.
697 webrtc::AudioTrackInterface* localtrack =
698 peer_connection_->local_streams()->at(0)->GetAudioTracks()[0];
699 dtmf_sender = peer_connection_->CreateDtmfSender(localtrack);
700 EXPECT_TRUE(dtmf_sender.get() != nullptr);
701 dtmf_sender->RegisterObserver(observer.get());
702
703 // Test the DtmfSender object just created.
704 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
705 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
706
707 // We don't need to verify that the DTMF tones are actually sent out because
708 // that is already covered by the tests of the lower level components.
709
710 EXPECT_TRUE_WAIT(observer->completed(), kMaxWaitMs);
711 std::vector<std::string> tones;
712 tones.push_back("1");
713 tones.push_back("a");
714 tones.push_back("");
715 observer->Verify(tones);
716
717 dtmf_sender->UnregisterObserver();
718 }
719
720 // Verifies that the SessionDescription have rejected the appropriate media
721 // content.
722 void VerifyRejectedMediaInSessionDescription() {
723 ASSERT_TRUE(peer_connection_->remote_description() != nullptr);
724 ASSERT_TRUE(peer_connection_->local_description() != nullptr);
725 const cricket::SessionDescription* remote_desc =
726 peer_connection_->remote_description()->description();
727 const cricket::SessionDescription* local_desc =
728 peer_connection_->local_description()->description();
729
730 const ContentInfo* remote_audio_content = GetFirstAudioContent(remote_desc);
731 if (remote_audio_content) {
732 const ContentInfo* audio_content =
733 GetFirstAudioContent(local_desc);
734 EXPECT_EQ(can_receive_audio(), !audio_content->rejected);
735 }
736
737 const ContentInfo* remote_video_content = GetFirstVideoContent(remote_desc);
738 if (remote_video_content) {
739 const ContentInfo* video_content =
740 GetFirstVideoContent(local_desc);
741 EXPECT_EQ(can_receive_video(), !video_content->rejected);
742 }
743 }
744
745 void VerifyLocalIceUfragAndPassword() {
746 ASSERT_TRUE(peer_connection_->local_description() != nullptr);
747 const cricket::SessionDescription* desc =
748 peer_connection_->local_description()->description();
749 const cricket::ContentInfos& contents = desc->contents();
750
751 for (size_t index = 0; index < contents.size(); ++index) {
752 if (contents[index].rejected)
753 continue;
754 const cricket::TransportDescription* transport_desc =
755 desc->GetTransportDescriptionByName(contents[index].name);
756
757 std::map<int, IceUfragPwdPair>::const_iterator ufragpair_it =
758 ice_ufrag_pwd_.find(static_cast<int>(index));
759 if (ufragpair_it == ice_ufrag_pwd_.end()) {
760 ASSERT_FALSE(ExpectIceRestart());
761 ice_ufrag_pwd_[static_cast<int>(index)] =
762 IceUfragPwdPair(transport_desc->ice_ufrag, transport_desc->ice_pwd);
763 } else if (ExpectIceRestart()) {
764 const IceUfragPwdPair& ufrag_pwd = ufragpair_it->second;
765 EXPECT_NE(ufrag_pwd.first, transport_desc->ice_ufrag);
766 EXPECT_NE(ufrag_pwd.second, transport_desc->ice_pwd);
767 } else {
768 const IceUfragPwdPair& ufrag_pwd = ufragpair_it->second;
769 EXPECT_EQ(ufrag_pwd.first, transport_desc->ice_ufrag);
770 EXPECT_EQ(ufrag_pwd.second, transport_desc->ice_pwd);
771 }
772 }
773 }
774
775 void VerifyLocalIceRenomination() {
776 ASSERT_TRUE(peer_connection_->local_description() != nullptr);
777 const cricket::SessionDescription* desc =
778 peer_connection_->local_description()->description();
779 const cricket::ContentInfos& contents = desc->contents();
780
781 for (auto content : contents) {
782 if (content.rejected)
783 continue;
784 const cricket::TransportDescription* transport_desc =
785 desc->GetTransportDescriptionByName(content.name);
786 const auto& options = transport_desc->transport_options;
787 auto iter = std::find(options.begin(), options.end(),
788 cricket::ICE_RENOMINATION_STR);
789 EXPECT_EQ(ExpectIceRenomination(), iter != options.end());
790 }
791 }
792
793 void VerifyRemoteIceRenomination() {
794 ASSERT_TRUE(peer_connection_->remote_description() != nullptr);
795 const cricket::SessionDescription* desc =
796 peer_connection_->remote_description()->description();
797 const cricket::ContentInfos& contents = desc->contents();
798
799 for (auto content : contents) {
800 if (content.rejected)
801 continue;
802 const cricket::TransportDescription* transport_desc =
803 desc->GetTransportDescriptionByName(content.name);
804 const auto& options = transport_desc->transport_options;
805 auto iter = std::find(options.begin(), options.end(),
806 cricket::ICE_RENOMINATION_STR);
807 EXPECT_EQ(ExpectRemoteIceRenomination(), iter != options.end());
808 }
809 }
810
811 int GetAudioOutputLevelStats(webrtc::MediaStreamTrackInterface* track) {
812 rtc::scoped_refptr<MockStatsObserver>
813 observer(new rtc::RefCountedObject<MockStatsObserver>());
814 EXPECT_TRUE(peer_connection_->GetStats(
815 observer, track, PeerConnectionInterface::kStatsOutputLevelStandard));
816 EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
817 EXPECT_NE(0, observer->timestamp());
818 return observer->AudioOutputLevel();
819 }
820
821 int GetAudioInputLevelStats() {
822 rtc::scoped_refptr<MockStatsObserver>
823 observer(new rtc::RefCountedObject<MockStatsObserver>());
824 EXPECT_TRUE(peer_connection_->GetStats(
825 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
826 EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
827 EXPECT_NE(0, observer->timestamp());
828 return observer->AudioInputLevel();
829 }
830
831 int GetBytesReceivedStats(webrtc::MediaStreamTrackInterface* track) {
832 rtc::scoped_refptr<MockStatsObserver>
833 observer(new rtc::RefCountedObject<MockStatsObserver>());
834 EXPECT_TRUE(peer_connection_->GetStats(
835 observer, track, PeerConnectionInterface::kStatsOutputLevelStandard));
836 EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
837 EXPECT_NE(0, observer->timestamp());
838 return observer->BytesReceived();
839 }
840
841 int GetBytesSentStats(webrtc::MediaStreamTrackInterface* track) {
842 rtc::scoped_refptr<MockStatsObserver>
843 observer(new rtc::RefCountedObject<MockStatsObserver>());
844 EXPECT_TRUE(peer_connection_->GetStats(
845 observer, track, PeerConnectionInterface::kStatsOutputLevelStandard));
846 EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
847 EXPECT_NE(0, observer->timestamp());
848 return observer->BytesSent();
849 }
850
851 int GetAvailableReceivedBandwidthStats() {
852 rtc::scoped_refptr<MockStatsObserver>
853 observer(new rtc::RefCountedObject<MockStatsObserver>());
854 EXPECT_TRUE(peer_connection_->GetStats(
855 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
856 EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
857 EXPECT_NE(0, observer->timestamp());
858 int bw = observer->AvailableReceiveBandwidth();
859 return bw;
860 }
861
862 std::string GetDtlsCipherStats() {
863 rtc::scoped_refptr<MockStatsObserver>
864 observer(new rtc::RefCountedObject<MockStatsObserver>());
865 EXPECT_TRUE(peer_connection_->GetStats(
866 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
867 EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
868 EXPECT_NE(0, observer->timestamp());
869 return observer->DtlsCipher();
870 }
871
872 std::string GetSrtpCipherStats() {
873 rtc::scoped_refptr<MockStatsObserver>
874 observer(new rtc::RefCountedObject<MockStatsObserver>());
875 EXPECT_TRUE(peer_connection_->GetStats(
876 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
877 EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
878 EXPECT_NE(0, observer->timestamp());
879 return observer->SrtpCipher();
880 }
881
882 int rendered_width() {
883 EXPECT_FALSE(fake_video_renderers_.empty());
884 return fake_video_renderers_.empty() ? 1 :
885 fake_video_renderers_.begin()->second->width();
886 }
887
888 int rendered_height() {
889 EXPECT_FALSE(fake_video_renderers_.empty());
890 return fake_video_renderers_.empty() ? 1 :
891 fake_video_renderers_.begin()->second->height();
892 }
893
894 webrtc::VideoRotation rendered_rotation() {
895 EXPECT_FALSE(fake_video_renderers_.empty());
896 return fake_video_renderers_.empty()
897 ? webrtc::kVideoRotation_0
898 : fake_video_renderers_.begin()->second->rotation();
899 }
900
901 int local_rendered_width() {
902 return local_video_renderer_ ? local_video_renderer_->width() : 1;
903 }
904
905 int local_rendered_height() {
906 return local_video_renderer_ ? local_video_renderer_->height() : 1;
907 }
908
909 size_t number_of_remote_streams() {
910 if (!pc())
911 return 0;
912 return pc()->remote_streams()->count();
913 }
914
915 StreamCollectionInterface* remote_streams() const {
916 if (!pc()) {
917 ADD_FAILURE();
918 return nullptr;
919 }
920 return pc()->remote_streams();
921 }
922
923 StreamCollectionInterface* local_streams() {
924 if (!pc()) {
925 ADD_FAILURE();
926 return nullptr;
927 }
928 return pc()->local_streams();
929 }
930
931 bool HasLocalAudioTrack() { return StreamsHaveAudioTrack(local_streams()); }
932
933 bool HasLocalVideoTrack() { return StreamsHaveVideoTrack(local_streams()); }
934
935 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
936 return pc()->signaling_state();
937 }
938
939 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
940 return pc()->ice_connection_state();
941 }
942
943 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
944 return pc()->ice_gathering_state();
945 }
946
947 std::vector<std::unique_ptr<MockRtpReceiverObserver>> const&
948 rtp_receiver_observers() {
949 return rtp_receiver_observers_;
950 }
951
952 void SetRtpReceiverObservers() {
953 rtp_receiver_observers_.clear();
954 for (auto receiver : pc()->GetReceivers()) {
955 std::unique_ptr<MockRtpReceiverObserver> observer(
956 new MockRtpReceiverObserver(receiver->media_type()));
957 receiver->SetObserver(observer.get());
958 rtp_receiver_observers_.push_back(std::move(observer));
959 }
960 }
961
962 private:
963 class DummyDtmfObserver : public DtmfSenderObserverInterface {
964 public:
965 DummyDtmfObserver() : completed_(false) {}
966
967 // Implements DtmfSenderObserverInterface.
968 void OnToneChange(const std::string& tone) override {
969 tones_.push_back(tone);
970 if (tone.empty()) {
971 completed_ = true;
972 }
973 }
974
975 void Verify(const std::vector<std::string>& tones) const {
976 ASSERT_TRUE(tones_.size() == tones.size());
977 EXPECT_TRUE(std::equal(tones.begin(), tones.end(), tones_.begin()));
978 }
979
980 bool completed() const { return completed_; }
981
982 private:
983 bool completed_;
984 std::vector<std::string> tones_;
985 };
986
987 explicit PeerConnectionTestClient(const std::string& id) : id_(id) {}
988
989 bool Init(
990 const MediaConstraintsInterface* constraints,
991 const PeerConnectionFactory::Options* options,
992 const PeerConnectionInterface::RTCConfiguration* config,
993 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
994 bool prefer_constraint_apis,
995 rtc::Thread* network_thread,
996 rtc::Thread* worker_thread) {
997 EXPECT_TRUE(!peer_connection_);
998 EXPECT_TRUE(!peer_connection_factory_);
999 if (!prefer_constraint_apis) {
1000 EXPECT_TRUE(!constraints);
1001 }
1002 prefer_constraint_apis_ = prefer_constraint_apis;
1003
1004 fake_network_manager_.reset(new rtc::FakeNetworkManager());
1005 fake_network_manager_->AddInterface(rtc::SocketAddress("192.168.1.1", 0));
1006
1007 std::unique_ptr<cricket::PortAllocator> port_allocator(
1008 new cricket::BasicPortAllocator(fake_network_manager_.get()));
1009 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
1010
1011 if (fake_audio_capture_module_ == nullptr) {
1012 return false;
1013 }
1014 fake_video_decoder_factory_ = new FakeWebRtcVideoDecoderFactory();
1015 fake_video_encoder_factory_ = new FakeWebRtcVideoEncoderFactory();
1016 rtc::Thread* const signaling_thread = rtc::Thread::Current();
1017 peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(
1018 network_thread, worker_thread, signaling_thread,
1019 fake_audio_capture_module_, fake_video_encoder_factory_,
1020 fake_video_decoder_factory_);
1021 if (!peer_connection_factory_) {
1022 return false;
1023 }
1024 if (options) {
1025 peer_connection_factory_->SetOptions(*options);
1026 }
1027 peer_connection_ =
1028 CreatePeerConnection(std::move(port_allocator), constraints, config,
1029 std::move(cert_generator));
1030 return peer_connection_.get() != nullptr;
1031 }
1032
1033 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
1034 std::unique_ptr<cricket::PortAllocator> port_allocator,
1035 const MediaConstraintsInterface* constraints,
1036 const PeerConnectionInterface::RTCConfiguration* config,
1037 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator) {
1038 // CreatePeerConnection with RTCConfiguration.
1039 PeerConnectionInterface::RTCConfiguration default_config;
1040
1041 if (!config) {
1042 config = &default_config;
1043 }
1044
1045 return peer_connection_factory_->CreatePeerConnection(
1046 *config, constraints, std::move(port_allocator),
1047 std::move(cert_generator), this);
1048 }
1049
1050 void HandleIncomingOffer(const std::string& msg) {
1051 LOG(INFO) << id_ << "HandleIncomingOffer ";
1052 if (NumberOfLocalMediaStreams() == 0 && auto_add_stream_) {
1053 // If we are not sending any streams ourselves it is time to add some.
1054 AddMediaStream(true, true);
1055 }
1056 std::unique_ptr<SessionDescriptionInterface> desc(
1057 webrtc::CreateSessionDescription("offer", msg, nullptr));
1058 EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
1059 // Set the RtpReceiverObserver after receivers are created.
1060 SetRtpReceiverObservers();
1061 std::unique_ptr<SessionDescriptionInterface> answer;
1062 EXPECT_TRUE(DoCreateAnswer(&answer));
1063 std::string sdp;
1064 EXPECT_TRUE(answer->ToString(&sdp));
1065 EXPECT_TRUE(DoSetLocalDescription(answer.release()));
1066 SendSdpMessage(webrtc::SessionDescriptionInterface::kAnswer, sdp);
1067 }
1068
1069 void HandleIncomingAnswer(const std::string& msg) {
1070 LOG(INFO) << id_ << "HandleIncomingAnswer";
1071 std::unique_ptr<SessionDescriptionInterface> desc(
1072 webrtc::CreateSessionDescription("answer", msg, nullptr));
1073 EXPECT_TRUE(DoSetRemoteDescription(desc.release()));
1074 // Set the RtpReceiverObserver after receivers are created.
1075 SetRtpReceiverObservers();
1076 }
1077
1078 bool DoCreateOfferAnswer(std::unique_ptr<SessionDescriptionInterface>* desc,
1079 bool offer) {
1080 rtc::scoped_refptr<MockCreateSessionDescriptionObserver>
1081 observer(new rtc::RefCountedObject<
1082 MockCreateSessionDescriptionObserver>());
1083 if (prefer_constraint_apis_) {
1084 if (offer) {
1085 pc()->CreateOffer(observer, &offer_answer_constraints_);
1086 } else {
1087 pc()->CreateAnswer(observer, &offer_answer_constraints_);
1088 }
1089 } else {
1090 if (offer) {
1091 pc()->CreateOffer(observer, offer_answer_options_);
1092 } else {
1093 pc()->CreateAnswer(observer, offer_answer_options_);
1094 }
1095 }
1096 EXPECT_EQ_WAIT(true, observer->called(), kMaxWaitMs);
1097 desc->reset(observer->release_desc());
1098 if (observer->result() && ExpectIceRestart()) {
1099 EXPECT_EQ(0u, (*desc)->candidates(0)->count());
1100 }
1101 return observer->result();
1102 }
1103
1104 bool DoCreateOffer(std::unique_ptr<SessionDescriptionInterface>* desc) {
1105 return DoCreateOfferAnswer(desc, true);
1106 }
1107
1108 bool DoCreateAnswer(std::unique_ptr<SessionDescriptionInterface>* desc) {
1109 return DoCreateOfferAnswer(desc, false);
1110 }
1111
1112 bool DoSetLocalDescription(SessionDescriptionInterface* desc) {
1113 rtc::scoped_refptr<MockSetSessionDescriptionObserver>
1114 observer(new rtc::RefCountedObject<
1115 MockSetSessionDescriptionObserver>());
1116 LOG(INFO) << id_ << "SetLocalDescription ";
1117 pc()->SetLocalDescription(observer, desc);
1118 // Ignore the observer result. If we wait for the result with
1119 // EXPECT_TRUE_WAIT, local ice candidates might be sent to the remote peer
1120 // before the offer which is an error.
1121 // The reason is that EXPECT_TRUE_WAIT uses
1122 // rtc::Thread::Current()->ProcessMessages(1);
1123 // ProcessMessages waits at least 1ms but processes all messages before
1124 // returning. Since this test is synchronous and send messages to the remote
1125 // peer whenever a callback is invoked, this can lead to messages being
1126 // sent to the remote peer in the wrong order.
1127 // TODO(perkj): Find a way to check the result without risking that the
1128 // order of sent messages are changed. Ex- by posting all messages that are
1129 // sent to the remote peer.
1130 return true;
1131 }
1132
1133 bool DoSetRemoteDescription(SessionDescriptionInterface* desc) {
1134 rtc::scoped_refptr<MockSetSessionDescriptionObserver>
1135 observer(new rtc::RefCountedObject<
1136 MockSetSessionDescriptionObserver>());
1137 LOG(INFO) << id_ << "SetRemoteDescription ";
1138 pc()->SetRemoteDescription(observer, desc);
1139 EXPECT_TRUE_WAIT(observer->called(), kMaxWaitMs);
1140 return observer->result();
1141 }
1142
1143 // This modifies all received SDP messages before they are processed.
1144 void FilterIncomingSdpMessage(std::string* sdp) {
1145 if (remove_msid_) {
1146 const char kSdpSsrcAttribute[] = "a=ssrc:";
1147 RemoveLinesFromSdp(kSdpSsrcAttribute, sdp);
1148 const char kSdpMsidSupportedAttribute[] = "a=msid-semantic:";
1149 RemoveLinesFromSdp(kSdpMsidSupportedAttribute, sdp);
1150 }
1151 if (remove_bundle_) {
1152 const char kSdpBundleAttribute[] = "a=group:BUNDLE";
1153 RemoveLinesFromSdp(kSdpBundleAttribute, sdp);
1154 }
1155 if (remove_sdes_) {
1156 const char kSdpSdesCryptoAttribute[] = "a=crypto";
1157 RemoveLinesFromSdp(kSdpSdesCryptoAttribute, sdp);
1158 }
1159 if (remove_cvo_) {
1160 const char kSdpCvoExtenstion[] = "urn:3gpp:video-orientation";
1161 RemoveLinesFromSdp(kSdpCvoExtenstion, sdp);
1162 }
1163 }
1164
1165 std::string id_;
1166
1167 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
1168
1169 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
1170 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
1171 peer_connection_factory_;
1172
1173 bool prefer_constraint_apis_ = true;
1174 bool auto_add_stream_ = true;
1175
1176 typedef std::pair<std::string, std::string> IceUfragPwdPair;
1177 std::map<int, IceUfragPwdPair> ice_ufrag_pwd_;
1178 bool expect_ice_restart_ = false;
1179 bool expect_ice_renomination_ = false;
1180 bool expect_remote_ice_renomination_ = false;
1181
1182 // Needed to keep track of number of frames sent.
1183 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1184 // Needed to keep track of number of frames received.
1185 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1186 fake_video_renderers_;
1187 // Needed to ensure frames aren't received for removed tracks.
1188 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1189 removed_fake_video_renderers_;
1190 // Needed to keep track of number of frames received when external decoder
1191 // used.
1192 FakeWebRtcVideoDecoderFactory* fake_video_decoder_factory_ = nullptr;
1193 FakeWebRtcVideoEncoderFactory* fake_video_encoder_factory_ = nullptr;
1194 bool video_decoder_factory_enabled_ = false;
1195 webrtc::FakeConstraints video_constraints_;
1196
1197 // For remote peer communication.
1198 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1199 int signaling_delay_ms_ = 0;
1200
1201 // Store references to the video capturers we've created, so that we can stop
1202 // them, if required.
1203 std::vector<cricket::FakeVideoCapturer*> video_capturers_;
1204 webrtc::VideoRotation capture_rotation_ = webrtc::kVideoRotation_0;
1205 // |local_video_renderer_| attached to the first created local video track.
1206 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1207
1208 webrtc::FakeConstraints offer_answer_constraints_;
1209 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1210 bool remove_msid_ = false; // True if MSID should be removed in received SDP.
1211 bool remove_bundle_ =
1212 false; // True if bundle should be removed in received SDP.
1213 bool remove_sdes_ =
1214 false; // True if a=crypto should be removed in received SDP.
1215 // |remove_cvo_| is true if extension urn:3gpp:video-orientation should be
1216 // removed in the received SDP.
1217 bool remove_cvo_ = false;
1218
1219 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1220 std::unique_ptr<MockDataChannelObserver> data_observer_;
1221
1222 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1223 };
1224
1225 class P2PTestConductor : public testing::Test {
1226 public:
1227 P2PTestConductor()
1228 : pss_(new rtc::PhysicalSocketServer),
1229 ss_(new rtc::VirtualSocketServer(pss_.get())),
1230 network_thread_(new rtc::Thread(ss_.get())),
1231 worker_thread_(rtc::Thread::Create()) {
1232 RTC_CHECK(network_thread_->Start());
1233 RTC_CHECK(worker_thread_->Start());
1234 }
1235
1236 bool SessionActive() {
1237 return initiating_client_->SessionActive() &&
1238 receiving_client_->SessionActive();
1239 }
1240
1241 // Return true if the number of frames provided have been received
1242 // on the video and audio tracks provided.
1243 bool FramesHaveArrived(int audio_frames_to_receive,
1244 int video_frames_to_receive) {
1245 bool all_good = true;
1246 if (initiating_client_->HasLocalAudioTrack() &&
1247 receiving_client_->can_receive_audio()) {
1248 all_good &=
1249 receiving_client_->AudioFramesReceivedCheck(audio_frames_to_receive);
1250 }
1251 if (initiating_client_->HasLocalVideoTrack() &&
1252 receiving_client_->can_receive_video()) {
1253 all_good &=
1254 receiving_client_->VideoFramesReceivedCheck(video_frames_to_receive);
1255 }
1256 if (receiving_client_->HasLocalAudioTrack() &&
1257 initiating_client_->can_receive_audio()) {
1258 all_good &=
1259 initiating_client_->AudioFramesReceivedCheck(audio_frames_to_receive);
1260 }
1261 if (receiving_client_->HasLocalVideoTrack() &&
1262 initiating_client_->can_receive_video()) {
1263 all_good &=
1264 initiating_client_->VideoFramesReceivedCheck(video_frames_to_receive);
1265 }
1266 return all_good;
1267 }
1268
1269 void VerifyDtmf() {
1270 initiating_client_->VerifyDtmf();
1271 receiving_client_->VerifyDtmf();
1272 }
1273
1274 void TestUpdateOfferWithRejectedContent() {
1275 // Renegotiate, rejecting the video m-line.
1276 initiating_client_->Negotiate(true, false);
1277 ASSERT_TRUE_WAIT(SessionActive(), kMaxWaitForActivationMs);
1278
1279 int pc1_audio_received = initiating_client_->audio_frames_received();
1280 int pc1_video_received = initiating_client_->video_frames_received();
1281 int pc2_audio_received = receiving_client_->audio_frames_received();
1282 int pc2_video_received = receiving_client_->video_frames_received();
1283
1284 // Wait for some additional audio frames to be received.
1285 EXPECT_TRUE_WAIT(initiating_client_->AudioFramesReceivedCheck(
1286 pc1_audio_received + kEndAudioFrameCount) &&
1287 receiving_client_->AudioFramesReceivedCheck(
1288 pc2_audio_received + kEndAudioFrameCount),
1289 kMaxWaitForFramesMs);
1290
1291 // During this time, we shouldn't have received any additional video frames
1292 // for the rejected video tracks.
1293 EXPECT_EQ(pc1_video_received, initiating_client_->video_frames_received());
1294 EXPECT_EQ(pc2_video_received, receiving_client_->video_frames_received());
1295 }
1296
1297 void VerifyRenderedAspectRatio(int width, int height) {
1298 VerifyRenderedAspectRatio(width, height, webrtc::kVideoRotation_0);
1299 }
1300
1301 void VerifyRenderedAspectRatio(int width,
1302 int height,
1303 webrtc::VideoRotation rotation) {
1304 double expected_aspect_ratio = static_cast<double>(width) / height;
1305 double receiving_client_rendered_aspect_ratio =
1306 static_cast<double>(receiving_client()->rendered_width()) /
1307 receiving_client()->rendered_height();
1308 double initializing_client_rendered_aspect_ratio =
1309 static_cast<double>(initializing_client()->rendered_width()) /
1310 initializing_client()->rendered_height();
1311 double initializing_client_local_rendered_aspect_ratio =
1312 static_cast<double>(initializing_client()->local_rendered_width()) /
1313 initializing_client()->local_rendered_height();
1314 // Verify end-to-end rendered aspect ratio.
1315 EXPECT_EQ(expected_aspect_ratio, receiving_client_rendered_aspect_ratio);
1316 EXPECT_EQ(expected_aspect_ratio, initializing_client_rendered_aspect_ratio);
1317 // Verify aspect ratio of the local preview.
1318 EXPECT_EQ(expected_aspect_ratio,
1319 initializing_client_local_rendered_aspect_ratio);
1320
1321 // Verify rotation.
1322 EXPECT_EQ(rotation, receiving_client()->rendered_rotation());
1323 EXPECT_EQ(rotation, initializing_client()->rendered_rotation());
1324 }
1325
1326 void VerifySessionDescriptions() {
1327 initiating_client_->VerifyRejectedMediaInSessionDescription();
1328 receiving_client_->VerifyRejectedMediaInSessionDescription();
1329 initiating_client_->VerifyLocalIceUfragAndPassword();
1330 receiving_client_->VerifyLocalIceUfragAndPassword();
1331 }
1332
1333 ~P2PTestConductor() {
1334 if (initiating_client_) {
1335 initiating_client_->set_signaling_message_receiver(nullptr);
1336 }
1337 if (receiving_client_) {
1338 receiving_client_->set_signaling_message_receiver(nullptr);
1339 }
1340 }
1341
1342 bool CreateTestClients() { return CreateTestClients(nullptr, nullptr); }
1343
1344 bool CreateTestClients(MediaConstraintsInterface* init_constraints,
1345 MediaConstraintsInterface* recv_constraints) {
1346 return CreateTestClients(init_constraints, nullptr, nullptr,
1347 recv_constraints, nullptr, nullptr);
1348 }
1349
1350 bool CreateTestClients(
1351 const PeerConnectionInterface::RTCConfiguration& init_config,
1352 const PeerConnectionInterface::RTCConfiguration& recv_config) {
1353 return CreateTestClients(nullptr, nullptr, &init_config, nullptr, nullptr,
1354 &recv_config);
1355 }
1356
1357 bool CreateTestClientsThatPreferNoConstraints() {
1358 initiating_client_.reset(
1359 PeerConnectionTestClient::CreateClientPreferNoConstraints(
1360 "Caller: ", nullptr, network_thread_.get(), worker_thread_.get()));
1361 receiving_client_.reset(
1362 PeerConnectionTestClient::CreateClientPreferNoConstraints(
1363 "Callee: ", nullptr, network_thread_.get(), worker_thread_.get()));
1364 if (!initiating_client_ || !receiving_client_) {
1365 return false;
1366 }
1367 // Remember the choice for possible later resets of the clients.
1368 prefer_constraint_apis_ = false;
1369 SetSignalingReceivers();
1370 return true;
1371 }
1372
1373 bool CreateTestClients(
1374 MediaConstraintsInterface* init_constraints,
1375 PeerConnectionFactory::Options* init_options,
1376 const PeerConnectionInterface::RTCConfiguration* init_config,
1377 MediaConstraintsInterface* recv_constraints,
1378 PeerConnectionFactory::Options* recv_options,
1379 const PeerConnectionInterface::RTCConfiguration* recv_config) {
1380 initiating_client_.reset(PeerConnectionTestClient::CreateClient(
1381 "Caller: ", init_constraints, init_options, init_config,
1382 network_thread_.get(), worker_thread_.get()));
1383 receiving_client_.reset(PeerConnectionTestClient::CreateClient(
1384 "Callee: ", recv_constraints, recv_options, recv_config,
1385 network_thread_.get(), worker_thread_.get()));
1386 if (!initiating_client_ || !receiving_client_) {
1387 return false;
1388 }
1389 SetSignalingReceivers();
1390 return true;
1391 }
1392
1393 void SetSignalingReceivers() {
1394 initiating_client_->set_signaling_message_receiver(receiving_client_.get());
1395 receiving_client_->set_signaling_message_receiver(initiating_client_.get());
1396 }
1397
1398 void SetSignalingDelayMs(int delay_ms) {
1399 initiating_client_->set_signaling_delay_ms(delay_ms);
1400 receiving_client_->set_signaling_delay_ms(delay_ms);
1401 }
1402
1403 void SetVideoConstraints(const webrtc::FakeConstraints& init_constraints,
1404 const webrtc::FakeConstraints& recv_constraints) {
1405 initiating_client_->SetVideoConstraints(init_constraints);
1406 receiving_client_->SetVideoConstraints(recv_constraints);
1407 }
1408
1409 void SetCaptureRotation(webrtc::VideoRotation rotation) {
1410 initiating_client_->SetCaptureRotation(rotation);
1411 receiving_client_->SetCaptureRotation(rotation);
1412 }
1413
1414 void EnableVideoDecoderFactory() {
1415 initiating_client_->EnableVideoDecoderFactory();
1416 receiving_client_->EnableVideoDecoderFactory();
1417 }
1418
1419 // This test sets up a call between two parties. Both parties send static
1420 // frames to each other. Once the test is finished the number of sent frames
1421 // is compared to the number of received frames.
1422 void LocalP2PTest() {
1423 if (initiating_client_->NumberOfLocalMediaStreams() == 0) {
1424 initiating_client_->AddMediaStream(true, true);
1425 }
1426 initiating_client_->Negotiate();
1427 // Assert true is used here since next tests are guaranteed to fail and
1428 // would eat up 5 seconds.
1429 ASSERT_TRUE_WAIT(SessionActive(), kMaxWaitForActivationMs);
1430 VerifySessionDescriptions();
1431
1432 int audio_frame_count = kEndAudioFrameCount;
1433 int video_frame_count = kEndVideoFrameCount;
1434 // TODO(ronghuawu): Add test to cover the case of sendonly and recvonly.
1435
1436 if ((!initiating_client_->can_receive_audio() &&
1437 !initiating_client_->can_receive_video()) ||
1438 (!receiving_client_->can_receive_audio() &&
1439 !receiving_client_->can_receive_video())) {
1440 // Neither audio nor video will flow, so connections won't be
1441 // established. There's nothing more to check.
1442 // TODO(hta): Check connection if there's a data channel.
1443 return;
1444 }
1445
1446 // Audio or video is expected to flow, so both clients should reach the
1447 // Connected state, and the offerer (ICE controller) should proceed to
1448 // Completed.
1449 // Note: These tests have been observed to fail under heavy load at
1450 // shorter timeouts, so they may be flaky.
1451 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
1452 initiating_client_->ice_connection_state(),
1453 kMaxWaitForFramesMs);
1454 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
1455 receiving_client_->ice_connection_state(),
1456 kMaxWaitForFramesMs);
1457
1458 // The ICE gathering state should end up in kIceGatheringComplete,
1459 // but there's a bug that prevents this at the moment, and the state
1460 // machine is being updated by the WEBRTC WG.
1461 // TODO(hta): Update this check when spec revisions finish.
1462 EXPECT_NE(webrtc::PeerConnectionInterface::kIceGatheringNew,
1463 initiating_client_->ice_gathering_state());
1464 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
1465 receiving_client_->ice_gathering_state(),
1466 kMaxWaitForFramesMs);
1467
1468 // Check that the expected number of frames have arrived.
1469 EXPECT_TRUE_WAIT(FramesHaveArrived(audio_frame_count, video_frame_count),
1470 kMaxWaitForFramesMs);
1471 }
1472
1473 void SetupAndVerifyDtlsCall() {
1474 MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1475 FakeConstraints setup_constraints;
1476 setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1477 true);
1478 // Disable resolution adaptation, we don't want it interfering with the
1479 // test results.
1480 webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;
1481 rtc_config.set_cpu_adaptation(false);
1482
1483 ASSERT_TRUE(CreateTestClients(&setup_constraints, nullptr, &rtc_config,
1484 &setup_constraints, nullptr, &rtc_config));
1485 LocalP2PTest();
1486 VerifyRenderedAspectRatio(640, 480);
1487 }
1488
1489 PeerConnectionTestClient* CreateDtlsClientWithAlternateKey() {
1490 FakeConstraints setup_constraints;
1491 setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1492 true);
1493 // Disable resolution adaptation, we don't want it interfering with the
1494 // test results.
1495 webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;
1496 rtc_config.set_cpu_adaptation(false);
1497
1498 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1499 rtc::SSLStreamAdapter::HaveDtlsSrtp() ?
1500 new FakeRTCCertificateGenerator() : nullptr);
1501 cert_generator->use_alternate_key();
1502
1503 // Make sure the new client is using a different certificate.
1504 return PeerConnectionTestClient::CreateClientWithDtlsIdentityStore(
1505 "New Peer: ", &setup_constraints, nullptr, &rtc_config,
1506 std::move(cert_generator), prefer_constraint_apis_,
1507 network_thread_.get(), worker_thread_.get());
1508 }
1509
1510 void SendRtpData(webrtc::DataChannelInterface* dc, const std::string& data) {
1511 // Messages may get lost on the unreliable DataChannel, so we send multiple
1512 // times to avoid test flakiness.
1513 static const size_t kSendAttempts = 5;
1514
1515 for (size_t i = 0; i < kSendAttempts; ++i) {
1516 dc->Send(DataBuffer(data));
1517 }
1518 }
1519
1520 rtc::Thread* network_thread() { return network_thread_.get(); }
1521
1522 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1523
1524 PeerConnectionTestClient* initializing_client() {
1525 return initiating_client_.get();
1526 }
1527
1528 // Set the |initiating_client_| to the |client| passed in and return the
1529 // original |initiating_client_|.
1530 PeerConnectionTestClient* set_initializing_client(
1531 PeerConnectionTestClient* client) {
1532 PeerConnectionTestClient* old = initiating_client_.release();
1533 initiating_client_.reset(client);
1534 return old;
1535 }
1536
1537 PeerConnectionTestClient* receiving_client() {
1538 return receiving_client_.get();
1539 }
1540
1541 // Set the |receiving_client_| to the |client| passed in and return the
1542 // original |receiving_client_|.
1543 PeerConnectionTestClient* set_receiving_client(
1544 PeerConnectionTestClient* client) {
1545 PeerConnectionTestClient* old = receiving_client_.release();
1546 receiving_client_.reset(client);
1547 return old;
1548 }
1549
1550 bool AllObserversReceived(
1551 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>& observers) {
1552 for (auto& observer : observers) {
1553 if (!observer->first_packet_received()) {
1554 return false;
1555 }
1556 }
1557 return true;
1558 }
1559
1560 void TestGcmNegotiation(bool local_gcm_enabled, bool remote_gcm_enabled,
1561 int expected_cipher_suite) {
1562 PeerConnectionFactory::Options init_options;
1563 init_options.crypto_options.enable_gcm_crypto_suites = local_gcm_enabled;
1564 PeerConnectionFactory::Options recv_options;
1565 recv_options.crypto_options.enable_gcm_crypto_suites = remote_gcm_enabled;
1566 ASSERT_TRUE(CreateTestClients(nullptr, &init_options, nullptr, nullptr,
1567 &recv_options, nullptr));
1568 rtc::scoped_refptr<webrtc::FakeMetricsObserver>
1569 init_observer =
1570 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1571 initializing_client()->pc()->RegisterUMAObserver(init_observer);
1572 LocalP2PTest();
1573
1574 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
1575 initializing_client()->GetSrtpCipherStats(),
1576 kMaxWaitMs);
1577 EXPECT_EQ(1,
1578 init_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1579 expected_cipher_suite));
1580 }
1581
1582 private:
1583 // |ss_| is used by |network_thread_| so it must be destroyed later.
1584 std::unique_ptr<rtc::PhysicalSocketServer> pss_;
1585 std::unique_ptr<rtc::VirtualSocketServer> ss_;
1586 // |network_thread_| and |worker_thread_| are used by both
1587 // |initiating_client_| and |receiving_client_| so they must be destroyed
1588 // later.
1589 std::unique_ptr<rtc::Thread> network_thread_;
1590 std::unique_ptr<rtc::Thread> worker_thread_;
1591 std::unique_ptr<PeerConnectionTestClient> initiating_client_;
1592 std::unique_ptr<PeerConnectionTestClient> receiving_client_;
1593 bool prefer_constraint_apis_ = true;
1594 };
1595
1596 // Disable for TSan v2, see
1597 // https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
1598 #if !defined(THREAD_SANITIZER)
1599
1600 TEST_F(P2PTestConductor, TestRtpReceiverObserverCallbackFunction) {
1601 ASSERT_TRUE(CreateTestClients());
1602 LocalP2PTest();
1603 EXPECT_TRUE_WAIT(
1604 AllObserversReceived(initializing_client()->rtp_receiver_observers()),
1605 kMaxWaitForFramesMs);
1606 EXPECT_TRUE_WAIT(
1607 AllObserversReceived(receiving_client()->rtp_receiver_observers()),
1608 kMaxWaitForFramesMs);
1609 }
1610
1611 // The observers are expected to fire the signal even if they are set after the
1612 // first packet is received.
1613 TEST_F(P2PTestConductor, TestSetRtpReceiverObserverAfterFirstPacketIsReceived) {
1614 ASSERT_TRUE(CreateTestClients());
1615 LocalP2PTest();
1616 // Reset the RtpReceiverObservers.
1617 initializing_client()->SetRtpReceiverObservers();
1618 receiving_client()->SetRtpReceiverObservers();
1619 EXPECT_TRUE_WAIT(
1620 AllObserversReceived(initializing_client()->rtp_receiver_observers()),
1621 kMaxWaitForFramesMs);
1622 EXPECT_TRUE_WAIT(
1623 AllObserversReceived(receiving_client()->rtp_receiver_observers()),
1624 kMaxWaitForFramesMs);
1625 }
1626
1627 // This test sets up a Jsep call between two parties and test Dtmf.
1628 // TODO(holmer): Disabled due to sometimes crashing on buildbots.
1629 // See issue webrtc/2378.
1630 TEST_F(P2PTestConductor, DISABLED_LocalP2PTestDtmf) {
1631 ASSERT_TRUE(CreateTestClients());
1632 LocalP2PTest();
1633 VerifyDtmf();
1634 }
1635
1636 // This test sets up a Jsep call between two parties and test that we can get a
1637 // video aspect ratio of 16:9.
1638 TEST_F(P2PTestConductor, LocalP2PTest16To9) {
1639 ASSERT_TRUE(CreateTestClients());
1640 FakeConstraints constraint;
1641 double requested_ratio = 640.0/360;
1642 constraint.SetMandatoryMinAspectRatio(requested_ratio);
1643 SetVideoConstraints(constraint, constraint);
1644 LocalP2PTest();
1645
1646 ASSERT_LE(0, initializing_client()->rendered_height());
1647 double initiating_video_ratio =
1648 static_cast<double>(initializing_client()->rendered_width()) /
1649 initializing_client()->rendered_height();
1650 EXPECT_LE(requested_ratio, initiating_video_ratio);
1651
1652 ASSERT_LE(0, receiving_client()->rendered_height());
1653 double receiving_video_ratio =
1654 static_cast<double>(receiving_client()->rendered_width()) /
1655 receiving_client()->rendered_height();
1656 EXPECT_LE(requested_ratio, receiving_video_ratio);
1657 }
1658
1659 // This test sets up a Jsep call between two parties and test that the
1660 // received video has a resolution of 1280*720.
1661 // TODO(mallinath): Enable when
1662 // http://code.google.com/p/webrtc/issues/detail?id=981 is fixed.
1663 TEST_F(P2PTestConductor, DISABLED_LocalP2PTest1280By720) {
1664 ASSERT_TRUE(CreateTestClients());
1665 FakeConstraints constraint;
1666 constraint.SetMandatoryMinWidth(1280);
1667 constraint.SetMandatoryMinHeight(720);
1668 SetVideoConstraints(constraint, constraint);
1669 LocalP2PTest();
1670 VerifyRenderedAspectRatio(1280, 720);
1671 }
1672
1673 // This test sets up a call between two endpoints that are configured to use
1674 // DTLS key agreement. As a result, DTLS is negotiated and used for transport.
1675 TEST_F(P2PTestConductor, LocalP2PTestDtls) {
1676 SetupAndVerifyDtlsCall();
1677 }
1678
1679 // This test sets up an one-way call, with media only from initiator to
1680 // responder.
1681 TEST_F(P2PTestConductor, OneWayMediaCall) {
1682 ASSERT_TRUE(CreateTestClients());
1683 receiving_client()->set_auto_add_stream(false);
1684 LocalP2PTest();
1685 }
1686
1687 TEST_F(P2PTestConductor, OneWayMediaCallWithoutConstraints) {
1688 ASSERT_TRUE(CreateTestClientsThatPreferNoConstraints());
1689 receiving_client()->set_auto_add_stream(false);
1690 LocalP2PTest();
1691 }
1692
1693 // This test sets up a audio call initially and then upgrades to audio/video,
1694 // using DTLS.
1695 TEST_F(P2PTestConductor, LocalP2PTestDtlsRenegotiate) {
1696 MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1697 FakeConstraints setup_constraints;
1698 setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1699 true);
1700 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1701 receiving_client()->SetReceiveAudioVideo(true, false);
1702 LocalP2PTest();
1703 receiving_client()->SetReceiveAudioVideo(true, true);
1704 receiving_client()->Negotiate();
1705 }
1706
1707 // This test sets up a call transfer to a new caller with a different DTLS
1708 // fingerprint.
1709 TEST_F(P2PTestConductor, LocalP2PTestDtlsTransferCallee) {
1710 MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1711 SetupAndVerifyDtlsCall();
1712
1713 // Keeping the original peer around which will still send packets to the
1714 // receiving client. These SRTP packets will be dropped.
1715 std::unique_ptr<PeerConnectionTestClient> original_peer(
1716 set_initializing_client(CreateDtlsClientWithAlternateKey()));
1717 original_peer->pc()->Close();
1718
1719 SetSignalingReceivers();
1720 receiving_client()->SetExpectIceRestart(true);
1721 LocalP2PTest();
1722 VerifyRenderedAspectRatio(640, 480);
1723 }
1724
1725 // This test sets up a non-bundle call and apply bundle during ICE restart. When
1726 // bundle is in effect in the restart, the channel can successfully reset its
1727 // DTLS-SRTP context.
1728 TEST_F(P2PTestConductor, LocalP2PTestDtlsBundleInIceRestart) {
1729 MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1730 FakeConstraints setup_constraints;
1731 setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1732 true);
1733 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1734 receiving_client()->RemoveBundleFromReceivedSdp(true);
1735 LocalP2PTest();
1736 VerifyRenderedAspectRatio(640, 480);
1737
1738 initializing_client()->IceRestart();
1739 receiving_client()->SetExpectIceRestart(true);
1740 receiving_client()->RemoveBundleFromReceivedSdp(false);
1741 LocalP2PTest();
1742 VerifyRenderedAspectRatio(640, 480);
1743 }
1744
1745 // This test sets up a call transfer to a new callee with a different DTLS
1746 // fingerprint.
1747 TEST_F(P2PTestConductor, LocalP2PTestDtlsTransferCaller) {
1748 MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1749 SetupAndVerifyDtlsCall();
1750
1751 // Keeping the original peer around which will still send packets to the
1752 // receiving client. These SRTP packets will be dropped.
1753 std::unique_ptr<PeerConnectionTestClient> original_peer(
1754 set_receiving_client(CreateDtlsClientWithAlternateKey()));
1755 original_peer->pc()->Close();
1756
1757 SetSignalingReceivers();
1758 initializing_client()->IceRestart();
1759 LocalP2PTest();
1760 VerifyRenderedAspectRatio(640, 480);
1761 }
1762
1763 TEST_F(P2PTestConductor, LocalP2PTestCVO) {
1764 ASSERT_TRUE(CreateTestClients());
1765 SetCaptureRotation(webrtc::kVideoRotation_90);
1766 LocalP2PTest();
1767 VerifyRenderedAspectRatio(640, 480, webrtc::kVideoRotation_90);
1768 }
1769
1770 TEST_F(P2PTestConductor, LocalP2PTestReceiverDoesntSupportCVO) {
1771 ASSERT_TRUE(CreateTestClients());
1772 SetCaptureRotation(webrtc::kVideoRotation_90);
1773 receiving_client()->RemoveCvoFromReceivedSdp(true);
1774 LocalP2PTest();
1775 VerifyRenderedAspectRatio(480, 640, webrtc::kVideoRotation_0);
1776 }
1777
1778 // This test sets up a call between two endpoints that are configured to use
1779 // DTLS key agreement. The offerer don't support SDES. As a result, DTLS is
1780 // negotiated and used for transport.
1781 TEST_F(P2PTestConductor, LocalP2PTestOfferDtlsButNotSdes) {
1782 MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
1783 FakeConstraints setup_constraints;
1784 setup_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
1785 true);
1786 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
1787 receiving_client()->RemoveSdesCryptoFromReceivedSdp(true);
1788 LocalP2PTest();
1789 VerifyRenderedAspectRatio(640, 480);
1790 }
1791
1792 // This test verifies that the negotiation will succeed with data channel only
1793 // in max-bundle mode.
1794 TEST_F(P2PTestConductor, LocalP2PTestOfferDataChannelOnly) {
1795 webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;
1796 rtc_config.bundle_policy =
1797 webrtc::PeerConnectionInterface::kBundlePolicyMaxBundle;
1798 ASSERT_TRUE(CreateTestClients(rtc_config, rtc_config));
1799 initializing_client()->CreateDataChannel();
1800 initializing_client()->Negotiate();
1801 }
1802
1803 // This test sets up a Jsep call between two parties, and the callee only
1804 // accept to receive video.
1805 TEST_F(P2PTestConductor, LocalP2PTestAnswerVideo) {
1806 ASSERT_TRUE(CreateTestClients());
1807 receiving_client()->SetReceiveAudioVideo(false, true);
1808 LocalP2PTest();
1809 }
1810
1811 // This test sets up a Jsep call between two parties, and the callee only
1812 // accept to receive audio.
1813 TEST_F(P2PTestConductor, LocalP2PTestAnswerAudio) {
1814 ASSERT_TRUE(CreateTestClients());
1815 receiving_client()->SetReceiveAudioVideo(true, false);
1816 LocalP2PTest();
1817 }
1818
1819 // This test sets up a Jsep call between two parties, and the callee reject both
1820 // audio and video.
1821 TEST_F(P2PTestConductor, LocalP2PTestAnswerNone) {
1822 ASSERT_TRUE(CreateTestClients());
1823 receiving_client()->SetReceiveAudioVideo(false, false);
1824 LocalP2PTest();
1825 }
1826
1827 // This test sets up an audio and video call between two parties. After the call
1828 // runs for a while (10 frames), the caller sends an update offer with video
1829 // being rejected. Once the re-negotiation is done, the video flow should stop
1830 // and the audio flow should continue.
1831 TEST_F(P2PTestConductor, UpdateOfferWithRejectedContent) {
1832 ASSERT_TRUE(CreateTestClients());
1833 LocalP2PTest();
1834 TestUpdateOfferWithRejectedContent();
1835 }
1836
1837 // This test sets up a Jsep call between two parties. The MSID is removed from
1838 // the SDP strings from the caller.
1839 TEST_F(P2PTestConductor, LocalP2PTestWithoutMsid) {
1840 ASSERT_TRUE(CreateTestClients());
1841 receiving_client()->RemoveMsidFromReceivedSdp(true);
1842 // TODO(perkj): Currently there is a bug that cause audio to stop playing if
1843 // audio and video is muxed when MSID is disabled. Remove
1844 // SetRemoveBundleFromSdp once
1845 // https://code.google.com/p/webrtc/issues/detail?id=1193 is fixed.
1846 receiving_client()->RemoveBundleFromReceivedSdp(true);
1847 LocalP2PTest();
1848 }
1849
1850 TEST_F(P2PTestConductor, LocalP2PTestTwoStreams) {
1851 ASSERT_TRUE(CreateTestClients());
1852 // Set optional video constraint to max 320pixels to decrease CPU usage.
1853 FakeConstraints constraint;
1854 constraint.SetOptionalMaxWidth(320);
1855 SetVideoConstraints(constraint, constraint);
1856 initializing_client()->AddMediaStream(true, true);
1857 initializing_client()->AddMediaStream(false, true);
1858 ASSERT_EQ(2u, initializing_client()->NumberOfLocalMediaStreams());
1859 LocalP2PTest();
1860 EXPECT_EQ(2u, receiving_client()->number_of_remote_streams());
1861 }
1862
1863 // Test that we can receive the audio output level from a remote audio track.
1864 TEST_F(P2PTestConductor, GetAudioOutputLevelStats) {
1865 ASSERT_TRUE(CreateTestClients());
1866 LocalP2PTest();
1867
1868 StreamCollectionInterface* remote_streams =
1869 initializing_client()->remote_streams();
1870 ASSERT_GT(remote_streams->count(), 0u);
1871 ASSERT_GT(remote_streams->at(0)->GetAudioTracks().size(), 0u);
1872 MediaStreamTrackInterface* remote_audio_track =
1873 remote_streams->at(0)->GetAudioTracks()[0];
1874
1875 // Get the audio output level stats. Note that the level is not available
1876 // until a RTCP packet has been received.
1877 EXPECT_TRUE_WAIT(
1878 initializing_client()->GetAudioOutputLevelStats(remote_audio_track) > 0,
1879 kMaxWaitForStatsMs);
1880 }
1881
1882 // Test that an audio input level is reported.
1883 TEST_F(P2PTestConductor, GetAudioInputLevelStats) {
1884 ASSERT_TRUE(CreateTestClients());
1885 LocalP2PTest();
1886
1887 // Get the audio input level stats. The level should be available very
1888 // soon after the test starts.
1889 EXPECT_TRUE_WAIT(initializing_client()->GetAudioInputLevelStats() > 0,
1890 kMaxWaitForStatsMs);
1891 }
1892
1893 // Test that we can get incoming byte counts from both audio and video tracks.
1894 TEST_F(P2PTestConductor, GetBytesReceivedStats) {
1895 ASSERT_TRUE(CreateTestClients());
1896 LocalP2PTest();
1897
1898 StreamCollectionInterface* remote_streams =
1899 initializing_client()->remote_streams();
1900 ASSERT_GT(remote_streams->count(), 0u);
1901 ASSERT_GT(remote_streams->at(0)->GetAudioTracks().size(), 0u);
1902 MediaStreamTrackInterface* remote_audio_track =
1903 remote_streams->at(0)->GetAudioTracks()[0];
1904 EXPECT_TRUE_WAIT(
1905 initializing_client()->GetBytesReceivedStats(remote_audio_track) > 0,
1906 kMaxWaitForStatsMs);
1907
1908 MediaStreamTrackInterface* remote_video_track =
1909 remote_streams->at(0)->GetVideoTracks()[0];
1910 EXPECT_TRUE_WAIT(
1911 initializing_client()->GetBytesReceivedStats(remote_video_track) > 0,
1912 kMaxWaitForStatsMs);
1913 }
1914
1915 // Test that we can get outgoing byte counts from both audio and video tracks.
1916 TEST_F(P2PTestConductor, GetBytesSentStats) {
1917 ASSERT_TRUE(CreateTestClients());
1918 LocalP2PTest();
1919
1920 StreamCollectionInterface* local_streams =
1921 initializing_client()->local_streams();
1922 ASSERT_GT(local_streams->count(), 0u);
1923 ASSERT_GT(local_streams->at(0)->GetAudioTracks().size(), 0u);
1924 MediaStreamTrackInterface* local_audio_track =
1925 local_streams->at(0)->GetAudioTracks()[0];
1926 EXPECT_TRUE_WAIT(
1927 initializing_client()->GetBytesSentStats(local_audio_track) > 0,
1928 kMaxWaitForStatsMs);
1929
1930 MediaStreamTrackInterface* local_video_track =
1931 local_streams->at(0)->GetVideoTracks()[0];
1932 EXPECT_TRUE_WAIT(
1933 initializing_client()->GetBytesSentStats(local_video_track) > 0,
1934 kMaxWaitForStatsMs);
1935 }
1936
1937 // Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
1938 TEST_F(P2PTestConductor, GetDtls12None) {
1939 PeerConnectionFactory::Options init_options;
1940 init_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
1941 PeerConnectionFactory::Options recv_options;
1942 recv_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
1943 ASSERT_TRUE(CreateTestClients(nullptr, &init_options, nullptr, nullptr,
1944 &recv_options, nullptr));
1945 rtc::scoped_refptr<webrtc::FakeMetricsObserver>
1946 init_observer = new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1947 initializing_client()->pc()->RegisterUMAObserver(init_observer);
1948 LocalP2PTest();
1949
1950 EXPECT_TRUE_WAIT(
1951 rtc::SSLStreamAdapter::IsAcceptableCipher(
1952 initializing_client()->GetDtlsCipherStats(), rtc::KT_DEFAULT),
1953 kMaxWaitForStatsMs);
1954 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
1955 initializing_client()->GetSrtpCipherStats(),
1956 kMaxWaitForStatsMs);
1957 EXPECT_EQ(1,
1958 init_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1959 kDefaultSrtpCryptoSuite));
1960 }
1961
1962 // Test that DTLS 1.2 is used if both ends support it.
1963 TEST_F(P2PTestConductor, GetDtls12Both) {
1964 PeerConnectionFactory::Options init_options;
1965 init_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
1966 PeerConnectionFactory::Options recv_options;
1967 recv_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
1968 ASSERT_TRUE(CreateTestClients(nullptr, &init_options, nullptr, nullptr,
1969 &recv_options, nullptr));
1970 rtc::scoped_refptr<webrtc::FakeMetricsObserver>
1971 init_observer = new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1972 initializing_client()->pc()->RegisterUMAObserver(init_observer);
1973 LocalP2PTest();
1974
1975 EXPECT_TRUE_WAIT(
1976 rtc::SSLStreamAdapter::IsAcceptableCipher(
1977 initializing_client()->GetDtlsCipherStats(), rtc::KT_DEFAULT),
1978 kMaxWaitForStatsMs);
1979 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
1980 initializing_client()->GetSrtpCipherStats(),
1981 kMaxWaitForStatsMs);
1982 EXPECT_EQ(1,
1983 init_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1984 kDefaultSrtpCryptoSuite));
1985 }
1986
1987 // Test that DTLS 1.0 is used if the initator supports DTLS 1.2 and the
1988 // received supports 1.0.
1989 TEST_F(P2PTestConductor, GetDtls12Init) {
1990 PeerConnectionFactory::Options init_options;
1991 init_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
1992 PeerConnectionFactory::Options recv_options;
1993 recv_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
1994 ASSERT_TRUE(CreateTestClients(nullptr, &init_options, nullptr, nullptr,
1995 &recv_options, nullptr));
1996 rtc::scoped_refptr<webrtc::FakeMetricsObserver>
1997 init_observer = new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1998 initializing_client()->pc()->RegisterUMAObserver(init_observer);
1999 LocalP2PTest();
2000
2001 EXPECT_TRUE_WAIT(
2002 rtc::SSLStreamAdapter::IsAcceptableCipher(
2003 initializing_client()->GetDtlsCipherStats(), rtc::KT_DEFAULT),
2004 kMaxWaitForStatsMs);
2005 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
2006 initializing_client()->GetSrtpCipherStats(),
2007 kMaxWaitForStatsMs);
2008 EXPECT_EQ(1,
2009 init_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2010 kDefaultSrtpCryptoSuite));
2011 }
2012
2013 // Test that DTLS 1.0 is used if the initator supports DTLS 1.0 and the
2014 // received supports 1.2.
2015 TEST_F(P2PTestConductor, GetDtls12Recv) {
2016 PeerConnectionFactory::Options init_options;
2017 init_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2018 PeerConnectionFactory::Options recv_options;
2019 recv_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2020 ASSERT_TRUE(CreateTestClients(nullptr, &init_options, nullptr, nullptr,
2021 &recv_options, nullptr));
2022 rtc::scoped_refptr<webrtc::FakeMetricsObserver>
2023 init_observer = new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2024 initializing_client()->pc()->RegisterUMAObserver(init_observer);
2025 LocalP2PTest();
2026
2027 EXPECT_TRUE_WAIT(
2028 rtc::SSLStreamAdapter::IsAcceptableCipher(
2029 initializing_client()->GetDtlsCipherStats(), rtc::KT_DEFAULT),
2030 kMaxWaitForStatsMs);
2031 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
2032 initializing_client()->GetSrtpCipherStats(),
2033 kMaxWaitForStatsMs);
2034 EXPECT_EQ(1,
2035 init_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2036 kDefaultSrtpCryptoSuite));
2037 }
2038
2039 // Test that a non-GCM cipher is used if both sides only support non-GCM.
2040 TEST_F(P2PTestConductor, GetGcmNone) {
2041 TestGcmNegotiation(false, false, kDefaultSrtpCryptoSuite);
2042 }
2043
2044 // Test that a GCM cipher is used if both ends support it.
2045 TEST_F(P2PTestConductor, GetGcmBoth) {
2046 TestGcmNegotiation(true, true, kDefaultSrtpCryptoSuiteGcm);
2047 }
2048
2049 // Test that GCM isn't used if only the initiator supports it.
2050 TEST_F(P2PTestConductor, GetGcmInit) {
2051 TestGcmNegotiation(true, false, kDefaultSrtpCryptoSuite);
2052 }
2053
2054 // Test that GCM isn't used if only the receiver supports it.
2055 TEST_F(P2PTestConductor, GetGcmRecv) {
2056 TestGcmNegotiation(false, true, kDefaultSrtpCryptoSuite);
2057 }
2058
2059 // This test sets up a call between two parties with audio, video and an RTP
2060 // data channel.
2061 TEST_F(P2PTestConductor, LocalP2PTestRtpDataChannel) {
2062 FakeConstraints setup_constraints;
2063 setup_constraints.SetAllowRtpDataChannels();
2064 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
2065 initializing_client()->CreateDataChannel();
2066 LocalP2PTest();
2067 ASSERT_TRUE(initializing_client()->data_channel() != nullptr);
2068 ASSERT_TRUE(receiving_client()->data_channel() != nullptr);
2069 EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
2070 kMaxWaitMs);
2071 EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(),
2072 kMaxWaitMs);
2073
2074 std::string data = "hello world";
2075
2076 SendRtpData(initializing_client()->data_channel(), data);
2077 EXPECT_EQ_WAIT(data, receiving_client()->data_observer()->last_message(),
2078 kMaxWaitMs);
2079
2080 SendRtpData(receiving_client()->data_channel(), data);
2081 EXPECT_EQ_WAIT(data, initializing_client()->data_observer()->last_message(),
2082 kMaxWaitMs);
2083
2084 receiving_client()->data_channel()->Close();
2085 // Send new offer and answer.
2086 receiving_client()->Negotiate();
2087 EXPECT_FALSE(initializing_client()->data_observer()->IsOpen());
2088 EXPECT_FALSE(receiving_client()->data_observer()->IsOpen());
2089 }
2090
2091 // This test sets up a call between two parties with audio, video and an SCTP
2092 // data channel.
2093 TEST_F(P2PTestConductor, LocalP2PTestSctpDataChannel) {
2094 ASSERT_TRUE(CreateTestClients());
2095 initializing_client()->CreateDataChannel();
2096 LocalP2PTest();
2097 ASSERT_TRUE(initializing_client()->data_channel() != nullptr);
2098 EXPECT_TRUE_WAIT(receiving_client()->data_channel() != nullptr, kMaxWaitMs);
2099 EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
2100 kMaxWaitMs);
2101 EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(), kMaxWaitMs);
2102
2103 std::string data = "hello world";
2104
2105 initializing_client()->data_channel()->Send(DataBuffer(data));
2106 EXPECT_EQ_WAIT(data, receiving_client()->data_observer()->last_message(),
2107 kMaxWaitMs);
2108
2109 receiving_client()->data_channel()->Send(DataBuffer(data));
2110 EXPECT_EQ_WAIT(data, initializing_client()->data_observer()->last_message(),
2111 kMaxWaitMs);
2112
2113 receiving_client()->data_channel()->Close();
2114 EXPECT_TRUE_WAIT(!initializing_client()->data_observer()->IsOpen(),
2115 kMaxWaitMs);
2116 EXPECT_TRUE_WAIT(!receiving_client()->data_observer()->IsOpen(), kMaxWaitMs);
2117 }
2118
2119 TEST_F(P2PTestConductor, UnorderedSctpDataChannel) {
2120 ASSERT_TRUE(CreateTestClients());
2121 webrtc::DataChannelInit init;
2122 init.ordered = false;
2123 initializing_client()->CreateDataChannel(&init);
2124
2125 // Introduce random network delays.
2126 // Otherwise it's not a true "unordered" test.
2127 virtual_socket_server()->set_delay_mean(20);
2128 virtual_socket_server()->set_delay_stddev(5);
2129 virtual_socket_server()->UpdateDelayDistribution();
2130
2131 initializing_client()->Negotiate();
2132 ASSERT_TRUE(initializing_client()->data_channel() != nullptr);
2133 EXPECT_TRUE_WAIT(receiving_client()->data_channel() != nullptr, kMaxWaitMs);
2134 EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
2135 kMaxWaitMs);
2136 EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(), kMaxWaitMs);
2137
2138 static constexpr int kNumMessages = 100;
2139 // Deliberately chosen to be larger than the MTU so messages get fragmented.
2140 static constexpr size_t kMaxMessageSize = 4096;
2141 // Create and send random messages.
2142 std::vector<std::string> sent_messages;
2143 for (int i = 0; i < kNumMessages; ++i) {
2144 size_t length = (rand() % kMaxMessageSize) + 1;
2145 std::string message;
2146 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
2147 initializing_client()->data_channel()->Send(DataBuffer(message));
2148 receiving_client()->data_channel()->Send(DataBuffer(message));
2149 sent_messages.push_back(message);
2150 }
2151
2152 EXPECT_EQ_WAIT(
2153 kNumMessages,
2154 initializing_client()->data_observer()->received_message_count(),
2155 kMaxWaitMs);
2156 EXPECT_EQ_WAIT(kNumMessages,
2157 receiving_client()->data_observer()->received_message_count(),
2158 kMaxWaitMs);
2159
2160 // Sort and compare to make sure none of the messages were corrupted.
2161 std::vector<std::string> initializing_client_received_messages =
2162 initializing_client()->data_observer()->messages();
2163 std::vector<std::string> receiving_client_received_messages =
2164 receiving_client()->data_observer()->messages();
2165 std::sort(sent_messages.begin(), sent_messages.end());
2166 std::sort(initializing_client_received_messages.begin(),
2167 initializing_client_received_messages.end());
2168 std::sort(receiving_client_received_messages.begin(),
2169 receiving_client_received_messages.end());
2170 EXPECT_EQ(sent_messages, initializing_client_received_messages);
2171 EXPECT_EQ(sent_messages, receiving_client_received_messages);
2172
2173 receiving_client()->data_channel()->Close();
2174 EXPECT_TRUE_WAIT(!initializing_client()->data_observer()->IsOpen(),
2175 kMaxWaitMs);
2176 EXPECT_TRUE_WAIT(!receiving_client()->data_observer()->IsOpen(), kMaxWaitMs);
2177 }
2178
2179 // This test sets up a call between two parties and creates a data channel.
2180 // The test tests that received data is buffered unless an observer has been
2181 // registered.
2182 // Rtp data channels can receive data before the underlying
2183 // transport has detected that a channel is writable and thus data can be
2184 // received before the data channel state changes to open. That is hard to test
2185 // but the same buffering is used in that case.
2186 TEST_F(P2PTestConductor, RegisterDataChannelObserver) {
2187 FakeConstraints setup_constraints;
2188 setup_constraints.SetAllowRtpDataChannels();
2189 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
2190 initializing_client()->CreateDataChannel();
2191 initializing_client()->Negotiate();
2192
2193 ASSERT_TRUE(initializing_client()->data_channel() != nullptr);
2194 ASSERT_TRUE(receiving_client()->data_channel() != nullptr);
2195 EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
2196 kMaxWaitMs);
2197 EXPECT_EQ_WAIT(DataChannelInterface::kOpen,
2198 receiving_client()->data_channel()->state(), kMaxWaitMs);
2199
2200 // Unregister the existing observer.
2201 receiving_client()->data_channel()->UnregisterObserver();
2202
2203 std::string data = "hello world";
2204 SendRtpData(initializing_client()->data_channel(), data);
2205
2206 // Wait a while to allow the sent data to arrive before an observer is
2207 // registered..
2208 rtc::Thread::Current()->ProcessMessages(100);
2209
2210 MockDataChannelObserver new_observer(receiving_client()->data_channel());
2211 EXPECT_EQ_WAIT(data, new_observer.last_message(), kMaxWaitMs);
2212 }
2213
2214 // This test sets up a call between two parties with audio, video and but only
2215 // the initiating client support data.
2216 TEST_F(P2PTestConductor, LocalP2PTestReceiverDoesntSupportData) {
2217 FakeConstraints setup_constraints_1;
2218 setup_constraints_1.SetAllowRtpDataChannels();
2219 // Must disable DTLS to make negotiation succeed.
2220 setup_constraints_1.SetMandatory(
2221 MediaConstraintsInterface::kEnableDtlsSrtp, false);
2222 FakeConstraints setup_constraints_2;
2223 setup_constraints_2.SetMandatory(
2224 MediaConstraintsInterface::kEnableDtlsSrtp, false);
2225 ASSERT_TRUE(CreateTestClients(&setup_constraints_1, &setup_constraints_2));
2226 initializing_client()->CreateDataChannel();
2227 LocalP2PTest();
2228 EXPECT_TRUE(initializing_client()->data_channel() != nullptr);
2229 EXPECT_FALSE(receiving_client()->data_channel());
2230 EXPECT_FALSE(initializing_client()->data_observer()->IsOpen());
2231 }
2232
2233 // This test sets up a call between two parties with audio, video. When audio
2234 // and video is setup and flowing and data channel is negotiated.
2235 TEST_F(P2PTestConductor, AddDataChannelAfterRenegotiation) {
2236 FakeConstraints setup_constraints;
2237 setup_constraints.SetAllowRtpDataChannels();
2238 ASSERT_TRUE(CreateTestClients(&setup_constraints, &setup_constraints));
2239 LocalP2PTest();
2240 initializing_client()->CreateDataChannel();
2241 // Send new offer and answer.
2242 initializing_client()->Negotiate();
2243 ASSERT_TRUE(initializing_client()->data_channel() != nullptr);
2244 ASSERT_TRUE(receiving_client()->data_channel() != nullptr);
2245 EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
2246 kMaxWaitMs);
2247 EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(),
2248 kMaxWaitMs);
2249 }
2250
2251 // This test sets up a Jsep call with SCTP DataChannel and verifies the
2252 // negotiation is completed without error.
2253 #ifdef HAVE_SCTP
2254 TEST_F(P2PTestConductor, CreateOfferWithSctpDataChannel) {
2255 MAYBE_SKIP_TEST(rtc::SSLStreamAdapter::HaveDtlsSrtp);
2256 FakeConstraints constraints;
2257 constraints.SetMandatory(
2258 MediaConstraintsInterface::kEnableDtlsSrtp, true);
2259 ASSERT_TRUE(CreateTestClients(&constraints, &constraints));
2260 initializing_client()->CreateDataChannel();
2261 initializing_client()->Negotiate(false, false);
2262 }
2263 #endif
2264
2265 // This test sets up a call between two parties with audio, and video.
2266 // During the call, the initializing side restart ice and the test verifies that
2267 // new ice candidates are generated and audio and video still can flow.
2268 TEST_F(P2PTestConductor, IceRestart) {
2269 ASSERT_TRUE(CreateTestClients());
2270
2271 // Negotiate and wait for ice completion and make sure audio and video plays.
2272 LocalP2PTest();
2273
2274 // Create a SDP string of the first audio candidate for both clients.
2275 const webrtc::IceCandidateCollection* audio_candidates_initiator =
2276 initializing_client()->pc()->local_description()->candidates(0);
2277 const webrtc::IceCandidateCollection* audio_candidates_receiver =
2278 receiving_client()->pc()->local_description()->candidates(0);
2279 ASSERT_GT(audio_candidates_initiator->count(), 0u);
2280 ASSERT_GT(audio_candidates_receiver->count(), 0u);
2281 std::string initiator_candidate;
2282 EXPECT_TRUE(
2283 audio_candidates_initiator->at(0)->ToString(&initiator_candidate));
2284 std::string receiver_candidate;
2285 EXPECT_TRUE(audio_candidates_receiver->at(0)->ToString(&receiver_candidate));
2286
2287 // Restart ice on the initializing client.
2288 receiving_client()->SetExpectIceRestart(true);
2289 initializing_client()->IceRestart();
2290
2291 // Negotiate and wait for ice completion again and make sure audio and video
2292 // plays.
2293 LocalP2PTest();
2294
2295 // Create a SDP string of the first audio candidate for both clients again.
2296 const webrtc::IceCandidateCollection* audio_candidates_initiator_restart =
2297 initializing_client()->pc()->local_description()->candidates(0);
2298 const webrtc::IceCandidateCollection* audio_candidates_reciever_restart =
2299 receiving_client()->pc()->local_description()->candidates(0);
2300 ASSERT_GT(audio_candidates_initiator_restart->count(), 0u);
2301 ASSERT_GT(audio_candidates_reciever_restart->count(), 0u);
2302 std::string initiator_candidate_restart;
2303 EXPECT_TRUE(audio_candidates_initiator_restart->at(0)->ToString(
2304 &initiator_candidate_restart));
2305 std::string receiver_candidate_restart;
2306 EXPECT_TRUE(audio_candidates_reciever_restart->at(0)->ToString(
2307 &receiver_candidate_restart));
2308
2309 // Verify that the first candidates in the local session descriptions has
2310 // changed.
2311 EXPECT_NE(initiator_candidate, initiator_candidate_restart);
2312 EXPECT_NE(receiver_candidate, receiver_candidate_restart);
2313 }
2314
2315 TEST_F(P2PTestConductor, IceRenominationDisabled) {
2316 PeerConnectionInterface::RTCConfiguration config;
2317 config.enable_ice_renomination = false;
2318 ASSERT_TRUE(CreateTestClients(config, config));
2319 LocalP2PTest();
2320
2321 initializing_client()->VerifyLocalIceRenomination();
2322 receiving_client()->VerifyLocalIceRenomination();
2323 initializing_client()->VerifyRemoteIceRenomination();
2324 receiving_client()->VerifyRemoteIceRenomination();
2325 }
2326
2327 TEST_F(P2PTestConductor, IceRenominationEnabled) {
2328 PeerConnectionInterface::RTCConfiguration config;
2329 config.enable_ice_renomination = true;
2330 ASSERT_TRUE(CreateTestClients(config, config));
2331 initializing_client()->SetExpectIceRenomination(true);
2332 initializing_client()->SetExpectRemoteIceRenomination(true);
2333 receiving_client()->SetExpectIceRenomination(true);
2334 receiving_client()->SetExpectRemoteIceRenomination(true);
2335 LocalP2PTest();
2336
2337 initializing_client()->VerifyLocalIceRenomination();
2338 receiving_client()->VerifyLocalIceRenomination();
2339 initializing_client()->VerifyRemoteIceRenomination();
2340 receiving_client()->VerifyRemoteIceRenomination();
2341 }
2342
2343 // This test sets up a call between two parties with audio, and video.
2344 // It then renegotiates setting the video m-line to "port 0", then later
2345 // renegotiates again, enabling video.
2346 TEST_F(P2PTestConductor, LocalP2PTestVideoDisableEnable) {
2347 ASSERT_TRUE(CreateTestClients());
2348
2349 // Do initial negotiation. Will result in video and audio sendonly m-lines.
2350 receiving_client()->set_auto_add_stream(false);
2351 initializing_client()->AddMediaStream(true, true);
2352 initializing_client()->Negotiate();
2353
2354 // Negotiate again, disabling the video m-line (receiving client will
2355 // set port to 0 due to mandatory "OfferToReceiveVideo: false" constraint).
2356 receiving_client()->SetReceiveVideo(false);
2357 initializing_client()->Negotiate();
2358
2359 // Enable video and do negotiation again, making sure video is received
2360 // end-to-end.
2361 receiving_client()->SetReceiveVideo(true);
2362 receiving_client()->AddMediaStream(true, true);
2363 LocalP2PTest();
2364 }
2365
2366 // This test sets up a Jsep call between two parties with external
2367 // VideoDecoderFactory.
2368 // TODO(holmer): Disabled due to sometimes crashing on buildbots.
2369 // See issue webrtc/2378.
2370 TEST_F(P2PTestConductor, DISABLED_LocalP2PTestWithVideoDecoderFactory) {
2371 ASSERT_TRUE(CreateTestClients());
2372 EnableVideoDecoderFactory();
2373 LocalP2PTest();
2374 }
2375
2376 // This tests that if we negotiate after calling CreateSender but before we
2377 // have a track, then set a track later, frames from the newly-set track are
2378 // received end-to-end.
2379 TEST_F(P2PTestConductor, EarlyWarmupTest) {
2380 ASSERT_TRUE(CreateTestClients());
2381 auto audio_sender =
2382 initializing_client()->pc()->CreateSender("audio", "stream_id");
2383 auto video_sender =
2384 initializing_client()->pc()->CreateSender("video", "stream_id");
2385 initializing_client()->Negotiate();
2386 // Wait for ICE connection to complete, without any tracks.
2387 // Note that the receiving client WILL (in HandleIncomingOffer) create
2388 // tracks, so it's only the initiator here that's doing early warmup.
2389 ASSERT_TRUE_WAIT(SessionActive(), kMaxWaitForActivationMs);
2390 VerifySessionDescriptions();
2391 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2392 initializing_client()->ice_connection_state(),
2393 kMaxWaitForFramesMs);
2394 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2395 receiving_client()->ice_connection_state(),
2396 kMaxWaitForFramesMs);
2397 // Now set the tracks, and expect frames to immediately start flowing.
2398 EXPECT_TRUE(
2399 audio_sender->SetTrack(initializing_client()->CreateLocalAudioTrack("")));
2400 EXPECT_TRUE(
2401 video_sender->SetTrack(initializing_client()->CreateLocalVideoTrack("")));
2402 EXPECT_TRUE_WAIT(FramesHaveArrived(kEndAudioFrameCount, kEndVideoFrameCount),
2403 kMaxWaitForFramesMs);
2404 }
2405
2406 #ifdef HAVE_QUIC
2407 // This test sets up a call between two parties using QUIC instead of DTLS for
2408 // audio and video, and a QUIC data channel.
2409 TEST_F(P2PTestConductor, LocalP2PTestQuicDataChannel) {
2410 PeerConnectionInterface::RTCConfiguration quic_config;
2411 quic_config.enable_quic = true;
2412 ASSERT_TRUE(CreateTestClients(quic_config, quic_config));
2413 webrtc::DataChannelInit init;
2414 init.ordered = false;
2415 init.reliable = true;
2416 init.id = 1;
2417 initializing_client()->CreateDataChannel(&init);
2418 receiving_client()->CreateDataChannel(&init);
2419 LocalP2PTest();
2420 ASSERT_NE(nullptr, initializing_client()->data_channel());
2421 ASSERT_NE(nullptr, receiving_client()->data_channel());
2422 EXPECT_TRUE_WAIT(initializing_client()->data_observer()->IsOpen(),
2423 kMaxWaitMs);
2424 EXPECT_TRUE_WAIT(receiving_client()->data_observer()->IsOpen(), kMaxWaitMs);
2425
2426 std::string data = "hello world";
2427
2428 initializing_client()->data_channel()->Send(DataBuffer(data));
2429 EXPECT_EQ_WAIT(data, receiving_client()->data_observer()->last_message(),
2430 kMaxWaitMs);
2431
2432 receiving_client()->data_channel()->Send(DataBuffer(data));
2433 EXPECT_EQ_WAIT(data, initializing_client()->data_observer()->last_message(),
2434 kMaxWaitMs);
2435 }
2436
2437 // Tests that negotiation of QUIC data channels is completed without error.
2438 TEST_F(P2PTestConductor, NegotiateQuicDataChannel) {
2439 PeerConnectionInterface::RTCConfiguration quic_config;
2440 quic_config.enable_quic = true;
2441 ASSERT_TRUE(CreateTestClients(quic_config, quic_config));
2442 FakeConstraints constraints;
2443 constraints.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp, true);
2444 ASSERT_TRUE(CreateTestClients(&constraints, &constraints));
2445 webrtc::DataChannelInit init;
2446 init.ordered = false;
2447 init.reliable = true;
2448 init.id = 1;
2449 initializing_client()->CreateDataChannel(&init);
2450 initializing_client()->Negotiate(false, false);
2451 }
2452
2453 // This test sets up a JSEP call using QUIC. The callee only receives video.
2454 TEST_F(P2PTestConductor, LocalP2PTestVideoOnlyWithQuic) {
2455 PeerConnectionInterface::RTCConfiguration quic_config;
2456 quic_config.enable_quic = true;
2457 ASSERT_TRUE(CreateTestClients(quic_config, quic_config));
2458 receiving_client()->SetReceiveAudioVideo(false, true);
2459 LocalP2PTest();
2460 }
2461
2462 // This test sets up a JSEP call using QUIC. The callee only receives audio.
2463 TEST_F(P2PTestConductor, LocalP2PTestAudioOnlyWithQuic) {
2464 PeerConnectionInterface::RTCConfiguration quic_config;
2465 quic_config.enable_quic = true;
2466 ASSERT_TRUE(CreateTestClients(quic_config, quic_config));
2467 receiving_client()->SetReceiveAudioVideo(true, false);
2468 LocalP2PTest();
2469 }
2470
2471 // This test sets up a JSEP call using QUIC. The callee rejects both audio and
2472 // video.
2473 TEST_F(P2PTestConductor, LocalP2PTestNoVideoAudioWithQuic) {
2474 PeerConnectionInterface::RTCConfiguration quic_config;
2475 quic_config.enable_quic = true;
2476 ASSERT_TRUE(CreateTestClients(quic_config, quic_config));
2477 receiving_client()->SetReceiveAudioVideo(false, false);
2478 LocalP2PTest();
2479 }
2480
2481 #endif // HAVE_QUIC
2482
2483 TEST_F(P2PTestConductor, ForwardVideoOnlyStream) {
2484 ASSERT_TRUE(CreateTestClients());
2485 // One-way stream
2486 receiving_client()->set_auto_add_stream(false);
2487 // Video only, audio forwarding not expected to work.
2488 initializing_client()->AddMediaStream(false, true);
2489 initializing_client()->Negotiate();
2490
2491 ASSERT_TRUE_WAIT(SessionActive(), kMaxWaitForActivationMs);
2492 VerifySessionDescriptions();
2493
2494 ASSERT_TRUE(initializing_client()->can_receive_video());
2495 ASSERT_TRUE(receiving_client()->can_receive_video());
2496
2497 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2498 initializing_client()->ice_connection_state(),
2499 kMaxWaitForFramesMs);
2500 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2501 receiving_client()->ice_connection_state(),
2502 kMaxWaitForFramesMs);
2503
2504 ASSERT_TRUE(receiving_client()->remote_streams()->count() == 1);
2505
2506 // Echo the stream back.
2507 receiving_client()->pc()->AddStream(
2508 receiving_client()->remote_streams()->at(0));
2509 receiving_client()->Negotiate();
2510
2511 EXPECT_TRUE_WAIT(
2512 initializing_client()->VideoFramesReceivedCheck(kEndVideoFrameCount),
2513 kMaxWaitForFramesMs);
2514 }
2515
2516 // Test that we achieve the expected end-to-end connection time, using a
2517 // fake clock and simulated latency on the media and signaling paths.
2518 // We use a TURN<->TURN connection because this is usually the quickest to
2519 // set up initially, especially when we're confident the connection will work
2520 // and can start sending media before we get a STUN response.
2521 //
2522 // With various optimizations enabled, here are the network delays we expect to
2523 // be on the critical path:
2524 // 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
2525 // signaling answer (with DTLS fingerprint).
2526 // 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
2527 // using TURN<->TURN pair, and DTLS exchange is 4 packets,
2528 // the first of which should have arrived before the answer.
2529 TEST_F(P2PTestConductor, EndToEndConnectionTimeWithTurnTurnPair) {
2530 rtc::ScopedFakeClock fake_clock;
2531 // Some things use a time of "0" as a special value, so we need to start out
2532 // the fake clock at a nonzero time.
2533 // TODO(deadbeef): Fix this.
2534 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2535
2536 static constexpr int media_hop_delay_ms = 50;
2537 static constexpr int signaling_trip_delay_ms = 500;
2538 // For explanation of these values, see comment above.
2539 static constexpr int required_media_hops = 9;
2540 static constexpr int required_signaling_trips = 2;
2541 // For internal delays (such as posting an event asychronously).
2542 static constexpr int allowed_internal_delay_ms = 20;
2543 static constexpr int total_connection_time_ms =
2544 media_hop_delay_ms * required_media_hops +
2545 signaling_trip_delay_ms * required_signaling_trips +
2546 allowed_internal_delay_ms;
2547
2548 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
2549 3478};
2550 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
2551 0};
2552 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
2553 3478};
2554 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
2555 0};
2556 cricket::TestTurnServer turn_server_1(network_thread(),
2557 turn_server_1_internal_address,
2558 turn_server_1_external_address);
2559 cricket::TestTurnServer turn_server_2(network_thread(),
2560 turn_server_2_internal_address,
2561 turn_server_2_external_address);
2562 // Bypass permission check on received packets so media can be sent before
2563 // the candidate is signaled.
2564 turn_server_1.set_enable_permission_checks(false);
2565 turn_server_2.set_enable_permission_checks(false);
2566
2567 PeerConnectionInterface::RTCConfiguration client_1_config;
2568 webrtc::PeerConnectionInterface::IceServer ice_server_1;
2569 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
2570 ice_server_1.username = "test";
2571 ice_server_1.password = "test";
2572 client_1_config.servers.push_back(ice_server_1);
2573 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
2574 client_1_config.presume_writable_when_fully_relayed = true;
2575
2576 PeerConnectionInterface::RTCConfiguration client_2_config;
2577 webrtc::PeerConnectionInterface::IceServer ice_server_2;
2578 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
2579 ice_server_2.username = "test";
2580 ice_server_2.password = "test";
2581 client_2_config.servers.push_back(ice_server_2);
2582 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
2583 client_2_config.presume_writable_when_fully_relayed = true;
2584
2585 ASSERT_TRUE(CreateTestClients(client_1_config, client_2_config));
2586 // Set up the simulated delays.
2587 SetSignalingDelayMs(signaling_trip_delay_ms);
2588 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
2589 virtual_socket_server()->UpdateDelayDistribution();
2590
2591 initializing_client()->SetOfferToReceiveAudioVideo(true, true);
2592 initializing_client()->Negotiate();
2593 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
2594 // are connected. This is an important distinction. Once we have separate ICE
2595 // and DTLS state, this check needs to use the DTLS state.
2596 EXPECT_TRUE_SIMULATED_WAIT(
2597 (receiving_client()->ice_connection_state() ==
2598 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
2599 receiving_client()->ice_connection_state() ==
2600 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
2601 (initializing_client()->ice_connection_state() ==
2602 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
2603 initializing_client()->ice_connection_state() ==
2604 webrtc::PeerConnectionInterface::kIceConnectionCompleted),
2605 total_connection_time_ms, fake_clock);
2606 // Need to free the clients here since they're using things we created on
2607 // the stack.
2608 delete set_initializing_client(nullptr);
2609 delete set_receiving_client(nullptr);
2610 }
2611
2612 class IceServerParsingTest : public testing::Test {
2613 public:
2614 // Convenience for parsing a single URL.
2615 bool ParseUrl(const std::string& url) {
2616 return ParseUrl(url, std::string(), std::string());
2617 }
2618
2619 bool ParseUrl(const std::string& url,
2620 const std::string& username,
2621 const std::string& password) {
2622 PeerConnectionInterface::IceServers servers;
2623 PeerConnectionInterface::IceServer server;
2624 server.urls.push_back(url);
2625 server.username = username;
2626 server.password = password;
2627 servers.push_back(server);
2628 return webrtc::ParseIceServers(servers, &stun_servers_, &turn_servers_);
2629 }
2630
2631 protected:
2632 cricket::ServerAddresses stun_servers_;
2633 std::vector<cricket::RelayServerConfig> turn_servers_;
2634 };
2635
2636 // Make sure all STUN/TURN prefixes are parsed correctly.
2637 TEST_F(IceServerParsingTest, ParseStunPrefixes) {
2638 EXPECT_TRUE(ParseUrl("stun:hostname"));
2639 EXPECT_EQ(1U, stun_servers_.size());
2640 EXPECT_EQ(0U, turn_servers_.size());
2641 stun_servers_.clear();
2642
2643 EXPECT_TRUE(ParseUrl("stuns:hostname"));
2644 EXPECT_EQ(1U, stun_servers_.size());
2645 EXPECT_EQ(0U, turn_servers_.size());
2646 stun_servers_.clear();
2647
2648 EXPECT_TRUE(ParseUrl("turn:hostname"));
2649 EXPECT_EQ(0U, stun_servers_.size());
2650 EXPECT_EQ(1U, turn_servers_.size());
2651 EXPECT_FALSE(turn_servers_[0].ports[0].secure);
2652 turn_servers_.clear();
2653
2654 EXPECT_TRUE(ParseUrl("turns:hostname"));
2655 EXPECT_EQ(0U, stun_servers_.size());
2656 EXPECT_EQ(1U, turn_servers_.size());
2657 EXPECT_TRUE(turn_servers_[0].ports[0].secure);
2658 turn_servers_.clear();
2659
2660 // invalid prefixes
2661 EXPECT_FALSE(ParseUrl("stunn:hostname"));
2662 EXPECT_FALSE(ParseUrl(":hostname"));
2663 EXPECT_FALSE(ParseUrl(":"));
2664 EXPECT_FALSE(ParseUrl(""));
2665 }
2666
2667 TEST_F(IceServerParsingTest, VerifyDefaults) {
2668 // TURNS defaults
2669 EXPECT_TRUE(ParseUrl("turns:hostname"));
2670 EXPECT_EQ(1U, turn_servers_.size());
2671 EXPECT_EQ(5349, turn_servers_[0].ports[0].address.port());
2672 EXPECT_EQ(cricket::PROTO_TCP, turn_servers_[0].ports[0].proto);
2673 turn_servers_.clear();
2674
2675 // TURN defaults
2676 EXPECT_TRUE(ParseUrl("turn:hostname"));
2677 EXPECT_EQ(1U, turn_servers_.size());
2678 EXPECT_EQ(3478, turn_servers_[0].ports[0].address.port());
2679 EXPECT_EQ(cricket::PROTO_UDP, turn_servers_[0].ports[0].proto);
2680 turn_servers_.clear();
2681
2682 // STUN defaults
2683 EXPECT_TRUE(ParseUrl("stun:hostname"));
2684 EXPECT_EQ(1U, stun_servers_.size());
2685 EXPECT_EQ(3478, stun_servers_.begin()->port());
2686 stun_servers_.clear();
2687 }
2688
2689 // Check that the 6 combinations of IPv4/IPv6/hostname and with/without port
2690 // can be parsed correctly.
2691 TEST_F(IceServerParsingTest, ParseHostnameAndPort) {
2692 EXPECT_TRUE(ParseUrl("stun:1.2.3.4:1234"));
2693 EXPECT_EQ(1U, stun_servers_.size());
2694 EXPECT_EQ("1.2.3.4", stun_servers_.begin()->hostname());
2695 EXPECT_EQ(1234, stun_servers_.begin()->port());
2696 stun_servers_.clear();
2697
2698 EXPECT_TRUE(ParseUrl("stun:[1:2:3:4:5:6:7:8]:4321"));
2699 EXPECT_EQ(1U, stun_servers_.size());
2700 EXPECT_EQ("1:2:3:4:5:6:7:8", stun_servers_.begin()->hostname());
2701 EXPECT_EQ(4321, stun_servers_.begin()->port());
2702 stun_servers_.clear();
2703
2704 EXPECT_TRUE(ParseUrl("stun:hostname:9999"));
2705 EXPECT_EQ(1U, stun_servers_.size());
2706 EXPECT_EQ("hostname", stun_servers_.begin()->hostname());
2707 EXPECT_EQ(9999, stun_servers_.begin()->port());
2708 stun_servers_.clear();
2709
2710 EXPECT_TRUE(ParseUrl("stun:1.2.3.4"));
2711 EXPECT_EQ(1U, stun_servers_.size());
2712 EXPECT_EQ("1.2.3.4", stun_servers_.begin()->hostname());
2713 EXPECT_EQ(3478, stun_servers_.begin()->port());
2714 stun_servers_.clear();
2715
2716 EXPECT_TRUE(ParseUrl("stun:[1:2:3:4:5:6:7:8]"));
2717 EXPECT_EQ(1U, stun_servers_.size());
2718 EXPECT_EQ("1:2:3:4:5:6:7:8", stun_servers_.begin()->hostname());
2719 EXPECT_EQ(3478, stun_servers_.begin()->port());
2720 stun_servers_.clear();
2721
2722 EXPECT_TRUE(ParseUrl("stun:hostname"));
2723 EXPECT_EQ(1U, stun_servers_.size());
2724 EXPECT_EQ("hostname", stun_servers_.begin()->hostname());
2725 EXPECT_EQ(3478, stun_servers_.begin()->port());
2726 stun_servers_.clear();
2727
2728 // Try some invalid hostname:port strings.
2729 EXPECT_FALSE(ParseUrl("stun:hostname:99a99"));
2730 EXPECT_FALSE(ParseUrl("stun:hostname:-1"));
2731 EXPECT_FALSE(ParseUrl("stun:hostname:port:more"));
2732 EXPECT_FALSE(ParseUrl("stun:hostname:port more"));
2733 EXPECT_FALSE(ParseUrl("stun:hostname:"));
2734 EXPECT_FALSE(ParseUrl("stun:[1:2:3:4:5:6:7:8]junk:1000"));
2735 EXPECT_FALSE(ParseUrl("stun::5555"));
2736 EXPECT_FALSE(ParseUrl("stun:"));
2737 }
2738
2739 // Test parsing the "?transport=xxx" part of the URL.
2740 TEST_F(IceServerParsingTest, ParseTransport) {
2741 EXPECT_TRUE(ParseUrl("turn:hostname:1234?transport=tcp"));
2742 EXPECT_EQ(1U, turn_servers_.size());
2743 EXPECT_EQ(cricket::PROTO_TCP, turn_servers_[0].ports[0].proto);
2744 turn_servers_.clear();
2745
2746 EXPECT_TRUE(ParseUrl("turn:hostname?transport=udp"));
2747 EXPECT_EQ(1U, turn_servers_.size());
2748 EXPECT_EQ(cricket::PROTO_UDP, turn_servers_[0].ports[0].proto);
2749 turn_servers_.clear();
2750
2751 EXPECT_FALSE(ParseUrl("turn:hostname?transport=invalid"));
2752 }
2753
2754 // Test parsing ICE username contained in URL.
2755 TEST_F(IceServerParsingTest, ParseUsername) {
2756 EXPECT_TRUE(ParseUrl("turn:user@hostname"));
2757 EXPECT_EQ(1U, turn_servers_.size());
2758 EXPECT_EQ("user", turn_servers_[0].credentials.username);
2759 turn_servers_.clear();
2760
2761 EXPECT_FALSE(ParseUrl("turn:@hostname"));
2762 EXPECT_FALSE(ParseUrl("turn:username@"));
2763 EXPECT_FALSE(ParseUrl("turn:@"));
2764 EXPECT_FALSE(ParseUrl("turn:user@name@hostname"));
2765 }
2766
2767 // Test that username and password from IceServer is copied into the resulting
2768 // RelayServerConfig.
2769 TEST_F(IceServerParsingTest, CopyUsernameAndPasswordFromIceServer) {
2770 EXPECT_TRUE(ParseUrl("turn:hostname", "username", "password"));
2771 EXPECT_EQ(1U, turn_servers_.size());
2772 EXPECT_EQ("username", turn_servers_[0].credentials.username);
2773 EXPECT_EQ("password", turn_servers_[0].credentials.password);
2774 }
2775
2776 // Ensure that if a server has multiple URLs, each one is parsed.
2777 TEST_F(IceServerParsingTest, ParseMultipleUrls) {
2778 PeerConnectionInterface::IceServers servers;
2779 PeerConnectionInterface::IceServer server;
2780 server.urls.push_back("stun:hostname");
2781 server.urls.push_back("turn:hostname");
2782 servers.push_back(server);
2783 EXPECT_TRUE(webrtc::ParseIceServers(servers, &stun_servers_, &turn_servers_));
2784 EXPECT_EQ(1U, stun_servers_.size());
2785 EXPECT_EQ(1U, turn_servers_.size());
2786 }
2787
2788 // Ensure that TURN servers are given unique priorities,
2789 // so that their resulting candidates have unique priorities.
2790 TEST_F(IceServerParsingTest, TurnServerPrioritiesUnique) {
2791 PeerConnectionInterface::IceServers servers;
2792 PeerConnectionInterface::IceServer server;
2793 server.urls.push_back("turn:hostname");
2794 server.urls.push_back("turn:hostname2");
2795 servers.push_back(server);
2796 EXPECT_TRUE(webrtc::ParseIceServers(servers, &stun_servers_, &turn_servers_));
2797 EXPECT_EQ(2U, turn_servers_.size());
2798 EXPECT_NE(turn_servers_[0].priority, turn_servers_[1].priority);
2799 }
2800
2801 #endif // if !defined(THREAD_SANITIZER)
2802
2803 } // namespace
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698