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

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

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

Powered by Google App Engine
This is Rietveld 408576698