blob: 12b99b49020ab44cc9f78c05534053be54ef6213 [file] [log] [blame]
deadbeef1dcb1642017-03-29 21:08:16 -07001/*
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// Disable for TSan v2, see
12// https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
13#if !defined(THREAD_SANITIZER)
14
15#include <stdio.h>
16
17#include <algorithm>
18#include <functional>
19#include <list>
20#include <map>
21#include <memory>
22#include <utility>
23#include <vector>
24
25#include "webrtc/api/fakemetricsobserver.h"
26#include "webrtc/api/mediastreaminterface.h"
27#include "webrtc/api/peerconnectioninterface.h"
28#include "webrtc/api/test/fakeconstraints.h"
Henrik Kjellandera80c16a2017-07-01 16:48:15 +020029#include "webrtc/base/asyncinvoker.h"
30#include "webrtc/base/fakenetwork.h"
31#include "webrtc/base/gunit.h"
32#include "webrtc/base/helpers.h"
33#include "webrtc/base/ssladapter.h"
34#include "webrtc/base/sslstreamadapter.h"
35#include "webrtc/base/thread.h"
36#include "webrtc/base/virtualsocketserver.h"
deadbeef1dcb1642017-03-29 21:08:16 -070037#include "webrtc/media/engine/fakewebrtcvideoengine.h"
38#include "webrtc/p2p/base/p2pconstants.h"
39#include "webrtc/p2p/base/portinterface.h"
40#include "webrtc/p2p/base/sessiondescription.h"
41#include "webrtc/p2p/base/testturnserver.h"
42#include "webrtc/p2p/client/basicportallocator.h"
43#include "webrtc/pc/dtmfsender.h"
44#include "webrtc/pc/localaudiosource.h"
45#include "webrtc/pc/mediasession.h"
46#include "webrtc/pc/peerconnection.h"
47#include "webrtc/pc/peerconnectionfactory.h"
48#include "webrtc/pc/test/fakeaudiocapturemodule.h"
49#include "webrtc/pc/test/fakeperiodicvideocapturer.h"
50#include "webrtc/pc/test/fakertccertificategenerator.h"
51#include "webrtc/pc/test/fakevideotrackrenderer.h"
52#include "webrtc/pc/test/mockpeerconnectionobservers.h"
53
54using cricket::ContentInfo;
55using cricket::FakeWebRtcVideoDecoder;
56using cricket::FakeWebRtcVideoDecoderFactory;
57using cricket::FakeWebRtcVideoEncoder;
58using cricket::FakeWebRtcVideoEncoderFactory;
59using cricket::MediaContentDescription;
60using webrtc::DataBuffer;
61using webrtc::DataChannelInterface;
62using webrtc::DtmfSender;
63using webrtc::DtmfSenderInterface;
64using webrtc::DtmfSenderObserverInterface;
65using webrtc::FakeConstraints;
66using webrtc::MediaConstraintsInterface;
67using webrtc::MediaStreamInterface;
68using webrtc::MediaStreamTrackInterface;
69using webrtc::MockCreateSessionDescriptionObserver;
70using webrtc::MockDataChannelObserver;
71using webrtc::MockSetSessionDescriptionObserver;
72using webrtc::MockStatsObserver;
73using webrtc::ObserverInterface;
74using webrtc::PeerConnectionInterface;
75using webrtc::PeerConnectionFactory;
76using webrtc::SessionDescriptionInterface;
77using webrtc::StreamCollectionInterface;
78
79namespace {
80
81static const int kDefaultTimeout = 10000;
82static const int kMaxWaitForStatsMs = 3000;
83static const int kMaxWaitForActivationMs = 5000;
84static const int kMaxWaitForFramesMs = 10000;
85// Default number of audio/video frames to wait for before considering a test
86// successful.
87static const int kDefaultExpectedAudioFrameCount = 3;
88static const int kDefaultExpectedVideoFrameCount = 3;
89
90static const char kDefaultStreamLabel[] = "stream_label";
91static const char kDefaultVideoTrackId[] = "video_track";
92static const char kDefaultAudioTrackId[] = "audio_track";
93static const char kDataChannelLabel[] = "data_channel";
94
95// SRTP cipher name negotiated by the tests. This must be updated if the
96// default changes.
97static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_32;
98static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
99
100// Helper function for constructing offer/answer options to initiate an ICE
101// restart.
102PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
103 PeerConnectionInterface::RTCOfferAnswerOptions options;
104 options.ice_restart = true;
105 return options;
106}
107
deadbeefd8ad7882017-04-18 16:01:17 -0700108// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
109// attribute from received SDP, simulating a legacy endpoint.
110void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
111 for (ContentInfo& content : desc->contents()) {
112 MediaContentDescription* media_desc =
113 static_cast<MediaContentDescription*>(content.description);
114 media_desc->mutable_streams().clear();
115 }
116 desc->set_msid_supported(false);
117}
118
zhihuangf8164932017-05-19 13:09:47 -0700119int FindFirstMediaStatsIndexByKind(
120 const std::string& kind,
121 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
122 media_stats_vec) {
123 for (size_t i = 0; i < media_stats_vec.size(); i++) {
124 if (media_stats_vec[i]->kind.ValueToString() == kind) {
125 return i;
126 }
127 }
128 return -1;
129}
130
deadbeef1dcb1642017-03-29 21:08:16 -0700131class SignalingMessageReceiver {
132 public:
133 virtual void ReceiveSdpMessage(const std::string& type,
134 const std::string& msg) = 0;
135 virtual void ReceiveIceMessage(const std::string& sdp_mid,
136 int sdp_mline_index,
137 const std::string& msg) = 0;
138
139 protected:
140 SignalingMessageReceiver() {}
141 virtual ~SignalingMessageReceiver() {}
142};
143
144class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
145 public:
146 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
147 : expected_media_type_(media_type) {}
148
149 void OnFirstPacketReceived(cricket::MediaType media_type) override {
150 ASSERT_EQ(expected_media_type_, media_type);
151 first_packet_received_ = true;
152 }
153
154 bool first_packet_received() const { return first_packet_received_; }
155
156 virtual ~MockRtpReceiverObserver() {}
157
158 private:
159 bool first_packet_received_ = false;
160 cricket::MediaType expected_media_type_;
161};
162
163// Helper class that wraps a peer connection, observes it, and can accept
164// signaling messages from another wrapper.
165//
166// Uses a fake network, fake A/V capture, and optionally fake
167// encoders/decoders, though they aren't used by default since they don't
168// advertise support of any codecs.
169class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
170 public SignalingMessageReceiver,
171 public ObserverInterface {
172 public:
173 // Different factory methods for convenience.
174 // TODO(deadbeef): Could use the pattern of:
175 //
176 // PeerConnectionWrapper =
177 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
178 //
179 // To reduce some code duplication.
180 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
181 const std::string& debug_name,
182 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
183 rtc::Thread* network_thread,
184 rtc::Thread* worker_thread) {
185 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
186 if (!client->Init(nullptr, nullptr, nullptr, std::move(cert_generator),
187 network_thread, worker_thread)) {
188 delete client;
189 return nullptr;
190 }
191 return client;
192 }
193
194 static PeerConnectionWrapper* CreateWithConfig(
195 const std::string& debug_name,
196 const PeerConnectionInterface::RTCConfiguration& config,
197 rtc::Thread* network_thread,
198 rtc::Thread* worker_thread) {
199 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
200 new FakeRTCCertificateGenerator());
201 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
202 if (!client->Init(nullptr, nullptr, &config, std::move(cert_generator),
203 network_thread, worker_thread)) {
204 delete client;
205 return nullptr;
206 }
207 return client;
208 }
209
210 static PeerConnectionWrapper* CreateWithOptions(
211 const std::string& debug_name,
212 const PeerConnectionFactory::Options& options,
213 rtc::Thread* network_thread,
214 rtc::Thread* worker_thread) {
215 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
216 new FakeRTCCertificateGenerator());
217 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
218 if (!client->Init(nullptr, &options, nullptr, std::move(cert_generator),
219 network_thread, worker_thread)) {
220 delete client;
221 return nullptr;
222 }
223 return client;
224 }
225
226 static PeerConnectionWrapper* CreateWithConstraints(
227 const std::string& debug_name,
228 const MediaConstraintsInterface* constraints,
229 rtc::Thread* network_thread,
230 rtc::Thread* worker_thread) {
231 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
232 new FakeRTCCertificateGenerator());
233 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
234 if (!client->Init(constraints, nullptr, nullptr, std::move(cert_generator),
235 network_thread, worker_thread)) {
236 delete client;
237 return nullptr;
238 }
239 return client;
240 }
241
deadbeef2f425aa2017-04-14 10:41:32 -0700242 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
243 return peer_connection_factory_.get();
244 }
245
deadbeef1dcb1642017-03-29 21:08:16 -0700246 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
247
248 // If a signaling message receiver is set (via ConnectFakeSignaling), this
249 // will set the whole offer/answer exchange in motion. Just need to wait for
250 // the signaling state to reach "stable".
251 void CreateAndSetAndSignalOffer() {
252 auto offer = CreateOffer();
253 ASSERT_NE(nullptr, offer);
254 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
255 }
256
257 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
258 // when a remote offer is received (via fake signaling) and an answer is
259 // generated. By default, uses default options.
260 void SetOfferAnswerOptions(
261 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
262 offer_answer_options_ = options;
263 }
264
265 // Set a callback to be invoked when SDP is received via the fake signaling
266 // channel, which provides an opportunity to munge (modify) the SDP. This is
267 // used to test SDP being applied that a PeerConnection would normally not
268 // generate, but a non-JSEP endpoint might.
269 void SetReceivedSdpMunger(
270 std::function<void(cricket::SessionDescription*)> munger) {
271 received_sdp_munger_ = munger;
272 }
273
deadbeefc964d0b2017-04-03 10:03:35 -0700274 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700275 // generated.
276 void SetGeneratedSdpMunger(
277 std::function<void(cricket::SessionDescription*)> munger) {
278 generated_sdp_munger_ = munger;
279 }
280
281 // Number of times the gathering state has transitioned to "gathering".
282 // Useful for telling if an ICE restart occurred as expected.
283 int transitions_to_gathering_state() const {
284 return transitions_to_gathering_state_;
285 }
286
287 // TODO(deadbeef): Switch the majority of these tests to use AddTrack instead
288 // of AddStream since AddStream is deprecated.
289 void AddAudioVideoMediaStream() {
290 AddMediaStreamFromTracks(CreateLocalAudioTrack(), CreateLocalVideoTrack());
291 }
292
293 void AddAudioOnlyMediaStream() {
294 AddMediaStreamFromTracks(CreateLocalAudioTrack(), nullptr);
295 }
296
297 void AddVideoOnlyMediaStream() {
298 AddMediaStreamFromTracks(nullptr, CreateLocalVideoTrack());
299 }
300
301 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
302 FakeConstraints constraints;
303 // Disable highpass filter so that we can get all the test audio frames.
304 constraints.AddMandatory(MediaConstraintsInterface::kHighpassFilter, false);
305 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
306 peer_connection_factory_->CreateAudioSource(&constraints);
307 // TODO(perkj): Test audio source when it is implemented. Currently audio
308 // always use the default input.
309 return peer_connection_factory_->CreateAudioTrack(kDefaultAudioTrackId,
310 source);
311 }
312
313 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
314 return CreateLocalVideoTrackInternal(
315 kDefaultVideoTrackId, FakeConstraints(), webrtc::kVideoRotation_0);
316 }
317
318 rtc::scoped_refptr<webrtc::VideoTrackInterface>
319 CreateLocalVideoTrackWithConstraints(const FakeConstraints& constraints) {
320 return CreateLocalVideoTrackInternal(kDefaultVideoTrackId, constraints,
321 webrtc::kVideoRotation_0);
322 }
323
324 rtc::scoped_refptr<webrtc::VideoTrackInterface>
325 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
326 return CreateLocalVideoTrackInternal(kDefaultVideoTrackId,
327 FakeConstraints(), rotation);
328 }
329
330 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackWithId(
331 const std::string& id) {
332 return CreateLocalVideoTrackInternal(id, FakeConstraints(),
333 webrtc::kVideoRotation_0);
334 }
335
336 void AddMediaStreamFromTracks(
337 rtc::scoped_refptr<webrtc::AudioTrackInterface> audio,
338 rtc::scoped_refptr<webrtc::VideoTrackInterface> video) {
339 AddMediaStreamFromTracksWithLabel(audio, video, kDefaultStreamLabel);
340 }
341
342 void AddMediaStreamFromTracksWithLabel(
343 rtc::scoped_refptr<webrtc::AudioTrackInterface> audio,
344 rtc::scoped_refptr<webrtc::VideoTrackInterface> video,
345 const std::string& stream_label) {
346 rtc::scoped_refptr<MediaStreamInterface> stream =
347 peer_connection_factory_->CreateLocalMediaStream(stream_label);
348 if (audio) {
349 stream->AddTrack(audio);
350 }
351 if (video) {
352 stream->AddTrack(video);
353 }
354 EXPECT_TRUE(pc()->AddStream(stream));
355 }
356
357 bool SignalingStateStable() {
358 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
359 }
360
361 void CreateDataChannel() { CreateDataChannel(nullptr); }
362
363 void CreateDataChannel(const webrtc::DataChannelInit* init) {
364 data_channel_ = pc()->CreateDataChannel(kDataChannelLabel, init);
365 ASSERT_TRUE(data_channel_.get() != nullptr);
366 data_observer_.reset(new MockDataChannelObserver(data_channel_));
367 }
368
369 DataChannelInterface* data_channel() { return data_channel_; }
370 const MockDataChannelObserver* data_observer() const {
371 return data_observer_.get();
372 }
373
374 int audio_frames_received() const {
375 return fake_audio_capture_module_->frames_received();
376 }
377
378 // Takes minimum of video frames received for each track.
379 //
380 // Can be used like:
381 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
382 //
383 // To ensure that all video tracks received at least a certain number of
384 // frames.
385 int min_video_frames_received_per_track() const {
386 int min_frames = INT_MAX;
387 if (video_decoder_factory_enabled_) {
388 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
389 fake_video_decoder_factory_->decoders();
390 if (decoders.empty()) {
391 return 0;
392 }
393 for (FakeWebRtcVideoDecoder* decoder : decoders) {
394 min_frames = std::min(min_frames, decoder->GetNumFramesReceived());
395 }
396 return min_frames;
397 } else {
398 if (fake_video_renderers_.empty()) {
399 return 0;
400 }
401
402 for (const auto& pair : fake_video_renderers_) {
403 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
404 }
405 return min_frames;
406 }
407 }
408
409 // In contrast to the above, sums the video frames received for all tracks.
410 // Can be used to verify that no video frames were received, or that the
411 // counts didn't increase.
412 int total_video_frames_received() const {
413 int total = 0;
414 if (video_decoder_factory_enabled_) {
415 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
416 fake_video_decoder_factory_->decoders();
417 for (const FakeWebRtcVideoDecoder* decoder : decoders) {
418 total += decoder->GetNumFramesReceived();
419 }
420 } else {
421 for (const auto& pair : fake_video_renderers_) {
422 total += pair.second->num_rendered_frames();
423 }
424 for (const auto& renderer : removed_fake_video_renderers_) {
425 total += renderer->num_rendered_frames();
426 }
427 }
428 return total;
429 }
430
431 // Returns a MockStatsObserver in a state after stats gathering finished,
432 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700433 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700434 webrtc::MediaStreamTrackInterface* track) {
435 rtc::scoped_refptr<MockStatsObserver> observer(
436 new rtc::RefCountedObject<MockStatsObserver>());
437 EXPECT_TRUE(peer_connection_->GetStats(
438 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
439 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
440 return observer;
441 }
442
443 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700444 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
445 return OldGetStatsForTrack(nullptr);
446 }
447
448 // Synchronously gets stats and returns them. If it times out, fails the test
449 // and returns null.
450 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
451 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
452 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
453 peer_connection_->GetStats(callback);
454 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
455 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700456 }
457
458 int rendered_width() {
459 EXPECT_FALSE(fake_video_renderers_.empty());
460 return fake_video_renderers_.empty()
461 ? 0
462 : fake_video_renderers_.begin()->second->width();
463 }
464
465 int rendered_height() {
466 EXPECT_FALSE(fake_video_renderers_.empty());
467 return fake_video_renderers_.empty()
468 ? 0
469 : fake_video_renderers_.begin()->second->height();
470 }
471
472 double rendered_aspect_ratio() {
473 if (rendered_height() == 0) {
474 return 0.0;
475 }
476 return static_cast<double>(rendered_width()) / rendered_height();
477 }
478
479 webrtc::VideoRotation rendered_rotation() {
480 EXPECT_FALSE(fake_video_renderers_.empty());
481 return fake_video_renderers_.empty()
482 ? webrtc::kVideoRotation_0
483 : fake_video_renderers_.begin()->second->rotation();
484 }
485
486 int local_rendered_width() {
487 return local_video_renderer_ ? local_video_renderer_->width() : 0;
488 }
489
490 int local_rendered_height() {
491 return local_video_renderer_ ? local_video_renderer_->height() : 0;
492 }
493
494 double local_rendered_aspect_ratio() {
495 if (local_rendered_height() == 0) {
496 return 0.0;
497 }
498 return static_cast<double>(local_rendered_width()) /
499 local_rendered_height();
500 }
501
502 size_t number_of_remote_streams() {
503 if (!pc()) {
504 return 0;
505 }
506 return pc()->remote_streams()->count();
507 }
508
509 StreamCollectionInterface* remote_streams() const {
510 if (!pc()) {
511 ADD_FAILURE();
512 return nullptr;
513 }
514 return pc()->remote_streams();
515 }
516
517 StreamCollectionInterface* local_streams() {
518 if (!pc()) {
519 ADD_FAILURE();
520 return nullptr;
521 }
522 return pc()->local_streams();
523 }
524
525 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
526 return pc()->signaling_state();
527 }
528
529 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
530 return pc()->ice_connection_state();
531 }
532
533 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
534 return pc()->ice_gathering_state();
535 }
536
537 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
538 // GetReceivers. They're updated automatically when a remote offer/answer
539 // from the fake signaling channel is applied, or when
540 // ResetRtpReceiverObservers below is called.
541 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
542 rtp_receiver_observers() {
543 return rtp_receiver_observers_;
544 }
545
546 void ResetRtpReceiverObservers() {
547 rtp_receiver_observers_.clear();
548 for (auto receiver : pc()->GetReceivers()) {
549 std::unique_ptr<MockRtpReceiverObserver> observer(
550 new MockRtpReceiverObserver(receiver->media_type()));
551 receiver->SetObserver(observer.get());
552 rtp_receiver_observers_.push_back(std::move(observer));
553 }
554 }
555
556 private:
557 explicit PeerConnectionWrapper(const std::string& debug_name)
558 : debug_name_(debug_name) {}
559
560 bool Init(
561 const MediaConstraintsInterface* constraints,
562 const PeerConnectionFactory::Options* options,
563 const PeerConnectionInterface::RTCConfiguration* config,
564 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
565 rtc::Thread* network_thread,
566 rtc::Thread* worker_thread) {
567 // There's an error in this test code if Init ends up being called twice.
568 RTC_DCHECK(!peer_connection_);
569 RTC_DCHECK(!peer_connection_factory_);
570
571 fake_network_manager_.reset(new rtc::FakeNetworkManager());
572 fake_network_manager_->AddInterface(rtc::SocketAddress("192.168.1.1", 0));
573
574 std::unique_ptr<cricket::PortAllocator> port_allocator(
575 new cricket::BasicPortAllocator(fake_network_manager_.get()));
576 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
577 if (!fake_audio_capture_module_) {
578 return false;
579 }
580 // Note that these factories don't end up getting used unless supported
581 // codecs are added to them.
582 fake_video_decoder_factory_ = new FakeWebRtcVideoDecoderFactory();
583 fake_video_encoder_factory_ = new FakeWebRtcVideoEncoderFactory();
584 rtc::Thread* const signaling_thread = rtc::Thread::Current();
585 peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(
586 network_thread, worker_thread, signaling_thread,
587 fake_audio_capture_module_, fake_video_encoder_factory_,
588 fake_video_decoder_factory_);
589 if (!peer_connection_factory_) {
590 return false;
591 }
592 if (options) {
593 peer_connection_factory_->SetOptions(*options);
594 }
595 peer_connection_ =
596 CreatePeerConnection(std::move(port_allocator), constraints, config,
597 std::move(cert_generator));
598 return peer_connection_.get() != nullptr;
599 }
600
601 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
602 std::unique_ptr<cricket::PortAllocator> port_allocator,
603 const MediaConstraintsInterface* constraints,
604 const PeerConnectionInterface::RTCConfiguration* config,
605 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator) {
606 PeerConnectionInterface::RTCConfiguration modified_config;
607 // If |config| is null, this will result in a default configuration being
608 // used.
609 if (config) {
610 modified_config = *config;
611 }
612 // Disable resolution adaptation; we don't want it interfering with the
613 // test results.
614 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
615 // ratios and not specific resolutions, is this even necessary?
616 modified_config.set_cpu_adaptation(false);
617
618 return peer_connection_factory_->CreatePeerConnection(
619 modified_config, constraints, std::move(port_allocator),
620 std::move(cert_generator), this);
621 }
622
623 void set_signaling_message_receiver(
624 SignalingMessageReceiver* signaling_message_receiver) {
625 signaling_message_receiver_ = signaling_message_receiver;
626 }
627
628 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
629
630 void EnableVideoDecoderFactory() {
631 video_decoder_factory_enabled_ = true;
632 fake_video_decoder_factory_->AddSupportedVideoCodecType(
633 webrtc::kVideoCodecVP8);
634 }
635
636 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
637 const std::string& track_id,
638 const FakeConstraints& constraints,
639 webrtc::VideoRotation rotation) {
640 // Set max frame rate to 10fps to reduce the risk of test flakiness.
641 // TODO(deadbeef): Do something more robust.
642 FakeConstraints source_constraints = constraints;
643 source_constraints.SetMandatoryMaxFrameRate(10);
644
645 cricket::FakeVideoCapturer* fake_capturer =
646 new webrtc::FakePeriodicVideoCapturer();
647 fake_capturer->SetRotation(rotation);
648 video_capturers_.push_back(fake_capturer);
649 rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source =
650 peer_connection_factory_->CreateVideoSource(fake_capturer,
651 &source_constraints);
652 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
653 peer_connection_factory_->CreateVideoTrack(track_id, source));
654 if (!local_video_renderer_) {
655 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
656 }
657 return track;
658 }
659
660 void HandleIncomingOffer(const std::string& msg) {
661 LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
662 std::unique_ptr<SessionDescriptionInterface> desc(
663 webrtc::CreateSessionDescription("offer", msg, nullptr));
664 if (received_sdp_munger_) {
665 received_sdp_munger_(desc->description());
666 }
667
668 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
669 // Setting a remote description may have changed the number of receivers,
670 // so reset the receiver observers.
671 ResetRtpReceiverObservers();
672 auto answer = CreateAnswer();
673 ASSERT_NE(nullptr, answer);
674 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
675 }
676
677 void HandleIncomingAnswer(const std::string& msg) {
678 LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
679 std::unique_ptr<SessionDescriptionInterface> desc(
680 webrtc::CreateSessionDescription("answer", msg, nullptr));
681 if (received_sdp_munger_) {
682 received_sdp_munger_(desc->description());
683 }
684
685 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
686 // Set the RtpReceiverObserver after receivers are created.
687 ResetRtpReceiverObservers();
688 }
689
690 // Returns null on failure.
691 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
692 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
693 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
694 pc()->CreateOffer(observer, offer_answer_options_);
695 return WaitForDescriptionFromObserver(observer);
696 }
697
698 // Returns null on failure.
699 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
700 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
701 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
702 pc()->CreateAnswer(observer, offer_answer_options_);
703 return WaitForDescriptionFromObserver(observer);
704 }
705
706 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
707 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer) {
708 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
709 if (!observer->result()) {
710 return nullptr;
711 }
712 auto description = observer->MoveDescription();
713 if (generated_sdp_munger_) {
714 generated_sdp_munger_(description->description());
715 }
716 return description;
717 }
718
719 // Setting the local description and sending the SDP message over the fake
720 // signaling channel are combined into the same method because the SDP
721 // message needs to be sent as soon as SetLocalDescription finishes, without
722 // waiting for the observer to be called. This ensures that ICE candidates
723 // don't outrace the description.
724 bool SetLocalDescriptionAndSendSdpMessage(
725 std::unique_ptr<SessionDescriptionInterface> desc) {
726 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
727 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
728 LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
729 std::string type = desc->type();
730 std::string sdp;
731 EXPECT_TRUE(desc->ToString(&sdp));
732 pc()->SetLocalDescription(observer, desc.release());
733 // As mentioned above, we need to send the message immediately after
734 // SetLocalDescription.
735 SendSdpMessage(type, sdp);
736 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
737 return true;
738 }
739
740 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
741 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
742 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
743 LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
744 pc()->SetRemoteDescription(observer, desc.release());
745 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
746 return observer->result();
747 }
748
749 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
750 // default).
751 void SendSdpMessage(const std::string& type, const std::string& msg) {
752 if (signaling_delay_ms_ == 0) {
753 RelaySdpMessageIfReceiverExists(type, msg);
754 } else {
755 invoker_.AsyncInvokeDelayed<void>(
756 RTC_FROM_HERE, rtc::Thread::Current(),
757 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
758 this, type, msg),
759 signaling_delay_ms_);
760 }
761 }
762
763 void RelaySdpMessageIfReceiverExists(const std::string& type,
764 const std::string& msg) {
765 if (signaling_message_receiver_) {
766 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
767 }
768 }
769
770 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
771 // default).
772 void SendIceMessage(const std::string& sdp_mid,
773 int sdp_mline_index,
774 const std::string& msg) {
775 if (signaling_delay_ms_ == 0) {
776 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
777 } else {
778 invoker_.AsyncInvokeDelayed<void>(
779 RTC_FROM_HERE, rtc::Thread::Current(),
780 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
781 this, sdp_mid, sdp_mline_index, msg),
782 signaling_delay_ms_);
783 }
784 }
785
786 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
787 int sdp_mline_index,
788 const std::string& msg) {
789 if (signaling_message_receiver_) {
790 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
791 msg);
792 }
793 }
794
795 // SignalingMessageReceiver callbacks.
796 void ReceiveSdpMessage(const std::string& type,
797 const std::string& msg) override {
798 if (type == webrtc::SessionDescriptionInterface::kOffer) {
799 HandleIncomingOffer(msg);
800 } else {
801 HandleIncomingAnswer(msg);
802 }
803 }
804
805 void ReceiveIceMessage(const std::string& sdp_mid,
806 int sdp_mline_index,
807 const std::string& msg) override {
808 LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
809 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
810 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
811 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
812 }
813
814 // PeerConnectionObserver callbacks.
815 void OnSignalingChange(
816 webrtc::PeerConnectionInterface::SignalingState new_state) override {
817 EXPECT_EQ(pc()->signaling_state(), new_state);
818 }
819 void OnAddStream(
820 rtc::scoped_refptr<MediaStreamInterface> media_stream) override {
821 media_stream->RegisterObserver(this);
822 for (size_t i = 0; i < media_stream->GetVideoTracks().size(); ++i) {
823 const std::string id = media_stream->GetVideoTracks()[i]->id();
824 ASSERT_TRUE(fake_video_renderers_.find(id) ==
825 fake_video_renderers_.end());
826 fake_video_renderers_[id].reset(new webrtc::FakeVideoTrackRenderer(
827 media_stream->GetVideoTracks()[i]));
828 }
829 }
830 void OnRemoveStream(
831 rtc::scoped_refptr<MediaStreamInterface> media_stream) override {}
832 void OnRenegotiationNeeded() override {}
833 void OnIceConnectionChange(
834 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
835 EXPECT_EQ(pc()->ice_connection_state(), new_state);
836 }
837 void OnIceGatheringChange(
838 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
839 if (new_state == PeerConnectionInterface::kIceGatheringGathering) {
840 ++transitions_to_gathering_state_;
841 }
842 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
843 }
844 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
845 LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
846
847 std::string ice_sdp;
848 EXPECT_TRUE(candidate->ToString(&ice_sdp));
849 if (signaling_message_receiver_ == nullptr) {
850 // Remote party may be deleted.
851 return;
852 }
853 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
854 }
855 void OnDataChannel(
856 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
857 LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
858 data_channel_ = data_channel;
859 data_observer_.reset(new MockDataChannelObserver(data_channel));
860 }
861
862 // MediaStreamInterface callback
863 void OnChanged() override {
864 // Track added or removed from MediaStream, so update our renderers.
865 rtc::scoped_refptr<StreamCollectionInterface> remote_streams =
866 pc()->remote_streams();
867 // Remove renderers for tracks that were removed.
868 for (auto it = fake_video_renderers_.begin();
869 it != fake_video_renderers_.end();) {
870 if (remote_streams->FindVideoTrack(it->first) == nullptr) {
871 auto to_remove = it++;
872 removed_fake_video_renderers_.push_back(std::move(to_remove->second));
873 fake_video_renderers_.erase(to_remove);
874 } else {
875 ++it;
876 }
877 }
878 // Create renderers for new video tracks.
879 for (size_t stream_index = 0; stream_index < remote_streams->count();
880 ++stream_index) {
881 MediaStreamInterface* remote_stream = remote_streams->at(stream_index);
882 for (size_t track_index = 0;
883 track_index < remote_stream->GetVideoTracks().size();
884 ++track_index) {
885 const std::string id =
886 remote_stream->GetVideoTracks()[track_index]->id();
887 if (fake_video_renderers_.find(id) != fake_video_renderers_.end()) {
888 continue;
889 }
890 fake_video_renderers_[id].reset(new webrtc::FakeVideoTrackRenderer(
891 remote_stream->GetVideoTracks()[track_index]));
892 }
893 }
894 }
895
896 std::string debug_name_;
897
898 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
899
900 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
901 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
902 peer_connection_factory_;
903
904 // Needed to keep track of number of frames sent.
905 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
906 // Needed to keep track of number of frames received.
907 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
908 fake_video_renderers_;
909 // Needed to ensure frames aren't received for removed tracks.
910 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
911 removed_fake_video_renderers_;
912 // Needed to keep track of number of frames received when external decoder
913 // used.
914 FakeWebRtcVideoDecoderFactory* fake_video_decoder_factory_ = nullptr;
915 FakeWebRtcVideoEncoderFactory* fake_video_encoder_factory_ = nullptr;
916 bool video_decoder_factory_enabled_ = false;
917
918 // For remote peer communication.
919 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
920 int signaling_delay_ms_ = 0;
921
922 // Store references to the video capturers we've created, so that we can stop
923 // them, if required.
924 std::vector<cricket::FakeVideoCapturer*> video_capturers_;
925 // |local_video_renderer_| attached to the first created local video track.
926 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
927
928 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
929 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
930 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
931
932 rtc::scoped_refptr<DataChannelInterface> data_channel_;
933 std::unique_ptr<MockDataChannelObserver> data_observer_;
934
935 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
936
937 int transitions_to_gathering_state_ = 0;
938
939 rtc::AsyncInvoker invoker_;
940
941 friend class PeerConnectionIntegrationTest;
942};
943
944// Tests two PeerConnections connecting to each other end-to-end, using a
945// virtual network, fake A/V capture and fake encoder/decoders. The
946// PeerConnections share the threads/socket servers, but use separate versions
947// of everything else (including "PeerConnectionFactory"s).
948class PeerConnectionIntegrationTest : public testing::Test {
949 public:
950 PeerConnectionIntegrationTest()
deadbeef98e186c2017-05-16 18:00:06 -0700951 : ss_(new rtc::VirtualSocketServer()),
deadbeef1dcb1642017-03-29 21:08:16 -0700952 network_thread_(new rtc::Thread(ss_.get())),
953 worker_thread_(rtc::Thread::Create()) {
954 RTC_CHECK(network_thread_->Start());
955 RTC_CHECK(worker_thread_->Start());
956 }
957
958 ~PeerConnectionIntegrationTest() {
959 if (caller_) {
960 caller_->set_signaling_message_receiver(nullptr);
961 }
962 if (callee_) {
963 callee_->set_signaling_message_receiver(nullptr);
964 }
965 }
966
967 bool SignalingStateStable() {
968 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
969 }
970
deadbeef71452802017-05-07 17:21:01 -0700971 bool DtlsConnected() {
972 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
973 // are connected. This is an important distinction. Once we have separate
974 // ICE and DTLS state, this check needs to use the DTLS state.
975 return (callee()->ice_connection_state() ==
976 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
977 callee()->ice_connection_state() ==
978 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
979 (caller()->ice_connection_state() ==
980 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
981 caller()->ice_connection_state() ==
982 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
983 }
984
deadbeef1dcb1642017-03-29 21:08:16 -0700985 bool CreatePeerConnectionWrappers() {
986 return CreatePeerConnectionWrappersWithConfig(
987 PeerConnectionInterface::RTCConfiguration(),
988 PeerConnectionInterface::RTCConfiguration());
989 }
990
991 bool CreatePeerConnectionWrappersWithConstraints(
992 MediaConstraintsInterface* caller_constraints,
993 MediaConstraintsInterface* callee_constraints) {
994 caller_.reset(PeerConnectionWrapper::CreateWithConstraints(
995 "Caller", caller_constraints, network_thread_.get(),
996 worker_thread_.get()));
997 callee_.reset(PeerConnectionWrapper::CreateWithConstraints(
998 "Callee", callee_constraints, network_thread_.get(),
999 worker_thread_.get()));
1000 return caller_ && callee_;
1001 }
1002
1003 bool CreatePeerConnectionWrappersWithConfig(
1004 const PeerConnectionInterface::RTCConfiguration& caller_config,
1005 const PeerConnectionInterface::RTCConfiguration& callee_config) {
1006 caller_.reset(PeerConnectionWrapper::CreateWithConfig(
1007 "Caller", caller_config, network_thread_.get(), worker_thread_.get()));
1008 callee_.reset(PeerConnectionWrapper::CreateWithConfig(
1009 "Callee", callee_config, network_thread_.get(), worker_thread_.get()));
1010 return caller_ && callee_;
1011 }
1012
1013 bool CreatePeerConnectionWrappersWithOptions(
1014 const PeerConnectionFactory::Options& caller_options,
1015 const PeerConnectionFactory::Options& callee_options) {
1016 caller_.reset(PeerConnectionWrapper::CreateWithOptions(
1017 "Caller", caller_options, network_thread_.get(), worker_thread_.get()));
1018 callee_.reset(PeerConnectionWrapper::CreateWithOptions(
1019 "Callee", callee_options, network_thread_.get(), worker_thread_.get()));
1020 return caller_ && callee_;
1021 }
1022
1023 PeerConnectionWrapper* CreatePeerConnectionWrapperWithAlternateKey() {
1024 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1025 new FakeRTCCertificateGenerator());
1026 cert_generator->use_alternate_key();
1027
1028 // Make sure the new client is using a different certificate.
1029 return PeerConnectionWrapper::CreateWithDtlsIdentityStore(
1030 "New Peer", std::move(cert_generator), network_thread_.get(),
1031 worker_thread_.get());
1032 }
1033
1034 // Once called, SDP blobs and ICE candidates will be automatically signaled
1035 // between PeerConnections.
1036 void ConnectFakeSignaling() {
1037 caller_->set_signaling_message_receiver(callee_.get());
1038 callee_->set_signaling_message_receiver(caller_.get());
1039 }
1040
1041 void SetSignalingDelayMs(int delay_ms) {
1042 caller_->set_signaling_delay_ms(delay_ms);
1043 callee_->set_signaling_delay_ms(delay_ms);
1044 }
1045
1046 void EnableVideoDecoderFactory() {
1047 caller_->EnableVideoDecoderFactory();
1048 callee_->EnableVideoDecoderFactory();
1049 }
1050
1051 // Messages may get lost on the unreliable DataChannel, so we send multiple
1052 // times to avoid test flakiness.
1053 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1054 const std::string& data,
1055 int retries) {
1056 for (int i = 0; i < retries; ++i) {
1057 dc->Send(DataBuffer(data));
1058 }
1059 }
1060
1061 rtc::Thread* network_thread() { return network_thread_.get(); }
1062
1063 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1064
1065 PeerConnectionWrapper* caller() { return caller_.get(); }
1066
1067 // Set the |caller_| to the |wrapper| passed in and return the
1068 // original |caller_|.
1069 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1070 PeerConnectionWrapper* wrapper) {
1071 PeerConnectionWrapper* old = caller_.release();
1072 caller_.reset(wrapper);
1073 return old;
1074 }
1075
1076 PeerConnectionWrapper* callee() { return callee_.get(); }
1077
1078 // Set the |callee_| to the |wrapper| passed in and return the
1079 // original |callee_|.
1080 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1081 PeerConnectionWrapper* wrapper) {
1082 PeerConnectionWrapper* old = callee_.release();
1083 callee_.reset(wrapper);
1084 return old;
1085 }
1086
1087 // Expects the provided number of new frames to be received within |wait_ms|.
1088 // "New frames" meaning that it waits for the current frame counts to
1089 // *increase* by the provided values. For video, uses
1090 // RecievedVideoFramesForEachTrack for the case of multiple video tracks
1091 // being received.
1092 void ExpectNewFramesReceivedWithWait(
1093 int expected_caller_received_audio_frames,
1094 int expected_caller_received_video_frames,
1095 int expected_callee_received_audio_frames,
1096 int expected_callee_received_video_frames,
1097 int wait_ms) {
1098 // Add current frame counts to the provided values, in order to wait for
1099 // the frame count to increase.
1100 expected_caller_received_audio_frames += caller()->audio_frames_received();
1101 expected_caller_received_video_frames +=
1102 caller()->min_video_frames_received_per_track();
1103 expected_callee_received_audio_frames += callee()->audio_frames_received();
1104 expected_callee_received_video_frames +=
1105 callee()->min_video_frames_received_per_track();
1106
1107 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
1108 expected_caller_received_audio_frames &&
1109 caller()->min_video_frames_received_per_track() >=
1110 expected_caller_received_video_frames &&
1111 callee()->audio_frames_received() >=
1112 expected_callee_received_audio_frames &&
1113 callee()->min_video_frames_received_per_track() >=
1114 expected_callee_received_video_frames,
1115 wait_ms);
1116
1117 // After the combined wait, do an "expect" for each individual count, to
1118 // print out a more detailed message upon failure.
1119 EXPECT_GE(caller()->audio_frames_received(),
1120 expected_caller_received_audio_frames);
1121 EXPECT_GE(caller()->min_video_frames_received_per_track(),
1122 expected_caller_received_video_frames);
1123 EXPECT_GE(callee()->audio_frames_received(),
1124 expected_callee_received_audio_frames);
1125 EXPECT_GE(callee()->min_video_frames_received_per_track(),
1126 expected_callee_received_video_frames);
1127 }
1128
1129 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1130 bool remote_gcm_enabled,
1131 int expected_cipher_suite) {
1132 PeerConnectionFactory::Options caller_options;
1133 caller_options.crypto_options.enable_gcm_crypto_suites = local_gcm_enabled;
1134 PeerConnectionFactory::Options callee_options;
1135 callee_options.crypto_options.enable_gcm_crypto_suites = remote_gcm_enabled;
1136 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1137 callee_options));
1138 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1139 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1140 caller()->pc()->RegisterUMAObserver(caller_observer);
1141 ConnectFakeSignaling();
1142 caller()->AddAudioVideoMediaStream();
1143 callee()->AddAudioVideoMediaStream();
1144 caller()->CreateAndSetAndSignalOffer();
1145 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1146 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001147 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001148 EXPECT_EQ(
1149 1, caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1150 expected_cipher_suite));
1151 caller()->pc()->RegisterUMAObserver(nullptr);
1152 }
1153
1154 private:
1155 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001156 std::unique_ptr<rtc::VirtualSocketServer> ss_;
1157 // |network_thread_| and |worker_thread_| are used by both
1158 // |caller_| and |callee_| so they must be destroyed
1159 // later.
1160 std::unique_ptr<rtc::Thread> network_thread_;
1161 std::unique_ptr<rtc::Thread> worker_thread_;
1162 std::unique_ptr<PeerConnectionWrapper> caller_;
1163 std::unique_ptr<PeerConnectionWrapper> callee_;
1164};
1165
1166// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1167// includes testing that the callback is invoked if an observer is connected
1168// after the first packet has already been received.
1169TEST_F(PeerConnectionIntegrationTest,
1170 RtpReceiverObserverOnFirstPacketReceived) {
1171 ASSERT_TRUE(CreatePeerConnectionWrappers());
1172 ConnectFakeSignaling();
1173 caller()->AddAudioVideoMediaStream();
1174 callee()->AddAudioVideoMediaStream();
1175 // Start offer/answer exchange and wait for it to complete.
1176 caller()->CreateAndSetAndSignalOffer();
1177 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1178 // Should be one receiver each for audio/video.
1179 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1180 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1181 // Wait for all "first packet received" callbacks to be fired.
1182 EXPECT_TRUE_WAIT(
1183 std::all_of(caller()->rtp_receiver_observers().begin(),
1184 caller()->rtp_receiver_observers().end(),
1185 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1186 return o->first_packet_received();
1187 }),
1188 kMaxWaitForFramesMs);
1189 EXPECT_TRUE_WAIT(
1190 std::all_of(callee()->rtp_receiver_observers().begin(),
1191 callee()->rtp_receiver_observers().end(),
1192 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1193 return o->first_packet_received();
1194 }),
1195 kMaxWaitForFramesMs);
1196 // If new observers are set after the first packet was already received, the
1197 // callback should still be invoked.
1198 caller()->ResetRtpReceiverObservers();
1199 callee()->ResetRtpReceiverObservers();
1200 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1201 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1202 EXPECT_TRUE(
1203 std::all_of(caller()->rtp_receiver_observers().begin(),
1204 caller()->rtp_receiver_observers().end(),
1205 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1206 return o->first_packet_received();
1207 }));
1208 EXPECT_TRUE(
1209 std::all_of(callee()->rtp_receiver_observers().begin(),
1210 callee()->rtp_receiver_observers().end(),
1211 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1212 return o->first_packet_received();
1213 }));
1214}
1215
1216class DummyDtmfObserver : public DtmfSenderObserverInterface {
1217 public:
1218 DummyDtmfObserver() : completed_(false) {}
1219
1220 // Implements DtmfSenderObserverInterface.
1221 void OnToneChange(const std::string& tone) override {
1222 tones_.push_back(tone);
1223 if (tone.empty()) {
1224 completed_ = true;
1225 }
1226 }
1227
1228 const std::vector<std::string>& tones() const { return tones_; }
1229 bool completed() const { return completed_; }
1230
1231 private:
1232 bool completed_;
1233 std::vector<std::string> tones_;
1234};
1235
1236// Assumes |sender| already has an audio track added and the offer/answer
1237// exchange is done.
1238void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1239 PeerConnectionWrapper* receiver) {
1240 DummyDtmfObserver observer;
1241 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender;
1242
1243 // We should be able to create a DTMF sender from a local track.
1244 webrtc::AudioTrackInterface* localtrack =
1245 sender->local_streams()->at(0)->GetAudioTracks()[0];
1246 dtmf_sender = sender->pc()->CreateDtmfSender(localtrack);
1247 ASSERT_NE(nullptr, dtmf_sender.get());
1248 dtmf_sender->RegisterObserver(&observer);
1249
1250 // Test the DtmfSender object just created.
1251 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1252 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1253
1254 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1255 std::vector<std::string> tones = {"1", "a", ""};
1256 EXPECT_EQ(tones, observer.tones());
1257 dtmf_sender->UnregisterObserver();
1258 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1259}
1260
1261// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1262// direction).
1263TEST_F(PeerConnectionIntegrationTest, DtmfSenderObserver) {
1264 ASSERT_TRUE(CreatePeerConnectionWrappers());
1265 ConnectFakeSignaling();
1266 // Only need audio for DTMF.
1267 caller()->AddAudioOnlyMediaStream();
1268 callee()->AddAudioOnlyMediaStream();
1269 caller()->CreateAndSetAndSignalOffer();
1270 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001271 // DTLS must finish before the DTMF sender can be used reliably.
1272 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001273 TestDtmfFromSenderToReceiver(caller(), callee());
1274 TestDtmfFromSenderToReceiver(callee(), caller());
1275}
1276
1277// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1278// between two connections, using DTLS-SRTP.
1279TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
1280 ASSERT_TRUE(CreatePeerConnectionWrappers());
1281 ConnectFakeSignaling();
1282 // Do normal offer/answer and wait for some frames to be received in each
1283 // direction.
1284 caller()->AddAudioVideoMediaStream();
1285 callee()->AddAudioVideoMediaStream();
1286 caller()->CreateAndSetAndSignalOffer();
1287 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1288 ExpectNewFramesReceivedWithWait(
1289 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1290 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1291 kMaxWaitForFramesMs);
1292}
1293
1294// Uses SDES instead of DTLS for key agreement.
1295TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
1296 PeerConnectionInterface::RTCConfiguration sdes_config;
1297 sdes_config.enable_dtls_srtp.emplace(false);
1298 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1299 ConnectFakeSignaling();
1300
1301 // Do normal offer/answer and wait for some frames to be received in each
1302 // direction.
1303 caller()->AddAudioVideoMediaStream();
1304 callee()->AddAudioVideoMediaStream();
1305 caller()->CreateAndSetAndSignalOffer();
1306 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1307 ExpectNewFramesReceivedWithWait(
1308 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1309 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1310 kMaxWaitForFramesMs);
1311}
1312
1313// This test sets up a call between two parties (using DTLS) and tests that we
1314// can get a video aspect ratio of 16:9.
1315TEST_F(PeerConnectionIntegrationTest, SendAndReceive16To9AspectRatio) {
1316 ASSERT_TRUE(CreatePeerConnectionWrappers());
1317 ConnectFakeSignaling();
1318
1319 // Add video tracks with 16:9 constraint.
1320 FakeConstraints constraints;
1321 double requested_ratio = 16.0 / 9;
1322 constraints.SetMandatoryMinAspectRatio(requested_ratio);
1323 caller()->AddMediaStreamFromTracks(
1324 nullptr, caller()->CreateLocalVideoTrackWithConstraints(constraints));
1325 callee()->AddMediaStreamFromTracks(
1326 nullptr, callee()->CreateLocalVideoTrackWithConstraints(constraints));
1327
1328 // Do normal offer/answer and wait for at least one frame to be received in
1329 // each direction.
1330 caller()->CreateAndSetAndSignalOffer();
1331 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1332 callee()->min_video_frames_received_per_track() > 0,
1333 kMaxWaitForFramesMs);
1334
1335 // Check rendered aspect ratio.
1336 EXPECT_EQ(requested_ratio, caller()->local_rendered_aspect_ratio());
1337 EXPECT_EQ(requested_ratio, caller()->rendered_aspect_ratio());
1338 EXPECT_EQ(requested_ratio, callee()->local_rendered_aspect_ratio());
1339 EXPECT_EQ(requested_ratio, callee()->rendered_aspect_ratio());
1340}
1341
1342// This test sets up a call between two parties with a source resolution of
1343// 1280x720 and verifies that a 16:9 aspect ratio is received.
1344TEST_F(PeerConnectionIntegrationTest,
1345 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1346 ASSERT_TRUE(CreatePeerConnectionWrappers());
1347 ConnectFakeSignaling();
1348
1349 // Similar to above test, but uses MandatoryMin[Width/Height] constraint
1350 // instead of aspect ratio constraint.
1351 FakeConstraints constraints;
1352 constraints.SetMandatoryMinWidth(1280);
1353 constraints.SetMandatoryMinHeight(720);
1354 caller()->AddMediaStreamFromTracks(
1355 nullptr, caller()->CreateLocalVideoTrackWithConstraints(constraints));
1356 callee()->AddMediaStreamFromTracks(
1357 nullptr, callee()->CreateLocalVideoTrackWithConstraints(constraints));
1358
1359 // Do normal offer/answer and wait for at least one frame to be received in
1360 // each direction.
1361 caller()->CreateAndSetAndSignalOffer();
1362 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1363 callee()->min_video_frames_received_per_track() > 0,
1364 kMaxWaitForFramesMs);
1365
1366 // Check rendered aspect ratio.
1367 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1368 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1369 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1370 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1371}
1372
1373// This test sets up an one-way call, with media only from caller to
1374// callee.
1375TEST_F(PeerConnectionIntegrationTest, OneWayMediaCall) {
1376 ASSERT_TRUE(CreatePeerConnectionWrappers());
1377 ConnectFakeSignaling();
1378 caller()->AddAudioVideoMediaStream();
1379 caller()->CreateAndSetAndSignalOffer();
1380 int caller_received_frames = 0;
1381 ExpectNewFramesReceivedWithWait(
1382 caller_received_frames, caller_received_frames,
1383 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1384 kMaxWaitForFramesMs);
1385}
1386
1387// This test sets up a audio call initially, with the callee rejecting video
1388// initially. Then later the callee decides to upgrade to audio/video, and
1389// initiates a new offer/answer exchange.
1390TEST_F(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
1391 ASSERT_TRUE(CreatePeerConnectionWrappers());
1392 ConnectFakeSignaling();
1393 // Initially, offer an audio/video stream from the caller, but refuse to
1394 // send/receive video on the callee side.
1395 caller()->AddAudioVideoMediaStream();
1396 callee()->AddMediaStreamFromTracks(callee()->CreateLocalAudioTrack(),
1397 nullptr);
1398 PeerConnectionInterface::RTCOfferAnswerOptions options;
1399 options.offer_to_receive_video = 0;
1400 callee()->SetOfferAnswerOptions(options);
1401 // Do offer/answer and make sure audio is still received end-to-end.
1402 caller()->CreateAndSetAndSignalOffer();
1403 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1404 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1405 kDefaultExpectedAudioFrameCount, 0,
1406 kMaxWaitForFramesMs);
1407 // Sanity check that the callee's description has a rejected video section.
1408 ASSERT_NE(nullptr, callee()->pc()->local_description());
1409 const ContentInfo* callee_video_content =
1410 GetFirstVideoContent(callee()->pc()->local_description()->description());
1411 ASSERT_NE(nullptr, callee_video_content);
1412 EXPECT_TRUE(callee_video_content->rejected);
1413 // Now negotiate with video and ensure negotiation succeeds, with video
1414 // frames and additional audio frames being received.
1415 callee()->AddMediaStreamFromTracksWithLabel(
1416 nullptr, callee()->CreateLocalVideoTrack(), "video_only_stream");
1417 options.offer_to_receive_video = 1;
1418 callee()->SetOfferAnswerOptions(options);
1419 callee()->CreateAndSetAndSignalOffer();
1420 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1421 // Expect additional audio frames to be received after the upgrade.
1422 ExpectNewFramesReceivedWithWait(
1423 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1424 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1425 kMaxWaitForFramesMs);
1426}
1427
1428// This test sets up a call that's transferred to a new caller with a different
1429// DTLS fingerprint.
1430TEST_F(PeerConnectionIntegrationTest, CallTransferredForCallee) {
1431 ASSERT_TRUE(CreatePeerConnectionWrappers());
1432 ConnectFakeSignaling();
1433 caller()->AddAudioVideoMediaStream();
1434 callee()->AddAudioVideoMediaStream();
1435 caller()->CreateAndSetAndSignalOffer();
1436 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1437
1438 // Keep the original peer around which will still send packets to the
1439 // receiving client. These SRTP packets will be dropped.
1440 std::unique_ptr<PeerConnectionWrapper> original_peer(
1441 SetCallerPcWrapperAndReturnCurrent(
1442 CreatePeerConnectionWrapperWithAlternateKey()));
1443 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1444 // directly above.
1445 original_peer->pc()->Close();
1446
1447 ConnectFakeSignaling();
1448 caller()->AddAudioVideoMediaStream();
1449 caller()->CreateAndSetAndSignalOffer();
1450 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1451 // Wait for some additional frames to be transmitted end-to-end.
1452 ExpectNewFramesReceivedWithWait(
1453 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1454 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1455 kMaxWaitForFramesMs);
1456}
1457
1458// This test sets up a call that's transferred to a new callee with a different
1459// DTLS fingerprint.
1460TEST_F(PeerConnectionIntegrationTest, CallTransferredForCaller) {
1461 ASSERT_TRUE(CreatePeerConnectionWrappers());
1462 ConnectFakeSignaling();
1463 caller()->AddAudioVideoMediaStream();
1464 callee()->AddAudioVideoMediaStream();
1465 caller()->CreateAndSetAndSignalOffer();
1466 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1467
1468 // Keep the original peer around which will still send packets to the
1469 // receiving client. These SRTP packets will be dropped.
1470 std::unique_ptr<PeerConnectionWrapper> original_peer(
1471 SetCalleePcWrapperAndReturnCurrent(
1472 CreatePeerConnectionWrapperWithAlternateKey()));
1473 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1474 // directly above.
1475 original_peer->pc()->Close();
1476
1477 ConnectFakeSignaling();
1478 callee()->AddAudioVideoMediaStream();
1479 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1480 caller()->CreateAndSetAndSignalOffer();
1481 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1482 // Wait for some additional frames to be transmitted end-to-end.
1483 ExpectNewFramesReceivedWithWait(
1484 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1485 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1486 kMaxWaitForFramesMs);
1487}
1488
1489// This test sets up a non-bundled call and negotiates bundling at the same
1490// time as starting an ICE restart. When bundling is in effect in the restart,
1491// the DTLS-SRTP context should be successfully reset.
1492TEST_F(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
1493 ASSERT_TRUE(CreatePeerConnectionWrappers());
1494 ConnectFakeSignaling();
1495
1496 caller()->AddAudioVideoMediaStream();
1497 callee()->AddAudioVideoMediaStream();
1498 // Remove the bundle group from the SDP received by the callee.
1499 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1500 desc->RemoveGroupByName("BUNDLE");
1501 });
1502 caller()->CreateAndSetAndSignalOffer();
1503 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1504 ExpectNewFramesReceivedWithWait(
1505 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1506 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1507 kMaxWaitForFramesMs);
1508
1509 // Now stop removing the BUNDLE group, and trigger an ICE restart.
1510 callee()->SetReceivedSdpMunger(nullptr);
1511 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1512 caller()->CreateAndSetAndSignalOffer();
1513 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1514
1515 // Expect additional frames to be received after the ICE restart.
1516 ExpectNewFramesReceivedWithWait(
1517 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1518 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1519 kMaxWaitForFramesMs);
1520}
1521
1522// Test CVO (Coordination of Video Orientation). If a video source is rotated
1523// and both peers support the CVO RTP header extension, the actual video frames
1524// don't need to be encoded in different resolutions, since the rotation is
1525// communicated through the RTP header extension.
1526TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
1527 ASSERT_TRUE(CreatePeerConnectionWrappers());
1528 ConnectFakeSignaling();
1529 // Add rotated video tracks.
1530 caller()->AddMediaStreamFromTracks(
1531 nullptr,
1532 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
1533 callee()->AddMediaStreamFromTracks(
1534 nullptr,
1535 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1536
1537 // Wait for video frames to be received by both sides.
1538 caller()->CreateAndSetAndSignalOffer();
1539 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1540 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1541 callee()->min_video_frames_received_per_track() > 0,
1542 kMaxWaitForFramesMs);
1543
1544 // Ensure that the aspect ratio is unmodified.
1545 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1546 // not just assumed.
1547 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
1548 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
1549 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
1550 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
1551 // Ensure that the CVO bits were surfaced to the renderer.
1552 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
1553 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
1554}
1555
1556// Test that when the CVO extension isn't supported, video is rotated the
1557// old-fashioned way, by encoding rotated frames.
1558TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
1559 ASSERT_TRUE(CreatePeerConnectionWrappers());
1560 ConnectFakeSignaling();
1561 // Add rotated video tracks.
1562 caller()->AddMediaStreamFromTracks(
1563 nullptr,
1564 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
1565 callee()->AddMediaStreamFromTracks(
1566 nullptr,
1567 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1568
1569 // Remove the CVO extension from the offered SDP.
1570 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1571 cricket::VideoContentDescription* video =
1572 GetFirstVideoContentDescription(desc);
1573 video->ClearRtpHeaderExtensions();
1574 });
1575 // Wait for video frames to be received by both sides.
1576 caller()->CreateAndSetAndSignalOffer();
1577 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1578 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1579 callee()->min_video_frames_received_per_track() > 0,
1580 kMaxWaitForFramesMs);
1581
1582 // Expect that the aspect ratio is inversed to account for the 90/270 degree
1583 // rotation.
1584 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1585 // not just assumed.
1586 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
1587 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
1588 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
1589 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
1590 // Expect that each endpoint is unaware of the rotation of the other endpoint.
1591 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
1592 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
1593}
1594
1595// TODO(deadbeef): The tests below rely on RTCOfferAnswerOptions to reject an
1596// m= section. When we implement Unified Plan SDP, the right way to do this
1597// would be by stopping an RtpTransceiver.
1598
1599// Test that if the answerer rejects the audio m= section, no audio is sent or
1600// received, but video still can be.
1601TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
1602 ASSERT_TRUE(CreatePeerConnectionWrappers());
1603 ConnectFakeSignaling();
1604 caller()->AddAudioVideoMediaStream();
1605 // Only add video track for callee, and set offer_to_receive_audio to 0, so
1606 // it will reject the audio m= section completely.
1607 PeerConnectionInterface::RTCOfferAnswerOptions options;
1608 options.offer_to_receive_audio = 0;
1609 callee()->SetOfferAnswerOptions(options);
1610 callee()->AddMediaStreamFromTracks(nullptr,
1611 callee()->CreateLocalVideoTrack());
1612 // Do offer/answer and wait for successful end-to-end video frames.
1613 caller()->CreateAndSetAndSignalOffer();
1614 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1615 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount, 0,
1616 kDefaultExpectedVideoFrameCount,
1617 kMaxWaitForFramesMs);
1618 // Shouldn't have received audio frames at any point.
1619 EXPECT_EQ(0, caller()->audio_frames_received());
1620 EXPECT_EQ(0, callee()->audio_frames_received());
1621 // Sanity check that the callee's description has a rejected audio section.
1622 ASSERT_NE(nullptr, callee()->pc()->local_description());
1623 const ContentInfo* callee_audio_content =
1624 GetFirstAudioContent(callee()->pc()->local_description()->description());
1625 ASSERT_NE(nullptr, callee_audio_content);
1626 EXPECT_TRUE(callee_audio_content->rejected);
1627}
1628
1629// Test that if the answerer rejects the video m= section, no video is sent or
1630// received, but audio still can be.
1631TEST_F(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
1632 ASSERT_TRUE(CreatePeerConnectionWrappers());
1633 ConnectFakeSignaling();
1634 caller()->AddAudioVideoMediaStream();
1635 // Only add audio track for callee, and set offer_to_receive_video to 0, so
1636 // it will reject the video m= section completely.
1637 PeerConnectionInterface::RTCOfferAnswerOptions options;
1638 options.offer_to_receive_video = 0;
1639 callee()->SetOfferAnswerOptions(options);
1640 callee()->AddMediaStreamFromTracks(callee()->CreateLocalAudioTrack(),
1641 nullptr);
1642 // Do offer/answer and wait for successful end-to-end audio frames.
1643 caller()->CreateAndSetAndSignalOffer();
1644 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1645 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1646 kDefaultExpectedAudioFrameCount, 0,
1647 kMaxWaitForFramesMs);
1648 // Shouldn't have received video frames at any point.
1649 EXPECT_EQ(0, caller()->total_video_frames_received());
1650 EXPECT_EQ(0, callee()->total_video_frames_received());
1651 // Sanity check that the callee's description has a rejected video section.
1652 ASSERT_NE(nullptr, callee()->pc()->local_description());
1653 const ContentInfo* callee_video_content =
1654 GetFirstVideoContent(callee()->pc()->local_description()->description());
1655 ASSERT_NE(nullptr, callee_video_content);
1656 EXPECT_TRUE(callee_video_content->rejected);
1657}
1658
1659// Test that if the answerer rejects both audio and video m= sections, nothing
1660// bad happens.
1661// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
1662// test anything but the fact that negotiation succeeds, which doesn't mean
1663// much.
1664TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
1665 ASSERT_TRUE(CreatePeerConnectionWrappers());
1666 ConnectFakeSignaling();
1667 caller()->AddAudioVideoMediaStream();
1668 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
1669 // will reject both audio and video m= sections.
1670 PeerConnectionInterface::RTCOfferAnswerOptions options;
1671 options.offer_to_receive_audio = 0;
1672 options.offer_to_receive_video = 0;
1673 callee()->SetOfferAnswerOptions(options);
1674 // Do offer/answer and wait for stable signaling state.
1675 caller()->CreateAndSetAndSignalOffer();
1676 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1677 // Sanity check that the callee's description has rejected m= sections.
1678 ASSERT_NE(nullptr, callee()->pc()->local_description());
1679 const ContentInfo* callee_audio_content =
1680 GetFirstAudioContent(callee()->pc()->local_description()->description());
1681 ASSERT_NE(nullptr, callee_audio_content);
1682 EXPECT_TRUE(callee_audio_content->rejected);
1683 const ContentInfo* callee_video_content =
1684 GetFirstVideoContent(callee()->pc()->local_description()->description());
1685 ASSERT_NE(nullptr, callee_video_content);
1686 EXPECT_TRUE(callee_video_content->rejected);
1687}
1688
1689// This test sets up an audio and video call between two parties. After the
1690// call runs for a while, the caller sends an updated offer with video being
1691// rejected. Once the re-negotiation is done, the video flow should stop and
1692// the audio flow should continue.
1693TEST_F(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
1694 ASSERT_TRUE(CreatePeerConnectionWrappers());
1695 ConnectFakeSignaling();
1696 caller()->AddAudioVideoMediaStream();
1697 callee()->AddAudioVideoMediaStream();
1698 caller()->CreateAndSetAndSignalOffer();
1699 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1700 ExpectNewFramesReceivedWithWait(
1701 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1702 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1703 kMaxWaitForFramesMs);
1704
1705 // Renegotiate, rejecting the video m= section.
1706 // TODO(deadbeef): When an RtpTransceiver API is available, use that to
1707 // reject the video m= section.
1708 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
1709 for (cricket::ContentInfo& content : description->contents()) {
1710 if (cricket::IsVideoContent(&content)) {
1711 content.rejected = true;
1712 }
1713 }
1714 });
1715 caller()->CreateAndSetAndSignalOffer();
1716 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
1717
1718 // Sanity check that the caller's description has a rejected video section.
1719 ASSERT_NE(nullptr, caller()->pc()->local_description());
1720 const ContentInfo* caller_video_content =
1721 GetFirstVideoContent(caller()->pc()->local_description()->description());
1722 ASSERT_NE(nullptr, caller_video_content);
1723 EXPECT_TRUE(caller_video_content->rejected);
1724
1725 int caller_video_received = caller()->total_video_frames_received();
1726 int callee_video_received = callee()->total_video_frames_received();
1727
1728 // Wait for some additional audio frames to be received.
1729 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1730 kDefaultExpectedAudioFrameCount, 0,
1731 kMaxWaitForFramesMs);
1732
1733 // During this time, we shouldn't have received any additional video frames
1734 // for the rejected video tracks.
1735 EXPECT_EQ(caller_video_received, caller()->total_video_frames_received());
1736 EXPECT_EQ(callee_video_received, callee()->total_video_frames_received());
1737}
1738
1739// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
1740// is needed to support legacy endpoints.
1741// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
1742// add a test for an end-to-end test without MID signaling either (basically,
1743// the minimum acceptable SDP).
1744TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
1745 ASSERT_TRUE(CreatePeerConnectionWrappers());
1746 ConnectFakeSignaling();
1747 // Add audio and video, testing that packets can be demuxed on payload type.
1748 caller()->AddAudioVideoMediaStream();
1749 callee()->AddAudioVideoMediaStream();
deadbeefd8ad7882017-04-18 16:01:17 -07001750 // Remove SSRCs and MSIDs from the received offer SDP.
1751 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07001752 caller()->CreateAndSetAndSignalOffer();
1753 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1754 ExpectNewFramesReceivedWithWait(
1755 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1756 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1757 kMaxWaitForFramesMs);
1758}
1759
1760// Test that if two video tracks are sent (from caller to callee, in this test),
1761// they're transmitted correctly end-to-end.
1762TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
1763 ASSERT_TRUE(CreatePeerConnectionWrappers());
1764 ConnectFakeSignaling();
1765 // Add one audio/video stream, and one video-only stream.
1766 caller()->AddAudioVideoMediaStream();
1767 caller()->AddMediaStreamFromTracksWithLabel(
1768 nullptr, caller()->CreateLocalVideoTrackWithId("extra_track"),
1769 "extra_stream");
1770 caller()->CreateAndSetAndSignalOffer();
1771 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1772 ASSERT_EQ(2u, callee()->number_of_remote_streams());
1773 int expected_callee_received_frames = kDefaultExpectedVideoFrameCount;
1774 ExpectNewFramesReceivedWithWait(0, 0, 0, expected_callee_received_frames,
1775 kMaxWaitForFramesMs);
1776}
1777
1778static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
1779 bool first = true;
1780 for (cricket::ContentInfo& content : desc->contents()) {
1781 if (first) {
1782 first = false;
1783 continue;
1784 }
1785 content.bundle_only = true;
1786 }
1787 first = true;
1788 for (cricket::TransportInfo& transport : desc->transport_infos()) {
1789 if (first) {
1790 first = false;
1791 continue;
1792 }
1793 transport.description.ice_ufrag.clear();
1794 transport.description.ice_pwd.clear();
1795 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
1796 transport.description.identity_fingerprint.reset(nullptr);
1797 }
1798}
1799
1800// Test that if applying a true "max bundle" offer, which uses ports of 0,
1801// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
1802// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
1803// successfully and media flows.
1804// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
1805// TODO(deadbeef): Won't need this test once we start generating actual
1806// standards-compliant SDP.
1807TEST_F(PeerConnectionIntegrationTest,
1808 EndToEndCallWithSpecCompliantMaxBundleOffer) {
1809 ASSERT_TRUE(CreatePeerConnectionWrappers());
1810 ConnectFakeSignaling();
1811 caller()->AddAudioVideoMediaStream();
1812 callee()->AddAudioVideoMediaStream();
1813 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
1814 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
1815 // but the first m= section.
1816 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
1817 caller()->CreateAndSetAndSignalOffer();
1818 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1819 ExpectNewFramesReceivedWithWait(
1820 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1821 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1822 kMaxWaitForFramesMs);
1823}
1824
1825// Test that we can receive the audio output level from a remote audio track.
1826// TODO(deadbeef): Use a fake audio source and verify that the output level is
1827// exactly what the source on the other side was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001828TEST_F(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001829 ASSERT_TRUE(CreatePeerConnectionWrappers());
1830 ConnectFakeSignaling();
1831 // Just add an audio track.
1832 caller()->AddMediaStreamFromTracks(caller()->CreateLocalAudioTrack(),
1833 nullptr);
1834 caller()->CreateAndSetAndSignalOffer();
1835 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1836
1837 // Get the audio output level stats. Note that the level is not available
1838 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07001839 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001840 kMaxWaitForFramesMs);
1841}
1842
1843// Test that an audio input level is reported.
1844// TODO(deadbeef): Use a fake audio source and verify that the input level is
1845// exactly what the source was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001846TEST_F(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001847 ASSERT_TRUE(CreatePeerConnectionWrappers());
1848 ConnectFakeSignaling();
1849 // Just add an audio track.
1850 caller()->AddMediaStreamFromTracks(caller()->CreateLocalAudioTrack(),
1851 nullptr);
1852 caller()->CreateAndSetAndSignalOffer();
1853 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1854
1855 // Get the audio input level stats. The level should be available very
1856 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07001857 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001858 kMaxWaitForStatsMs);
1859}
1860
1861// Test that we can get incoming byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001862TEST_F(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001863 ASSERT_TRUE(CreatePeerConnectionWrappers());
1864 ConnectFakeSignaling();
1865 caller()->AddAudioVideoMediaStream();
1866 // Do offer/answer, wait for the callee to receive some frames.
1867 caller()->CreateAndSetAndSignalOffer();
1868 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1869 int expected_caller_received_frames = 0;
1870 ExpectNewFramesReceivedWithWait(
1871 expected_caller_received_frames, expected_caller_received_frames,
1872 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1873 kMaxWaitForFramesMs);
1874
1875 // Get a handle to the remote tracks created, so they can be used as GetStats
1876 // filters.
1877 StreamCollectionInterface* remote_streams = callee()->remote_streams();
1878 ASSERT_EQ(1u, remote_streams->count());
1879 ASSERT_EQ(1u, remote_streams->at(0)->GetAudioTracks().size());
1880 ASSERT_EQ(1u, remote_streams->at(0)->GetVideoTracks().size());
1881 MediaStreamTrackInterface* remote_audio_track =
1882 remote_streams->at(0)->GetAudioTracks()[0];
1883 MediaStreamTrackInterface* remote_video_track =
1884 remote_streams->at(0)->GetVideoTracks()[0];
1885
1886 // We received frames, so we definitely should have nonzero "received bytes"
1887 // stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07001888 EXPECT_GT(callee()->OldGetStatsForTrack(remote_audio_track)->BytesReceived(),
1889 0);
1890 EXPECT_GT(callee()->OldGetStatsForTrack(remote_video_track)->BytesReceived(),
1891 0);
deadbeef1dcb1642017-03-29 21:08:16 -07001892}
1893
1894// Test that we can get outgoing byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001895TEST_F(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001896 ASSERT_TRUE(CreatePeerConnectionWrappers());
1897 ConnectFakeSignaling();
1898 auto audio_track = caller()->CreateLocalAudioTrack();
1899 auto video_track = caller()->CreateLocalVideoTrack();
1900 caller()->AddMediaStreamFromTracks(audio_track, video_track);
1901 // Do offer/answer, wait for the callee to receive some frames.
1902 caller()->CreateAndSetAndSignalOffer();
1903 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1904 int expected_caller_received_frames = 0;
1905 ExpectNewFramesReceivedWithWait(
1906 expected_caller_received_frames, expected_caller_received_frames,
1907 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1908 kMaxWaitForFramesMs);
1909
1910 // The callee received frames, so we definitely should have nonzero "sent
1911 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07001912 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
1913 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
1914}
1915
1916// Test that we can get stats (using the new stats implemnetation) for
1917// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
1918// SDP.
1919TEST_F(PeerConnectionIntegrationTest,
1920 GetStatsForUnsignaledStreamWithNewStatsApi) {
1921 ASSERT_TRUE(CreatePeerConnectionWrappers());
1922 ConnectFakeSignaling();
1923 caller()->AddAudioOnlyMediaStream();
1924 // Remove SSRCs and MSIDs from the received offer SDP.
1925 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
1926 caller()->CreateAndSetAndSignalOffer();
1927 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1928 // Wait for one audio frame to be received by the callee.
1929 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
1930
1931 // We received a frame, so we should have nonzero "bytes received" stats for
1932 // the unsignaled stream, if stats are working for it.
1933 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
1934 callee()->NewGetStats();
1935 ASSERT_NE(nullptr, report);
1936 auto inbound_stream_stats =
1937 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
1938 ASSERT_EQ(1U, inbound_stream_stats.size());
1939 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
1940 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07001941 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
1942}
1943
1944// Test that we can successfully get the media related stats (audio level
1945// etc.) for the unsignaled stream.
1946TEST_F(PeerConnectionIntegrationTest,
1947 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
1948 ASSERT_TRUE(CreatePeerConnectionWrappers());
1949 ConnectFakeSignaling();
1950 caller()->AddAudioVideoMediaStream();
1951 // Remove SSRCs and MSIDs from the received offer SDP.
1952 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
1953 caller()->CreateAndSetAndSignalOffer();
1954 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1955 // Wait for one audio frame to be received by the callee.
1956 ExpectNewFramesReceivedWithWait(0, 0, 1, 1, kMaxWaitForFramesMs);
1957
1958 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
1959 callee()->NewGetStats();
1960 ASSERT_NE(nullptr, report);
1961
1962 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
1963 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
1964 ASSERT_GE(audio_index, 0);
1965 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07001966}
1967
1968// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
1969TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
1970 PeerConnectionFactory::Options dtls_10_options;
1971 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
1972 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
1973 dtls_10_options));
1974 ConnectFakeSignaling();
1975 // Do normal offer/answer and wait for some frames to be received in each
1976 // direction.
1977 caller()->AddAudioVideoMediaStream();
1978 callee()->AddAudioVideoMediaStream();
1979 caller()->CreateAndSetAndSignalOffer();
1980 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1981 ExpectNewFramesReceivedWithWait(
1982 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1983 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1984 kMaxWaitForFramesMs);
1985}
1986
1987// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
1988TEST_F(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
1989 PeerConnectionFactory::Options dtls_10_options;
1990 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
1991 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
1992 dtls_10_options));
1993 ConnectFakeSignaling();
1994 // Register UMA observer before signaling begins.
1995 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1996 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1997 caller()->pc()->RegisterUMAObserver(caller_observer);
1998 caller()->AddAudioVideoMediaStream();
1999 callee()->AddAudioVideoMediaStream();
2000 caller()->CreateAndSetAndSignalOffer();
2001 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2002 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002003 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002004 kDefaultTimeout);
2005 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002006 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002007 EXPECT_EQ(1,
2008 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2009 kDefaultSrtpCryptoSuite));
2010}
2011
2012// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
2013TEST_F(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
2014 PeerConnectionFactory::Options dtls_12_options;
2015 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2016 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2017 dtls_12_options));
2018 ConnectFakeSignaling();
2019 // Register UMA observer before signaling begins.
2020 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
2021 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2022 caller()->pc()->RegisterUMAObserver(caller_observer);
2023 caller()->AddAudioVideoMediaStream();
2024 callee()->AddAudioVideoMediaStream();
2025 caller()->CreateAndSetAndSignalOffer();
2026 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2027 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002028 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002029 kDefaultTimeout);
2030 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002031 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002032 EXPECT_EQ(1,
2033 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2034 kDefaultSrtpCryptoSuite));
2035}
2036
2037// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2038// callee only supports 1.0.
2039TEST_F(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
2040 PeerConnectionFactory::Options caller_options;
2041 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2042 PeerConnectionFactory::Options callee_options;
2043 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2044 ASSERT_TRUE(
2045 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2046 ConnectFakeSignaling();
2047 // Do normal offer/answer and wait for some frames to be received in each
2048 // direction.
2049 caller()->AddAudioVideoMediaStream();
2050 callee()->AddAudioVideoMediaStream();
2051 caller()->CreateAndSetAndSignalOffer();
2052 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2053 ExpectNewFramesReceivedWithWait(
2054 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2055 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2056 kMaxWaitForFramesMs);
2057}
2058
2059// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2060// callee supports 1.2.
2061TEST_F(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
2062 PeerConnectionFactory::Options caller_options;
2063 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2064 PeerConnectionFactory::Options callee_options;
2065 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2066 ASSERT_TRUE(
2067 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2068 ConnectFakeSignaling();
2069 // Do normal offer/answer and wait for some frames to be received in each
2070 // direction.
2071 caller()->AddAudioVideoMediaStream();
2072 callee()->AddAudioVideoMediaStream();
2073 caller()->CreateAndSetAndSignalOffer();
2074 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2075 ExpectNewFramesReceivedWithWait(
2076 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2077 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2078 kMaxWaitForFramesMs);
2079}
2080
2081// Test that a non-GCM cipher is used if both sides only support non-GCM.
2082TEST_F(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
2083 bool local_gcm_enabled = false;
2084 bool remote_gcm_enabled = false;
2085 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2086 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2087 expected_cipher_suite);
2088}
2089
2090// Test that a GCM cipher is used if both ends support it.
2091TEST_F(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
2092 bool local_gcm_enabled = true;
2093 bool remote_gcm_enabled = true;
2094 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2095 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2096 expected_cipher_suite);
2097}
2098
2099// Test that GCM isn't used if only the offerer supports it.
2100TEST_F(PeerConnectionIntegrationTest,
2101 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2102 bool local_gcm_enabled = true;
2103 bool remote_gcm_enabled = false;
2104 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2105 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2106 expected_cipher_suite);
2107}
2108
2109// Test that GCM isn't used if only the answerer supports it.
2110TEST_F(PeerConnectionIntegrationTest,
2111 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2112 bool local_gcm_enabled = false;
2113 bool remote_gcm_enabled = true;
2114 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2115 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2116 expected_cipher_suite);
2117}
2118
deadbeef7914b8c2017-04-21 03:23:33 -07002119// Verify that media can be transmitted end-to-end when GCM crypto suites are
2120// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
2121// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
2122// works with it.
2123TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
2124 PeerConnectionFactory::Options gcm_options;
2125 gcm_options.crypto_options.enable_gcm_crypto_suites = true;
2126 ASSERT_TRUE(
2127 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
2128 ConnectFakeSignaling();
2129 // Do normal offer/answer and wait for some frames to be received in each
2130 // direction.
2131 caller()->AddAudioVideoMediaStream();
2132 callee()->AddAudioVideoMediaStream();
2133 caller()->CreateAndSetAndSignalOffer();
2134 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2135 ExpectNewFramesReceivedWithWait(
2136 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2137 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2138 kMaxWaitForFramesMs);
2139}
2140
deadbeef1dcb1642017-03-29 21:08:16 -07002141// This test sets up a call between two parties with audio, video and an RTP
2142// data channel.
2143TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
2144 FakeConstraints setup_constraints;
2145 setup_constraints.SetAllowRtpDataChannels();
2146 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2147 &setup_constraints));
2148 ConnectFakeSignaling();
2149 // Expect that data channel created on caller side will show up for callee as
2150 // well.
2151 caller()->CreateDataChannel();
2152 caller()->AddAudioVideoMediaStream();
2153 callee()->AddAudioVideoMediaStream();
2154 caller()->CreateAndSetAndSignalOffer();
2155 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2156 // Ensure the existence of the RTP data channel didn't impede audio/video.
2157 ExpectNewFramesReceivedWithWait(
2158 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2159 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2160 kMaxWaitForFramesMs);
2161 ASSERT_NE(nullptr, caller()->data_channel());
2162 ASSERT_NE(nullptr, callee()->data_channel());
2163 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2164 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2165
2166 // Ensure data can be sent in both directions.
2167 std::string data = "hello world";
2168 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2169 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2170 kDefaultTimeout);
2171 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2172 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2173 kDefaultTimeout);
2174}
2175
2176// Ensure that an RTP data channel is signaled as closed for the caller when
2177// the callee rejects it in a subsequent offer.
2178TEST_F(PeerConnectionIntegrationTest,
2179 RtpDataChannelSignaledClosedInCalleeOffer) {
2180 // Same procedure as above test.
2181 FakeConstraints setup_constraints;
2182 setup_constraints.SetAllowRtpDataChannels();
2183 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2184 &setup_constraints));
2185 ConnectFakeSignaling();
2186 caller()->CreateDataChannel();
2187 caller()->AddAudioVideoMediaStream();
2188 callee()->AddAudioVideoMediaStream();
2189 caller()->CreateAndSetAndSignalOffer();
2190 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2191 ASSERT_NE(nullptr, caller()->data_channel());
2192 ASSERT_NE(nullptr, callee()->data_channel());
2193 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2194 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2195
2196 // Close the data channel on the callee, and do an updated offer/answer.
2197 callee()->data_channel()->Close();
2198 callee()->CreateAndSetAndSignalOffer();
2199 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2200 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2201 EXPECT_FALSE(callee()->data_observer()->IsOpen());
2202}
2203
2204// Tests that data is buffered in an RTP data channel until an observer is
2205// registered for it.
2206//
2207// NOTE: RTP data channels can receive data before the underlying
2208// transport has detected that a channel is writable and thus data can be
2209// received before the data channel state changes to open. That is hard to test
2210// but the same buffering is expected to be used in that case.
2211TEST_F(PeerConnectionIntegrationTest,
2212 DataBufferedUntilRtpDataChannelObserverRegistered) {
2213 // Use fake clock and simulated network delay so that we predictably can wait
2214 // until an SCTP message has been delivered without "sleep()"ing.
2215 rtc::ScopedFakeClock fake_clock;
2216 // Some things use a time of "0" as a special value, so we need to start out
2217 // the fake clock at a nonzero time.
2218 // TODO(deadbeef): Fix this.
2219 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2220 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
2221 virtual_socket_server()->UpdateDelayDistribution();
2222
2223 FakeConstraints constraints;
2224 constraints.SetAllowRtpDataChannels();
2225 ASSERT_TRUE(
2226 CreatePeerConnectionWrappersWithConstraints(&constraints, &constraints));
2227 ConnectFakeSignaling();
2228 caller()->CreateDataChannel();
2229 caller()->CreateAndSetAndSignalOffer();
2230 ASSERT_TRUE(caller()->data_channel() != nullptr);
2231 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
2232 kDefaultTimeout, fake_clock);
2233 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
2234 kDefaultTimeout, fake_clock);
2235 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
2236 callee()->data_channel()->state(), kDefaultTimeout,
2237 fake_clock);
2238
2239 // Unregister the observer which is normally automatically registered.
2240 callee()->data_channel()->UnregisterObserver();
2241 // Send data and advance fake clock until it should have been received.
2242 std::string data = "hello world";
2243 caller()->data_channel()->Send(DataBuffer(data));
2244 SIMULATED_WAIT(false, 50, fake_clock);
2245
2246 // Attach data channel and expect data to be received immediately. Note that
2247 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
2248 // further, but data can be received even if the callback is asynchronous.
2249 MockDataChannelObserver new_observer(callee()->data_channel());
2250 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
2251 fake_clock);
2252}
2253
2254// This test sets up a call between two parties with audio, video and but only
2255// the caller client supports RTP data channels.
2256TEST_F(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
2257 FakeConstraints setup_constraints_1;
2258 setup_constraints_1.SetAllowRtpDataChannels();
2259 // Must disable DTLS to make negotiation succeed.
2260 setup_constraints_1.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2261 false);
2262 FakeConstraints setup_constraints_2;
2263 setup_constraints_2.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2264 false);
2265 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(
2266 &setup_constraints_1, &setup_constraints_2));
2267 ConnectFakeSignaling();
2268 caller()->CreateDataChannel();
2269 caller()->AddAudioVideoMediaStream();
2270 callee()->AddAudioVideoMediaStream();
2271 caller()->CreateAndSetAndSignalOffer();
2272 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2273 // The caller should still have a data channel, but it should be closed, and
2274 // one should ever have been created for the callee.
2275 EXPECT_TRUE(caller()->data_channel() != nullptr);
2276 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2277 EXPECT_EQ(nullptr, callee()->data_channel());
2278}
2279
2280// This test sets up a call between two parties with audio, and video. When
2281// audio and video is setup and flowing, an RTP data channel is negotiated.
2282TEST_F(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
2283 FakeConstraints setup_constraints;
2284 setup_constraints.SetAllowRtpDataChannels();
2285 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2286 &setup_constraints));
2287 ConnectFakeSignaling();
2288 // Do initial offer/answer with audio/video.
2289 caller()->AddAudioVideoMediaStream();
2290 callee()->AddAudioVideoMediaStream();
2291 caller()->CreateAndSetAndSignalOffer();
2292 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2293 // Create data channel and do new offer and answer.
2294 caller()->CreateDataChannel();
2295 caller()->CreateAndSetAndSignalOffer();
2296 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2297 ASSERT_NE(nullptr, caller()->data_channel());
2298 ASSERT_NE(nullptr, callee()->data_channel());
2299 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2300 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2301 // Ensure data can be sent in both directions.
2302 std::string data = "hello world";
2303 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2304 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2305 kDefaultTimeout);
2306 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2307 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2308 kDefaultTimeout);
2309}
2310
2311#ifdef HAVE_SCTP
2312
2313// This test sets up a call between two parties with audio, video and an SCTP
2314// data channel.
2315TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
2316 ASSERT_TRUE(CreatePeerConnectionWrappers());
2317 ConnectFakeSignaling();
2318 // Expect that data channel created on caller side will show up for callee as
2319 // well.
2320 caller()->CreateDataChannel();
2321 caller()->AddAudioVideoMediaStream();
2322 callee()->AddAudioVideoMediaStream();
2323 caller()->CreateAndSetAndSignalOffer();
2324 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2325 // Ensure the existence of the SCTP data channel didn't impede audio/video.
2326 ExpectNewFramesReceivedWithWait(
2327 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2328 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2329 kMaxWaitForFramesMs);
2330 // Caller data channel should already exist (it created one). Callee data
2331 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2332 ASSERT_NE(nullptr, caller()->data_channel());
2333 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2334 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2335 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2336
2337 // Ensure data can be sent in both directions.
2338 std::string data = "hello world";
2339 caller()->data_channel()->Send(DataBuffer(data));
2340 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2341 kDefaultTimeout);
2342 callee()->data_channel()->Send(DataBuffer(data));
2343 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2344 kDefaultTimeout);
2345}
2346
2347// Ensure that when the callee closes an SCTP data channel, the closing
2348// procedure results in the data channel being closed for the caller as well.
2349TEST_F(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
2350 // Same procedure as above test.
2351 ASSERT_TRUE(CreatePeerConnectionWrappers());
2352 ConnectFakeSignaling();
2353 caller()->CreateDataChannel();
2354 caller()->AddAudioVideoMediaStream();
2355 callee()->AddAudioVideoMediaStream();
2356 caller()->CreateAndSetAndSignalOffer();
2357 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2358 ASSERT_NE(nullptr, caller()->data_channel());
2359 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2360 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2361 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2362
2363 // Close the data channel on the callee side, and wait for it to reach the
2364 // "closed" state on both sides.
2365 callee()->data_channel()->Close();
2366 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
2367 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
2368}
2369
2370// Test usrsctp's ability to process unordered data stream, where data actually
2371// arrives out of order using simulated delays. Previously there have been some
2372// bugs in this area.
2373TEST_F(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
2374 // Introduce random network delays.
2375 // Otherwise it's not a true "unordered" test.
2376 virtual_socket_server()->set_delay_mean(20);
2377 virtual_socket_server()->set_delay_stddev(5);
2378 virtual_socket_server()->UpdateDelayDistribution();
2379 // Normal procedure, but with unordered data channel config.
2380 ASSERT_TRUE(CreatePeerConnectionWrappers());
2381 ConnectFakeSignaling();
2382 webrtc::DataChannelInit init;
2383 init.ordered = false;
2384 caller()->CreateDataChannel(&init);
2385 caller()->CreateAndSetAndSignalOffer();
2386 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2387 ASSERT_NE(nullptr, caller()->data_channel());
2388 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2389 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2390 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2391
2392 static constexpr int kNumMessages = 100;
2393 // Deliberately chosen to be larger than the MTU so messages get fragmented.
2394 static constexpr size_t kMaxMessageSize = 4096;
2395 // Create and send random messages.
2396 std::vector<std::string> sent_messages;
2397 for (int i = 0; i < kNumMessages; ++i) {
2398 size_t length =
2399 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
2400 std::string message;
2401 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
2402 caller()->data_channel()->Send(DataBuffer(message));
2403 callee()->data_channel()->Send(DataBuffer(message));
2404 sent_messages.push_back(message);
2405 }
2406
2407 // Wait for all messages to be received.
2408 EXPECT_EQ_WAIT(kNumMessages,
2409 caller()->data_observer()->received_message_count(),
2410 kDefaultTimeout);
2411 EXPECT_EQ_WAIT(kNumMessages,
2412 callee()->data_observer()->received_message_count(),
2413 kDefaultTimeout);
2414
2415 // Sort and compare to make sure none of the messages were corrupted.
2416 std::vector<std::string> caller_received_messages =
2417 caller()->data_observer()->messages();
2418 std::vector<std::string> callee_received_messages =
2419 callee()->data_observer()->messages();
2420 std::sort(sent_messages.begin(), sent_messages.end());
2421 std::sort(caller_received_messages.begin(), caller_received_messages.end());
2422 std::sort(callee_received_messages.begin(), callee_received_messages.end());
2423 EXPECT_EQ(sent_messages, caller_received_messages);
2424 EXPECT_EQ(sent_messages, callee_received_messages);
2425}
2426
2427// This test sets up a call between two parties with audio, and video. When
2428// audio and video are setup and flowing, an SCTP data channel is negotiated.
2429TEST_F(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
2430 ASSERT_TRUE(CreatePeerConnectionWrappers());
2431 ConnectFakeSignaling();
2432 // Do initial offer/answer with audio/video.
2433 caller()->AddAudioVideoMediaStream();
2434 callee()->AddAudioVideoMediaStream();
2435 caller()->CreateAndSetAndSignalOffer();
2436 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2437 // Create data channel and do new offer and answer.
2438 caller()->CreateDataChannel();
2439 caller()->CreateAndSetAndSignalOffer();
2440 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2441 // Caller data channel should already exist (it created one). Callee data
2442 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2443 ASSERT_NE(nullptr, caller()->data_channel());
2444 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2445 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2446 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2447 // Ensure data can be sent in both directions.
2448 std::string data = "hello world";
2449 caller()->data_channel()->Send(DataBuffer(data));
2450 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2451 kDefaultTimeout);
2452 callee()->data_channel()->Send(DataBuffer(data));
2453 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2454 kDefaultTimeout);
2455}
2456
deadbeef7914b8c2017-04-21 03:23:33 -07002457// Set up a connection initially just using SCTP data channels, later upgrading
2458// to audio/video, ensuring frames are received end-to-end. Effectively the
2459// inverse of the test above.
2460// This was broken in M57; see https://crbug.com/711243
2461TEST_F(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
2462 ASSERT_TRUE(CreatePeerConnectionWrappers());
2463 ConnectFakeSignaling();
2464 // Do initial offer/answer with just data channel.
2465 caller()->CreateDataChannel();
2466 caller()->CreateAndSetAndSignalOffer();
2467 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2468 // Wait until data can be sent over the data channel.
2469 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2470 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2471 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2472
2473 // Do subsequent offer/answer with two-way audio and video. Audio and video
2474 // should end up bundled on the DTLS/ICE transport already used for data.
2475 caller()->AddAudioVideoMediaStream();
2476 callee()->AddAudioVideoMediaStream();
2477 caller()->CreateAndSetAndSignalOffer();
2478 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2479 ExpectNewFramesReceivedWithWait(
2480 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2481 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2482 kMaxWaitForFramesMs);
2483}
2484
deadbeef8b7e9ad2017-05-25 09:38:55 -07002485static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
2486 const ContentInfo* dc_offer = GetFirstDataContent(desc);
2487 ASSERT_NE(nullptr, dc_offer);
2488 cricket::DataContentDescription* dcd_offer =
2489 static_cast<cricket::DataContentDescription*>(dc_offer->description);
2490 dcd_offer->set_use_sctpmap(false);
2491 dcd_offer->set_protocol("UDP/DTLS/SCTP");
2492}
2493
2494// Test that the data channel works when a spec-compliant SCTP m= section is
2495// offered (using "a=sctp-port" instead of "a=sctpmap", and using
2496// "UDP/DTLS/SCTP" as the protocol).
2497TEST_F(PeerConnectionIntegrationTest,
2498 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
2499 ASSERT_TRUE(CreatePeerConnectionWrappers());
2500 ConnectFakeSignaling();
2501 caller()->CreateDataChannel();
2502 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
2503 caller()->CreateAndSetAndSignalOffer();
2504 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2505 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2506 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2507 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2508
2509 // Ensure data can be sent in both directions.
2510 std::string data = "hello world";
2511 caller()->data_channel()->Send(DataBuffer(data));
2512 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2513 kDefaultTimeout);
2514 callee()->data_channel()->Send(DataBuffer(data));
2515 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2516 kDefaultTimeout);
2517}
2518
deadbeef1dcb1642017-03-29 21:08:16 -07002519#endif // HAVE_SCTP
2520
2521// Test that the ICE connection and gathering states eventually reach
2522// "complete".
2523TEST_F(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
2524 ASSERT_TRUE(CreatePeerConnectionWrappers());
2525 ConnectFakeSignaling();
2526 // Do normal offer/answer.
2527 caller()->AddAudioVideoMediaStream();
2528 callee()->AddAudioVideoMediaStream();
2529 caller()->CreateAndSetAndSignalOffer();
2530 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2531 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2532 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
2533 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2534 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
2535 // After the best candidate pair is selected and all candidates are signaled,
2536 // the ICE connection state should reach "complete".
2537 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
2538 // answerer/"callee" by default) only reaches "connected". When this is
2539 // fixed, this test should be updated.
2540 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2541 caller()->ice_connection_state(), kDefaultTimeout);
2542 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2543 callee()->ice_connection_state(), kDefaultTimeout);
2544}
2545
2546// This test sets up a call between two parties with audio and video.
2547// During the call, the caller restarts ICE and the test verifies that
2548// new ICE candidates are generated and audio and video still can flow, and the
2549// ICE state reaches completed again.
2550TEST_F(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
2551 ASSERT_TRUE(CreatePeerConnectionWrappers());
2552 ConnectFakeSignaling();
2553 // Do normal offer/answer and wait for ICE to complete.
2554 caller()->AddAudioVideoMediaStream();
2555 callee()->AddAudioVideoMediaStream();
2556 caller()->CreateAndSetAndSignalOffer();
2557 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2558 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2559 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2560 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2561 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2562
2563 // To verify that the ICE restart actually occurs, get
2564 // ufrag/password/candidates before and after restart.
2565 // Create an SDP string of the first audio candidate for both clients.
2566 const webrtc::IceCandidateCollection* audio_candidates_caller =
2567 caller()->pc()->local_description()->candidates(0);
2568 const webrtc::IceCandidateCollection* audio_candidates_callee =
2569 callee()->pc()->local_description()->candidates(0);
2570 ASSERT_GT(audio_candidates_caller->count(), 0u);
2571 ASSERT_GT(audio_candidates_callee->count(), 0u);
2572 std::string caller_candidate_pre_restart;
2573 ASSERT_TRUE(
2574 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
2575 std::string callee_candidate_pre_restart;
2576 ASSERT_TRUE(
2577 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
2578 const cricket::SessionDescription* desc =
2579 caller()->pc()->local_description()->description();
2580 std::string caller_ufrag_pre_restart =
2581 desc->transport_infos()[0].description.ice_ufrag;
2582 desc = callee()->pc()->local_description()->description();
2583 std::string callee_ufrag_pre_restart =
2584 desc->transport_infos()[0].description.ice_ufrag;
2585
2586 // Have the caller initiate an ICE restart.
2587 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2588 caller()->CreateAndSetAndSignalOffer();
2589 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2590 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2591 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2592 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2593 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2594
2595 // Grab the ufrags/candidates again.
2596 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
2597 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
2598 ASSERT_GT(audio_candidates_caller->count(), 0u);
2599 ASSERT_GT(audio_candidates_callee->count(), 0u);
2600 std::string caller_candidate_post_restart;
2601 ASSERT_TRUE(
2602 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
2603 std::string callee_candidate_post_restart;
2604 ASSERT_TRUE(
2605 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
2606 desc = caller()->pc()->local_description()->description();
2607 std::string caller_ufrag_post_restart =
2608 desc->transport_infos()[0].description.ice_ufrag;
2609 desc = callee()->pc()->local_description()->description();
2610 std::string callee_ufrag_post_restart =
2611 desc->transport_infos()[0].description.ice_ufrag;
2612 // Sanity check that an ICE restart was actually negotiated in SDP.
2613 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
2614 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
2615 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
2616 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
2617
2618 // Ensure that additional frames are received after the ICE restart.
2619 ExpectNewFramesReceivedWithWait(
2620 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2621 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2622 kMaxWaitForFramesMs);
2623}
2624
2625// Verify that audio/video can be received end-to-end when ICE renomination is
2626// enabled.
2627TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
2628 PeerConnectionInterface::RTCConfiguration config;
2629 config.enable_ice_renomination = true;
2630 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
2631 ConnectFakeSignaling();
2632 // Do normal offer/answer and wait for some frames to be received in each
2633 // direction.
2634 caller()->AddAudioVideoMediaStream();
2635 callee()->AddAudioVideoMediaStream();
2636 caller()->CreateAndSetAndSignalOffer();
2637 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2638 // Sanity check that ICE renomination was actually negotiated.
2639 const cricket::SessionDescription* desc =
2640 caller()->pc()->local_description()->description();
2641 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07002642 ASSERT_NE(
2643 info.description.transport_options.end(),
2644 std::find(info.description.transport_options.begin(),
2645 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07002646 }
2647 desc = callee()->pc()->local_description()->description();
2648 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07002649 ASSERT_NE(
2650 info.description.transport_options.end(),
2651 std::find(info.description.transport_options.begin(),
2652 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07002653 }
2654 ExpectNewFramesReceivedWithWait(
2655 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2656 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2657 kMaxWaitForFramesMs);
2658}
2659
2660// This test sets up a call between two parties with audio and video. It then
2661// renegotiates setting the video m-line to "port 0", then later renegotiates
2662// again, enabling video.
2663TEST_F(PeerConnectionIntegrationTest,
2664 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
2665 ASSERT_TRUE(CreatePeerConnectionWrappers());
2666 ConnectFakeSignaling();
2667
2668 // Do initial negotiation, only sending media from the caller. Will result in
2669 // video and audio recvonly "m=" sections.
2670 caller()->AddAudioVideoMediaStream();
2671 caller()->CreateAndSetAndSignalOffer();
2672 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2673
2674 // Negotiate again, disabling the video "m=" section (the callee will set the
2675 // port to 0 due to offer_to_receive_video = 0).
2676 PeerConnectionInterface::RTCOfferAnswerOptions options;
2677 options.offer_to_receive_video = 0;
2678 callee()->SetOfferAnswerOptions(options);
2679 caller()->CreateAndSetAndSignalOffer();
2680 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2681 // Sanity check that video "m=" section was actually rejected.
2682 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
2683 callee()->pc()->local_description()->description());
2684 ASSERT_NE(nullptr, answer_video_content);
2685 ASSERT_TRUE(answer_video_content->rejected);
2686
2687 // Enable video and do negotiation again, making sure video is received
2688 // end-to-end, also adding media stream to callee.
2689 options.offer_to_receive_video = 1;
2690 callee()->SetOfferAnswerOptions(options);
2691 callee()->AddAudioVideoMediaStream();
2692 caller()->CreateAndSetAndSignalOffer();
2693 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2694 // Verify the caller receives frames from the newly added stream, and the
2695 // callee receives additional frames from the re-enabled video m= section.
2696 ExpectNewFramesReceivedWithWait(
2697 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2698 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2699 kMaxWaitForFramesMs);
2700}
2701
2702// This test sets up a Jsep call between two parties with external
2703// VideoDecoderFactory.
2704// TODO(holmer): Disabled due to sometimes crashing on buildbots.
2705// See issue webrtc/2378.
2706TEST_F(PeerConnectionIntegrationTest,
2707 DISABLED_EndToEndCallWithVideoDecoderFactory) {
2708 ASSERT_TRUE(CreatePeerConnectionWrappers());
2709 EnableVideoDecoderFactory();
2710 ConnectFakeSignaling();
2711 caller()->AddAudioVideoMediaStream();
2712 callee()->AddAudioVideoMediaStream();
2713 caller()->CreateAndSetAndSignalOffer();
2714 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2715 ExpectNewFramesReceivedWithWait(
2716 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2717 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2718 kMaxWaitForFramesMs);
2719}
2720
2721// This tests that if we negotiate after calling CreateSender but before we
2722// have a track, then set a track later, frames from the newly-set track are
2723// received end-to-end.
2724// TODO(deadbeef): Change this test to use AddTransceiver, once that's
2725// implemented.
2726TEST_F(PeerConnectionIntegrationTest,
2727 MediaFlowsAfterEarlyWarmupWithCreateSender) {
2728 ASSERT_TRUE(CreatePeerConnectionWrappers());
2729 ConnectFakeSignaling();
2730 auto caller_audio_sender =
2731 caller()->pc()->CreateSender("audio", "caller_stream");
2732 auto caller_video_sender =
2733 caller()->pc()->CreateSender("video", "caller_stream");
2734 auto callee_audio_sender =
2735 callee()->pc()->CreateSender("audio", "callee_stream");
2736 auto callee_video_sender =
2737 callee()->pc()->CreateSender("video", "callee_stream");
2738 caller()->CreateAndSetAndSignalOffer();
2739 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2740 // Wait for ICE to complete, without any tracks being set.
2741 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2742 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2743 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2744 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2745 // Now set the tracks, and expect frames to immediately start flowing.
2746 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
2747 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
2748 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
2749 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
2750 ExpectNewFramesReceivedWithWait(
2751 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2752 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2753 kMaxWaitForFramesMs);
2754}
2755
2756// This test verifies that a remote video track can be added via AddStream,
2757// and sent end-to-end. For this particular test, it's simply echoed back
2758// from the caller to the callee, rather than being forwarded to a third
2759// PeerConnection.
2760TEST_F(PeerConnectionIntegrationTest, CanSendRemoteVideoTrack) {
2761 ASSERT_TRUE(CreatePeerConnectionWrappers());
2762 ConnectFakeSignaling();
2763 // Just send a video track from the caller.
2764 caller()->AddMediaStreamFromTracks(nullptr,
2765 caller()->CreateLocalVideoTrack());
2766 caller()->CreateAndSetAndSignalOffer();
2767 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2768 ASSERT_EQ(1, callee()->remote_streams()->count());
2769
2770 // Echo the stream back, and do a new offer/anwer (initiated by callee this
2771 // time).
2772 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
2773 callee()->CreateAndSetAndSignalOffer();
2774 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2775
2776 int expected_caller_received_video_frames = kDefaultExpectedVideoFrameCount;
2777 ExpectNewFramesReceivedWithWait(0, expected_caller_received_video_frames, 0,
2778 0, kMaxWaitForFramesMs);
2779}
2780
2781// Test that we achieve the expected end-to-end connection time, using a
2782// fake clock and simulated latency on the media and signaling paths.
2783// We use a TURN<->TURN connection because this is usually the quickest to
2784// set up initially, especially when we're confident the connection will work
2785// and can start sending media before we get a STUN response.
2786//
2787// With various optimizations enabled, here are the network delays we expect to
2788// be on the critical path:
2789// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
2790// signaling answer (with DTLS fingerprint).
2791// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
2792// using TURN<->TURN pair, and DTLS exchange is 4 packets,
2793// the first of which should have arrived before the answer.
2794TEST_F(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
2795 rtc::ScopedFakeClock fake_clock;
2796 // Some things use a time of "0" as a special value, so we need to start out
2797 // the fake clock at a nonzero time.
2798 // TODO(deadbeef): Fix this.
2799 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2800
2801 static constexpr int media_hop_delay_ms = 50;
2802 static constexpr int signaling_trip_delay_ms = 500;
2803 // For explanation of these values, see comment above.
2804 static constexpr int required_media_hops = 9;
2805 static constexpr int required_signaling_trips = 2;
2806 // For internal delays (such as posting an event asychronously).
2807 static constexpr int allowed_internal_delay_ms = 20;
2808 static constexpr int total_connection_time_ms =
2809 media_hop_delay_ms * required_media_hops +
2810 signaling_trip_delay_ms * required_signaling_trips +
2811 allowed_internal_delay_ms;
2812
2813 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
2814 3478};
2815 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
2816 0};
2817 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
2818 3478};
2819 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
2820 0};
2821 cricket::TestTurnServer turn_server_1(network_thread(),
2822 turn_server_1_internal_address,
2823 turn_server_1_external_address);
2824 cricket::TestTurnServer turn_server_2(network_thread(),
2825 turn_server_2_internal_address,
2826 turn_server_2_external_address);
2827 // Bypass permission check on received packets so media can be sent before
2828 // the candidate is signaled.
2829 turn_server_1.set_enable_permission_checks(false);
2830 turn_server_2.set_enable_permission_checks(false);
2831
2832 PeerConnectionInterface::RTCConfiguration client_1_config;
2833 webrtc::PeerConnectionInterface::IceServer ice_server_1;
2834 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
2835 ice_server_1.username = "test";
2836 ice_server_1.password = "test";
2837 client_1_config.servers.push_back(ice_server_1);
2838 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
2839 client_1_config.presume_writable_when_fully_relayed = true;
2840
2841 PeerConnectionInterface::RTCConfiguration client_2_config;
2842 webrtc::PeerConnectionInterface::IceServer ice_server_2;
2843 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
2844 ice_server_2.username = "test";
2845 ice_server_2.password = "test";
2846 client_2_config.servers.push_back(ice_server_2);
2847 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
2848 client_2_config.presume_writable_when_fully_relayed = true;
2849
2850 ASSERT_TRUE(
2851 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
2852 // Set up the simulated delays.
2853 SetSignalingDelayMs(signaling_trip_delay_ms);
2854 ConnectFakeSignaling();
2855 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
2856 virtual_socket_server()->UpdateDelayDistribution();
2857
2858 // Set "offer to receive audio/video" without adding any tracks, so we just
2859 // set up ICE/DTLS with no media.
2860 PeerConnectionInterface::RTCOfferAnswerOptions options;
2861 options.offer_to_receive_audio = 1;
2862 options.offer_to_receive_video = 1;
2863 caller()->SetOfferAnswerOptions(options);
2864 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07002865 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
2866 fake_clock);
deadbeef1dcb1642017-03-29 21:08:16 -07002867 // Need to free the clients here since they're using things we created on
2868 // the stack.
2869 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
2870 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
2871}
2872
deadbeefc964d0b2017-04-03 10:03:35 -07002873// Test that audio and video flow end-to-end when codec names don't use the
2874// expected casing, given that they're supposed to be case insensitive. To test
2875// this, all but one codec is removed from each media description, and its
2876// casing is changed.
2877//
2878// In the past, this has regressed and caused crashes/black video, due to the
2879// fact that code at some layers was doing case-insensitive comparisons and
2880// code at other layers was not.
2881TEST_F(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
2882 ASSERT_TRUE(CreatePeerConnectionWrappers());
2883 ConnectFakeSignaling();
2884 caller()->AddAudioVideoMediaStream();
2885 callee()->AddAudioVideoMediaStream();
2886
2887 // Remove all but one audio/video codec (opus and VP8), and change the
2888 // casing of the caller's generated offer.
2889 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
2890 cricket::AudioContentDescription* audio =
2891 GetFirstAudioContentDescription(description);
2892 ASSERT_NE(nullptr, audio);
2893 auto audio_codecs = audio->codecs();
2894 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
2895 [](const cricket::AudioCodec& codec) {
2896 return codec.name != "opus";
2897 }),
2898 audio_codecs.end());
2899 ASSERT_EQ(1u, audio_codecs.size());
2900 audio_codecs[0].name = "OpUs";
2901 audio->set_codecs(audio_codecs);
2902
2903 cricket::VideoContentDescription* video =
2904 GetFirstVideoContentDescription(description);
2905 ASSERT_NE(nullptr, video);
2906 auto video_codecs = video->codecs();
2907 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
2908 [](const cricket::VideoCodec& codec) {
2909 return codec.name != "VP8";
2910 }),
2911 video_codecs.end());
2912 ASSERT_EQ(1u, video_codecs.size());
2913 video_codecs[0].name = "vP8";
2914 video->set_codecs(video_codecs);
2915 });
2916
2917 caller()->CreateAndSetAndSignalOffer();
2918 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2919
2920 // Verify frames are still received end-to-end.
2921 ExpectNewFramesReceivedWithWait(
2922 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2923 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2924 kMaxWaitForFramesMs);
2925}
2926
hbos8d609f62017-04-10 07:39:05 -07002927TEST_F(PeerConnectionIntegrationTest, GetSources) {
2928 ASSERT_TRUE(CreatePeerConnectionWrappers());
2929 ConnectFakeSignaling();
2930 caller()->AddAudioOnlyMediaStream();
2931 caller()->CreateAndSetAndSignalOffer();
2932 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07002933 // Wait for one audio frame to be received by the callee.
hbos8d609f62017-04-10 07:39:05 -07002934 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
2935 ASSERT_GT(callee()->pc()->GetReceivers().size(), 0u);
2936 auto receiver = callee()->pc()->GetReceivers()[0];
2937 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
2938
2939 auto contributing_sources = receiver->GetSources();
2940 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
2941 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
2942 contributing_sources[0].source_id());
2943}
2944
deadbeef2f425aa2017-04-14 10:41:32 -07002945// Test that if a track is removed and added again with a different stream ID,
2946// the new stream ID is successfully communicated in SDP and media continues to
2947// flow end-to-end.
2948TEST_F(PeerConnectionIntegrationTest, RemoveAndAddTrackWithNewStreamId) {
2949 ASSERT_TRUE(CreatePeerConnectionWrappers());
2950 ConnectFakeSignaling();
2951
2952 rtc::scoped_refptr<MediaStreamInterface> stream_1 =
2953 caller()->pc_factory()->CreateLocalMediaStream("stream_1");
2954 rtc::scoped_refptr<MediaStreamInterface> stream_2 =
2955 caller()->pc_factory()->CreateLocalMediaStream("stream_2");
2956
2957 // Add track using stream 1, do offer/answer.
2958 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2959 caller()->CreateLocalAudioTrack();
2960 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2961 caller()->pc()->AddTrack(track, {stream_1.get()});
2962 caller()->CreateAndSetAndSignalOffer();
2963 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2964 // Wait for one audio frame to be received by the callee.
2965 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
2966
2967 // Remove the sender, and create a new one with the new stream.
2968 caller()->pc()->RemoveTrack(sender);
2969 sender = caller()->pc()->AddTrack(track, {stream_2.get()});
2970 caller()->CreateAndSetAndSignalOffer();
2971 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2972 // Wait for additional audio frames to be received by the callee.
2973 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount, 0,
2974 kMaxWaitForFramesMs);
2975}
2976
deadbeef1dcb1642017-03-29 21:08:16 -07002977} // namespace
2978
2979#endif // if !defined(THREAD_SANITIZER)