blob: 21701cedde70926e4a27eb2bc955949d2ae4ad46 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "api/fakemetricsobserver.h"
26#include "api/mediastreaminterface.h"
27#include "api/peerconnectioninterface.h"
Steve Anton8c0f7a72017-10-03 10:03:10 -070028#include "api/peerconnectionproxy.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "api/test/fakeconstraints.h"
30#include "media/engine/fakewebrtcvideoengine.h"
31#include "p2p/base/p2pconstants.h"
32#include "p2p/base/portinterface.h"
33#include "p2p/base/sessiondescription.h"
Steve Antonede9ca52017-10-16 13:04:27 -070034#include "p2p/base/teststunserver.h"
Jonas Orelandbdcee282017-10-10 14:01:40 +020035#include "p2p/base/testturncustomizer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "p2p/base/testturnserver.h"
37#include "p2p/client/basicportallocator.h"
38#include "pc/dtmfsender.h"
39#include "pc/localaudiosource.h"
40#include "pc/mediasession.h"
41#include "pc/peerconnection.h"
42#include "pc/peerconnectionfactory.h"
43#include "pc/test/fakeaudiocapturemodule.h"
44#include "pc/test/fakeperiodicvideocapturer.h"
45#include "pc/test/fakertccertificategenerator.h"
46#include "pc/test/fakevideotrackrenderer.h"
47#include "pc/test/mockpeerconnectionobservers.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/fakenetwork.h"
Steve Antonede9ca52017-10-16 13:04:27 -070049#include "rtc_base/firewallsocketserver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/gunit.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "rtc_base/virtualsocketserver.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020052#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070053
54using cricket::ContentInfo;
55using cricket::FakeWebRtcVideoDecoder;
56using cricket::FakeWebRtcVideoDecoderFactory;
57using cricket::FakeWebRtcVideoEncoder;
58using cricket::FakeWebRtcVideoEncoderFactory;
59using cricket::MediaContentDescription;
Steve Antonede9ca52017-10-16 13:04:27 -070060using rtc::SocketAddress;
61using ::testing::ElementsAre;
62using ::testing::Values;
deadbeef1dcb1642017-03-29 21:08:16 -070063using webrtc::DataBuffer;
64using webrtc::DataChannelInterface;
65using webrtc::DtmfSender;
66using webrtc::DtmfSenderInterface;
67using webrtc::DtmfSenderObserverInterface;
68using webrtc::FakeConstraints;
69using webrtc::MediaConstraintsInterface;
70using webrtc::MediaStreamInterface;
71using webrtc::MediaStreamTrackInterface;
72using webrtc::MockCreateSessionDescriptionObserver;
73using webrtc::MockDataChannelObserver;
74using webrtc::MockSetSessionDescriptionObserver;
75using webrtc::MockStatsObserver;
76using webrtc::ObserverInterface;
Steve Anton8c0f7a72017-10-03 10:03:10 -070077using webrtc::PeerConnection;
deadbeef1dcb1642017-03-29 21:08:16 -070078using webrtc::PeerConnectionInterface;
79using webrtc::PeerConnectionFactory;
Steve Anton8c0f7a72017-10-03 10:03:10 -070080using webrtc::PeerConnectionProxy;
deadbeef1dcb1642017-03-29 21:08:16 -070081using webrtc::SessionDescriptionInterface;
82using webrtc::StreamCollectionInterface;
83
84namespace {
85
86static const int kDefaultTimeout = 10000;
87static const int kMaxWaitForStatsMs = 3000;
88static const int kMaxWaitForActivationMs = 5000;
89static const int kMaxWaitForFramesMs = 10000;
90// Default number of audio/video frames to wait for before considering a test
91// successful.
92static const int kDefaultExpectedAudioFrameCount = 3;
93static const int kDefaultExpectedVideoFrameCount = 3;
94
deadbeef1dcb1642017-03-29 21:08:16 -070095static const char kDataChannelLabel[] = "data_channel";
96
97// SRTP cipher name negotiated by the tests. This must be updated if the
98// default changes.
99static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_32;
100static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
101
Steve Antonede9ca52017-10-16 13:04:27 -0700102static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
103
deadbeef1dcb1642017-03-29 21:08:16 -0700104// Helper function for constructing offer/answer options to initiate an ICE
105// restart.
106PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
107 PeerConnectionInterface::RTCOfferAnswerOptions options;
108 options.ice_restart = true;
109 return options;
110}
111
deadbeefd8ad7882017-04-18 16:01:17 -0700112// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
113// attribute from received SDP, simulating a legacy endpoint.
114void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
115 for (ContentInfo& content : desc->contents()) {
116 MediaContentDescription* media_desc =
117 static_cast<MediaContentDescription*>(content.description);
118 media_desc->mutable_streams().clear();
119 }
120 desc->set_msid_supported(false);
121}
122
zhihuangf8164932017-05-19 13:09:47 -0700123int FindFirstMediaStatsIndexByKind(
124 const std::string& kind,
125 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
126 media_stats_vec) {
127 for (size_t i = 0; i < media_stats_vec.size(); i++) {
128 if (media_stats_vec[i]->kind.ValueToString() == kind) {
129 return i;
130 }
131 }
132 return -1;
133}
134
deadbeef1dcb1642017-03-29 21:08:16 -0700135class SignalingMessageReceiver {
136 public:
137 virtual void ReceiveSdpMessage(const std::string& type,
138 const std::string& msg) = 0;
139 virtual void ReceiveIceMessage(const std::string& sdp_mid,
140 int sdp_mline_index,
141 const std::string& msg) = 0;
142
143 protected:
144 SignalingMessageReceiver() {}
145 virtual ~SignalingMessageReceiver() {}
146};
147
148class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
149 public:
150 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
151 : expected_media_type_(media_type) {}
152
153 void OnFirstPacketReceived(cricket::MediaType media_type) override {
154 ASSERT_EQ(expected_media_type_, media_type);
155 first_packet_received_ = true;
156 }
157
158 bool first_packet_received() const { return first_packet_received_; }
159
160 virtual ~MockRtpReceiverObserver() {}
161
162 private:
163 bool first_packet_received_ = false;
164 cricket::MediaType expected_media_type_;
165};
166
167// Helper class that wraps a peer connection, observes it, and can accept
168// signaling messages from another wrapper.
169//
170// Uses a fake network, fake A/V capture, and optionally fake
171// encoders/decoders, though they aren't used by default since they don't
172// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700173// TODO(steveanton): See how this could become a subclass of
174// PeerConnectionWrapper defined in peerconnectionwrapper.h .
deadbeef1dcb1642017-03-29 21:08:16 -0700175class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
176 public SignalingMessageReceiver,
177 public ObserverInterface {
178 public:
179 // Different factory methods for convenience.
180 // TODO(deadbeef): Could use the pattern of:
181 //
182 // PeerConnectionWrapper =
183 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
184 //
185 // To reduce some code duplication.
186 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
187 const std::string& debug_name,
188 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
189 rtc::Thread* network_thread,
190 rtc::Thread* worker_thread) {
191 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
192 if (!client->Init(nullptr, nullptr, nullptr, std::move(cert_generator),
193 network_thread, worker_thread)) {
194 delete client;
195 return nullptr;
196 }
197 return client;
198 }
199
200 static PeerConnectionWrapper* CreateWithConfig(
201 const std::string& debug_name,
202 const PeerConnectionInterface::RTCConfiguration& config,
203 rtc::Thread* network_thread,
204 rtc::Thread* worker_thread) {
205 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
206 new FakeRTCCertificateGenerator());
207 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
208 if (!client->Init(nullptr, nullptr, &config, std::move(cert_generator),
209 network_thread, worker_thread)) {
210 delete client;
211 return nullptr;
212 }
213 return client;
214 }
215
216 static PeerConnectionWrapper* CreateWithOptions(
217 const std::string& debug_name,
218 const PeerConnectionFactory::Options& options,
219 rtc::Thread* network_thread,
220 rtc::Thread* worker_thread) {
221 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
222 new FakeRTCCertificateGenerator());
223 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
224 if (!client->Init(nullptr, &options, nullptr, std::move(cert_generator),
225 network_thread, worker_thread)) {
226 delete client;
227 return nullptr;
228 }
229 return client;
230 }
231
232 static PeerConnectionWrapper* CreateWithConstraints(
233 const std::string& debug_name,
234 const MediaConstraintsInterface* constraints,
235 rtc::Thread* network_thread,
236 rtc::Thread* worker_thread) {
237 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
238 new FakeRTCCertificateGenerator());
239 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
240 if (!client->Init(constraints, nullptr, nullptr, std::move(cert_generator),
241 network_thread, worker_thread)) {
242 delete client;
243 return nullptr;
244 }
245 return client;
246 }
247
deadbeef2f425aa2017-04-14 10:41:32 -0700248 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
249 return peer_connection_factory_.get();
250 }
251
deadbeef1dcb1642017-03-29 21:08:16 -0700252 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
253
254 // If a signaling message receiver is set (via ConnectFakeSignaling), this
255 // will set the whole offer/answer exchange in motion. Just need to wait for
256 // the signaling state to reach "stable".
257 void CreateAndSetAndSignalOffer() {
258 auto offer = CreateOffer();
259 ASSERT_NE(nullptr, offer);
260 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
261 }
262
263 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
264 // when a remote offer is received (via fake signaling) and an answer is
265 // generated. By default, uses default options.
266 void SetOfferAnswerOptions(
267 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
268 offer_answer_options_ = options;
269 }
270
271 // Set a callback to be invoked when SDP is received via the fake signaling
272 // channel, which provides an opportunity to munge (modify) the SDP. This is
273 // used to test SDP being applied that a PeerConnection would normally not
274 // generate, but a non-JSEP endpoint might.
275 void SetReceivedSdpMunger(
276 std::function<void(cricket::SessionDescription*)> munger) {
277 received_sdp_munger_ = munger;
278 }
279
deadbeefc964d0b2017-04-03 10:03:35 -0700280 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700281 // generated.
282 void SetGeneratedSdpMunger(
283 std::function<void(cricket::SessionDescription*)> munger) {
284 generated_sdp_munger_ = munger;
285 }
286
Steve Antonede9ca52017-10-16 13:04:27 -0700287 // Every ICE connection state in order that has been seen by the observer.
288 std::vector<PeerConnectionInterface::IceConnectionState>
289 ice_connection_state_history() const {
290 return ice_connection_state_history_;
291 }
292
293 // Every ICE gathering state in order that has been seen by the observer.
294 std::vector<PeerConnectionInterface::IceGatheringState>
295 ice_gathering_state_history() const {
296 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700297 }
298
299 // TODO(deadbeef): Switch the majority of these tests to use AddTrack instead
300 // of AddStream since AddStream is deprecated.
301 void AddAudioVideoMediaStream() {
302 AddMediaStreamFromTracks(CreateLocalAudioTrack(), CreateLocalVideoTrack());
303 }
304
305 void AddAudioOnlyMediaStream() {
306 AddMediaStreamFromTracks(CreateLocalAudioTrack(), nullptr);
307 }
308
309 void AddVideoOnlyMediaStream() {
310 AddMediaStreamFromTracks(nullptr, CreateLocalVideoTrack());
311 }
312
313 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
314 FakeConstraints constraints;
315 // Disable highpass filter so that we can get all the test audio frames.
316 constraints.AddMandatory(MediaConstraintsInterface::kHighpassFilter, false);
317 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
318 peer_connection_factory_->CreateAudioSource(&constraints);
319 // TODO(perkj): Test audio source when it is implemented. Currently audio
320 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700321 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700322 source);
323 }
324
325 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
deadbeefb1a15d72017-09-07 14:12:05 -0700326 return CreateLocalVideoTrackInternal(FakeConstraints(),
327 webrtc::kVideoRotation_0);
deadbeef1dcb1642017-03-29 21:08:16 -0700328 }
329
330 rtc::scoped_refptr<webrtc::VideoTrackInterface>
331 CreateLocalVideoTrackWithConstraints(const FakeConstraints& constraints) {
deadbeefb1a15d72017-09-07 14:12:05 -0700332 return CreateLocalVideoTrackInternal(constraints, webrtc::kVideoRotation_0);
deadbeef1dcb1642017-03-29 21:08:16 -0700333 }
334
335 rtc::scoped_refptr<webrtc::VideoTrackInterface>
336 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
deadbeefb1a15d72017-09-07 14:12:05 -0700337 return CreateLocalVideoTrackInternal(FakeConstraints(), rotation);
deadbeef1dcb1642017-03-29 21:08:16 -0700338 }
339
340 void AddMediaStreamFromTracks(
341 rtc::scoped_refptr<webrtc::AudioTrackInterface> audio,
342 rtc::scoped_refptr<webrtc::VideoTrackInterface> video) {
deadbeef1dcb1642017-03-29 21:08:16 -0700343 rtc::scoped_refptr<MediaStreamInterface> stream =
deadbeefb1a15d72017-09-07 14:12:05 -0700344 peer_connection_factory_->CreateLocalMediaStream(
345 rtc::CreateRandomUuid());
deadbeef1dcb1642017-03-29 21:08:16 -0700346 if (audio) {
347 stream->AddTrack(audio);
348 }
349 if (video) {
350 stream->AddTrack(video);
351 }
352 EXPECT_TRUE(pc()->AddStream(stream));
353 }
354
355 bool SignalingStateStable() {
356 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
357 }
358
359 void CreateDataChannel() { CreateDataChannel(nullptr); }
360
361 void CreateDataChannel(const webrtc::DataChannelInit* init) {
362 data_channel_ = pc()->CreateDataChannel(kDataChannelLabel, init);
363 ASSERT_TRUE(data_channel_.get() != nullptr);
364 data_observer_.reset(new MockDataChannelObserver(data_channel_));
365 }
366
367 DataChannelInterface* data_channel() { return data_channel_; }
368 const MockDataChannelObserver* data_observer() const {
369 return data_observer_.get();
370 }
371
372 int audio_frames_received() const {
373 return fake_audio_capture_module_->frames_received();
374 }
375
376 // Takes minimum of video frames received for each track.
377 //
378 // Can be used like:
379 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
380 //
381 // To ensure that all video tracks received at least a certain number of
382 // frames.
383 int min_video_frames_received_per_track() const {
384 int min_frames = INT_MAX;
385 if (video_decoder_factory_enabled_) {
386 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
387 fake_video_decoder_factory_->decoders();
388 if (decoders.empty()) {
389 return 0;
390 }
391 for (FakeWebRtcVideoDecoder* decoder : decoders) {
392 min_frames = std::min(min_frames, decoder->GetNumFramesReceived());
393 }
394 return min_frames;
395 } else {
396 if (fake_video_renderers_.empty()) {
397 return 0;
398 }
399
400 for (const auto& pair : fake_video_renderers_) {
401 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
402 }
403 return min_frames;
404 }
405 }
406
407 // In contrast to the above, sums the video frames received for all tracks.
408 // Can be used to verify that no video frames were received, or that the
409 // counts didn't increase.
410 int total_video_frames_received() const {
411 int total = 0;
412 if (video_decoder_factory_enabled_) {
413 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
414 fake_video_decoder_factory_->decoders();
415 for (const FakeWebRtcVideoDecoder* decoder : decoders) {
416 total += decoder->GetNumFramesReceived();
417 }
418 } else {
419 for (const auto& pair : fake_video_renderers_) {
420 total += pair.second->num_rendered_frames();
421 }
422 for (const auto& renderer : removed_fake_video_renderers_) {
423 total += renderer->num_rendered_frames();
424 }
425 }
426 return total;
427 }
428
429 // Returns a MockStatsObserver in a state after stats gathering finished,
430 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700431 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700432 webrtc::MediaStreamTrackInterface* track) {
433 rtc::scoped_refptr<MockStatsObserver> observer(
434 new rtc::RefCountedObject<MockStatsObserver>());
435 EXPECT_TRUE(peer_connection_->GetStats(
436 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
437 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
438 return observer;
439 }
440
441 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700442 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
443 return OldGetStatsForTrack(nullptr);
444 }
445
446 // Synchronously gets stats and returns them. If it times out, fails the test
447 // and returns null.
448 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
449 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
450 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
451 peer_connection_->GetStats(callback);
452 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
453 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700454 }
455
456 int rendered_width() {
457 EXPECT_FALSE(fake_video_renderers_.empty());
458 return fake_video_renderers_.empty()
459 ? 0
460 : fake_video_renderers_.begin()->second->width();
461 }
462
463 int rendered_height() {
464 EXPECT_FALSE(fake_video_renderers_.empty());
465 return fake_video_renderers_.empty()
466 ? 0
467 : fake_video_renderers_.begin()->second->height();
468 }
469
470 double rendered_aspect_ratio() {
471 if (rendered_height() == 0) {
472 return 0.0;
473 }
474 return static_cast<double>(rendered_width()) / rendered_height();
475 }
476
477 webrtc::VideoRotation rendered_rotation() {
478 EXPECT_FALSE(fake_video_renderers_.empty());
479 return fake_video_renderers_.empty()
480 ? webrtc::kVideoRotation_0
481 : fake_video_renderers_.begin()->second->rotation();
482 }
483
484 int local_rendered_width() {
485 return local_video_renderer_ ? local_video_renderer_->width() : 0;
486 }
487
488 int local_rendered_height() {
489 return local_video_renderer_ ? local_video_renderer_->height() : 0;
490 }
491
492 double local_rendered_aspect_ratio() {
493 if (local_rendered_height() == 0) {
494 return 0.0;
495 }
496 return static_cast<double>(local_rendered_width()) /
497 local_rendered_height();
498 }
499
500 size_t number_of_remote_streams() {
501 if (!pc()) {
502 return 0;
503 }
504 return pc()->remote_streams()->count();
505 }
506
507 StreamCollectionInterface* remote_streams() const {
508 if (!pc()) {
509 ADD_FAILURE();
510 return nullptr;
511 }
512 return pc()->remote_streams();
513 }
514
515 StreamCollectionInterface* local_streams() {
516 if (!pc()) {
517 ADD_FAILURE();
518 return nullptr;
519 }
520 return pc()->local_streams();
521 }
522
523 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
524 return pc()->signaling_state();
525 }
526
527 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
528 return pc()->ice_connection_state();
529 }
530
531 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
532 return pc()->ice_gathering_state();
533 }
534
535 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
536 // GetReceivers. They're updated automatically when a remote offer/answer
537 // from the fake signaling channel is applied, or when
538 // ResetRtpReceiverObservers below is called.
539 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
540 rtp_receiver_observers() {
541 return rtp_receiver_observers_;
542 }
543
544 void ResetRtpReceiverObservers() {
545 rtp_receiver_observers_.clear();
546 for (auto receiver : pc()->GetReceivers()) {
547 std::unique_ptr<MockRtpReceiverObserver> observer(
548 new MockRtpReceiverObserver(receiver->media_type()));
549 receiver->SetObserver(observer.get());
550 rtp_receiver_observers_.push_back(std::move(observer));
551 }
552 }
553
Steve Antonede9ca52017-10-16 13:04:27 -0700554 rtc::FakeNetworkManager* network() const {
555 return fake_network_manager_.get();
556 }
557 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
558
deadbeef1dcb1642017-03-29 21:08:16 -0700559 private:
560 explicit PeerConnectionWrapper(const std::string& debug_name)
561 : debug_name_(debug_name) {}
562
563 bool Init(
564 const MediaConstraintsInterface* constraints,
565 const PeerConnectionFactory::Options* options,
566 const PeerConnectionInterface::RTCConfiguration* config,
567 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
568 rtc::Thread* network_thread,
569 rtc::Thread* worker_thread) {
570 // There's an error in this test code if Init ends up being called twice.
571 RTC_DCHECK(!peer_connection_);
572 RTC_DCHECK(!peer_connection_factory_);
573
574 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700575 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700576
577 std::unique_ptr<cricket::PortAllocator> port_allocator(
578 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700579 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700580 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
581 if (!fake_audio_capture_module_) {
582 return false;
583 }
584 // Note that these factories don't end up getting used unless supported
585 // codecs are added to them.
586 fake_video_decoder_factory_ = new FakeWebRtcVideoDecoderFactory();
587 fake_video_encoder_factory_ = new FakeWebRtcVideoEncoderFactory();
588 rtc::Thread* const signaling_thread = rtc::Thread::Current();
589 peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(
590 network_thread, worker_thread, signaling_thread,
591 fake_audio_capture_module_, fake_video_encoder_factory_,
592 fake_video_decoder_factory_);
593 if (!peer_connection_factory_) {
594 return false;
595 }
596 if (options) {
597 peer_connection_factory_->SetOptions(*options);
598 }
599 peer_connection_ =
600 CreatePeerConnection(std::move(port_allocator), constraints, config,
601 std::move(cert_generator));
602 return peer_connection_.get() != nullptr;
603 }
604
605 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
606 std::unique_ptr<cricket::PortAllocator> port_allocator,
607 const MediaConstraintsInterface* constraints,
608 const PeerConnectionInterface::RTCConfiguration* config,
609 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator) {
610 PeerConnectionInterface::RTCConfiguration modified_config;
611 // If |config| is null, this will result in a default configuration being
612 // used.
613 if (config) {
614 modified_config = *config;
615 }
616 // Disable resolution adaptation; we don't want it interfering with the
617 // test results.
618 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
619 // ratios and not specific resolutions, is this even necessary?
620 modified_config.set_cpu_adaptation(false);
621
622 return peer_connection_factory_->CreatePeerConnection(
623 modified_config, constraints, std::move(port_allocator),
624 std::move(cert_generator), this);
625 }
626
627 void set_signaling_message_receiver(
628 SignalingMessageReceiver* signaling_message_receiver) {
629 signaling_message_receiver_ = signaling_message_receiver;
630 }
631
632 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
633
Steve Antonede9ca52017-10-16 13:04:27 -0700634 void set_signal_ice_candidates(bool signal) {
635 signal_ice_candidates_ = signal;
636 }
637
deadbeef1dcb1642017-03-29 21:08:16 -0700638 void EnableVideoDecoderFactory() {
639 video_decoder_factory_enabled_ = true;
640 fake_video_decoder_factory_->AddSupportedVideoCodecType(
641 webrtc::kVideoCodecVP8);
642 }
643
644 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
deadbeef1dcb1642017-03-29 21:08:16 -0700645 const FakeConstraints& constraints,
646 webrtc::VideoRotation rotation) {
647 // Set max frame rate to 10fps to reduce the risk of test flakiness.
648 // TODO(deadbeef): Do something more robust.
649 FakeConstraints source_constraints = constraints;
650 source_constraints.SetMandatoryMaxFrameRate(10);
651
652 cricket::FakeVideoCapturer* fake_capturer =
653 new webrtc::FakePeriodicVideoCapturer();
654 fake_capturer->SetRotation(rotation);
655 video_capturers_.push_back(fake_capturer);
656 rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source =
657 peer_connection_factory_->CreateVideoSource(fake_capturer,
658 &source_constraints);
659 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
deadbeefb1a15d72017-09-07 14:12:05 -0700660 peer_connection_factory_->CreateVideoTrack(rtc::CreateRandomUuid(),
661 source));
deadbeef1dcb1642017-03-29 21:08:16 -0700662 if (!local_video_renderer_) {
663 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
664 }
665 return track;
666 }
667
668 void HandleIncomingOffer(const std::string& msg) {
669 LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
670 std::unique_ptr<SessionDescriptionInterface> desc(
671 webrtc::CreateSessionDescription("offer", msg, nullptr));
672 if (received_sdp_munger_) {
673 received_sdp_munger_(desc->description());
674 }
675
676 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
677 // Setting a remote description may have changed the number of receivers,
678 // so reset the receiver observers.
679 ResetRtpReceiverObservers();
680 auto answer = CreateAnswer();
681 ASSERT_NE(nullptr, answer);
682 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
683 }
684
685 void HandleIncomingAnswer(const std::string& msg) {
686 LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
687 std::unique_ptr<SessionDescriptionInterface> desc(
688 webrtc::CreateSessionDescription("answer", msg, nullptr));
689 if (received_sdp_munger_) {
690 received_sdp_munger_(desc->description());
691 }
692
693 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
694 // Set the RtpReceiverObserver after receivers are created.
695 ResetRtpReceiverObservers();
696 }
697
698 // Returns null on failure.
699 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
700 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
701 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
702 pc()->CreateOffer(observer, offer_answer_options_);
703 return WaitForDescriptionFromObserver(observer);
704 }
705
706 // Returns null on failure.
707 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
708 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
709 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
710 pc()->CreateAnswer(observer, offer_answer_options_);
711 return WaitForDescriptionFromObserver(observer);
712 }
713
714 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
715 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer) {
716 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
717 if (!observer->result()) {
718 return nullptr;
719 }
720 auto description = observer->MoveDescription();
721 if (generated_sdp_munger_) {
722 generated_sdp_munger_(description->description());
723 }
724 return description;
725 }
726
727 // Setting the local description and sending the SDP message over the fake
728 // signaling channel are combined into the same method because the SDP
729 // message needs to be sent as soon as SetLocalDescription finishes, without
730 // waiting for the observer to be called. This ensures that ICE candidates
731 // don't outrace the description.
732 bool SetLocalDescriptionAndSendSdpMessage(
733 std::unique_ptr<SessionDescriptionInterface> desc) {
734 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
735 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
736 LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
737 std::string type = desc->type();
738 std::string sdp;
739 EXPECT_TRUE(desc->ToString(&sdp));
740 pc()->SetLocalDescription(observer, desc.release());
741 // As mentioned above, we need to send the message immediately after
742 // SetLocalDescription.
743 SendSdpMessage(type, sdp);
744 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
745 return true;
746 }
747
748 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
749 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
750 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
751 LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
752 pc()->SetRemoteDescription(observer, desc.release());
753 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
754 return observer->result();
755 }
756
757 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
758 // default).
759 void SendSdpMessage(const std::string& type, const std::string& msg) {
760 if (signaling_delay_ms_ == 0) {
761 RelaySdpMessageIfReceiverExists(type, msg);
762 } else {
763 invoker_.AsyncInvokeDelayed<void>(
764 RTC_FROM_HERE, rtc::Thread::Current(),
765 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
766 this, type, msg),
767 signaling_delay_ms_);
768 }
769 }
770
771 void RelaySdpMessageIfReceiverExists(const std::string& type,
772 const std::string& msg) {
773 if (signaling_message_receiver_) {
774 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
775 }
776 }
777
778 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
779 // default).
780 void SendIceMessage(const std::string& sdp_mid,
781 int sdp_mline_index,
782 const std::string& msg) {
783 if (signaling_delay_ms_ == 0) {
784 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
785 } else {
786 invoker_.AsyncInvokeDelayed<void>(
787 RTC_FROM_HERE, rtc::Thread::Current(),
788 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
789 this, sdp_mid, sdp_mline_index, msg),
790 signaling_delay_ms_);
791 }
792 }
793
794 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
795 int sdp_mline_index,
796 const std::string& msg) {
797 if (signaling_message_receiver_) {
798 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
799 msg);
800 }
801 }
802
803 // SignalingMessageReceiver callbacks.
804 void ReceiveSdpMessage(const std::string& type,
805 const std::string& msg) override {
806 if (type == webrtc::SessionDescriptionInterface::kOffer) {
807 HandleIncomingOffer(msg);
808 } else {
809 HandleIncomingAnswer(msg);
810 }
811 }
812
813 void ReceiveIceMessage(const std::string& sdp_mid,
814 int sdp_mline_index,
815 const std::string& msg) override {
816 LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
817 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
818 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
819 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
820 }
821
822 // PeerConnectionObserver callbacks.
823 void OnSignalingChange(
824 webrtc::PeerConnectionInterface::SignalingState new_state) override {
825 EXPECT_EQ(pc()->signaling_state(), new_state);
826 }
827 void OnAddStream(
828 rtc::scoped_refptr<MediaStreamInterface> media_stream) override {
829 media_stream->RegisterObserver(this);
830 for (size_t i = 0; i < media_stream->GetVideoTracks().size(); ++i) {
831 const std::string id = media_stream->GetVideoTracks()[i]->id();
832 ASSERT_TRUE(fake_video_renderers_.find(id) ==
833 fake_video_renderers_.end());
834 fake_video_renderers_[id].reset(new webrtc::FakeVideoTrackRenderer(
835 media_stream->GetVideoTracks()[i]));
836 }
837 }
838 void OnRemoveStream(
839 rtc::scoped_refptr<MediaStreamInterface> media_stream) override {}
840 void OnRenegotiationNeeded() override {}
841 void OnIceConnectionChange(
842 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
843 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700844 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700845 }
846 void OnIceGatheringChange(
847 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700848 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700849 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700850 }
851 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
852 LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
853
854 std::string ice_sdp;
855 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700856 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700857 // Remote party may be deleted.
858 return;
859 }
860 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
861 }
862 void OnDataChannel(
863 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
864 LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
865 data_channel_ = data_channel;
866 data_observer_.reset(new MockDataChannelObserver(data_channel));
867 }
868
869 // MediaStreamInterface callback
870 void OnChanged() override {
871 // Track added or removed from MediaStream, so update our renderers.
872 rtc::scoped_refptr<StreamCollectionInterface> remote_streams =
873 pc()->remote_streams();
874 // Remove renderers for tracks that were removed.
875 for (auto it = fake_video_renderers_.begin();
876 it != fake_video_renderers_.end();) {
877 if (remote_streams->FindVideoTrack(it->first) == nullptr) {
878 auto to_remove = it++;
879 removed_fake_video_renderers_.push_back(std::move(to_remove->second));
880 fake_video_renderers_.erase(to_remove);
881 } else {
882 ++it;
883 }
884 }
885 // Create renderers for new video tracks.
886 for (size_t stream_index = 0; stream_index < remote_streams->count();
887 ++stream_index) {
888 MediaStreamInterface* remote_stream = remote_streams->at(stream_index);
889 for (size_t track_index = 0;
890 track_index < remote_stream->GetVideoTracks().size();
891 ++track_index) {
892 const std::string id =
893 remote_stream->GetVideoTracks()[track_index]->id();
894 if (fake_video_renderers_.find(id) != fake_video_renderers_.end()) {
895 continue;
896 }
897 fake_video_renderers_[id].reset(new webrtc::FakeVideoTrackRenderer(
898 remote_stream->GetVideoTracks()[track_index]));
899 }
900 }
901 }
902
903 std::string debug_name_;
904
905 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
906
907 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
908 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
909 peer_connection_factory_;
910
Steve Antonede9ca52017-10-16 13:04:27 -0700911 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700912 // Needed to keep track of number of frames sent.
913 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
914 // Needed to keep track of number of frames received.
915 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
916 fake_video_renderers_;
917 // Needed to ensure frames aren't received for removed tracks.
918 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
919 removed_fake_video_renderers_;
920 // Needed to keep track of number of frames received when external decoder
921 // used.
922 FakeWebRtcVideoDecoderFactory* fake_video_decoder_factory_ = nullptr;
923 FakeWebRtcVideoEncoderFactory* fake_video_encoder_factory_ = nullptr;
924 bool video_decoder_factory_enabled_ = false;
925
926 // For remote peer communication.
927 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
928 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -0700929 bool signal_ice_candidates_ = true;
deadbeef1dcb1642017-03-29 21:08:16 -0700930
931 // Store references to the video capturers we've created, so that we can stop
932 // them, if required.
933 std::vector<cricket::FakeVideoCapturer*> video_capturers_;
934 // |local_video_renderer_| attached to the first created local video track.
935 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
936
937 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
938 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
939 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
940
941 rtc::scoped_refptr<DataChannelInterface> data_channel_;
942 std::unique_ptr<MockDataChannelObserver> data_observer_;
943
944 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
945
Steve Antonede9ca52017-10-16 13:04:27 -0700946 std::vector<PeerConnectionInterface::IceConnectionState>
947 ice_connection_state_history_;
948 std::vector<PeerConnectionInterface::IceGatheringState>
949 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700950
951 rtc::AsyncInvoker invoker_;
952
953 friend class PeerConnectionIntegrationTest;
954};
955
Elad Alon99c3fe52017-10-13 16:29:40 +0200956class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
957 public:
958 virtual ~MockRtcEventLogOutput() = default;
959 MOCK_CONST_METHOD0(IsActive, bool());
960 MOCK_METHOD1(Write, bool(const std::string&));
961};
962
deadbeef1dcb1642017-03-29 21:08:16 -0700963// Tests two PeerConnections connecting to each other end-to-end, using a
964// virtual network, fake A/V capture and fake encoder/decoders. The
965// PeerConnections share the threads/socket servers, but use separate versions
966// of everything else (including "PeerConnectionFactory"s).
967class PeerConnectionIntegrationTest : public testing::Test {
968 public:
969 PeerConnectionIntegrationTest()
deadbeef98e186c2017-05-16 18:00:06 -0700970 : ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -0700971 fss_(new rtc::FirewallSocketServer(ss_.get())),
972 network_thread_(new rtc::Thread(fss_.get())),
deadbeef1dcb1642017-03-29 21:08:16 -0700973 worker_thread_(rtc::Thread::Create()) {
974 RTC_CHECK(network_thread_->Start());
975 RTC_CHECK(worker_thread_->Start());
976 }
977
978 ~PeerConnectionIntegrationTest() {
979 if (caller_) {
980 caller_->set_signaling_message_receiver(nullptr);
981 }
982 if (callee_) {
983 callee_->set_signaling_message_receiver(nullptr);
984 }
985 }
986
987 bool SignalingStateStable() {
988 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
989 }
990
deadbeef71452802017-05-07 17:21:01 -0700991 bool DtlsConnected() {
992 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
993 // are connected. This is an important distinction. Once we have separate
994 // ICE and DTLS state, this check needs to use the DTLS state.
995 return (callee()->ice_connection_state() ==
996 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
997 callee()->ice_connection_state() ==
998 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
999 (caller()->ice_connection_state() ==
1000 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1001 caller()->ice_connection_state() ==
1002 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
1003 }
1004
deadbeef1dcb1642017-03-29 21:08:16 -07001005 bool CreatePeerConnectionWrappers() {
1006 return CreatePeerConnectionWrappersWithConfig(
1007 PeerConnectionInterface::RTCConfiguration(),
1008 PeerConnectionInterface::RTCConfiguration());
1009 }
1010
1011 bool CreatePeerConnectionWrappersWithConstraints(
1012 MediaConstraintsInterface* caller_constraints,
1013 MediaConstraintsInterface* callee_constraints) {
1014 caller_.reset(PeerConnectionWrapper::CreateWithConstraints(
1015 "Caller", caller_constraints, network_thread_.get(),
1016 worker_thread_.get()));
1017 callee_.reset(PeerConnectionWrapper::CreateWithConstraints(
1018 "Callee", callee_constraints, network_thread_.get(),
1019 worker_thread_.get()));
1020 return caller_ && callee_;
1021 }
1022
1023 bool CreatePeerConnectionWrappersWithConfig(
1024 const PeerConnectionInterface::RTCConfiguration& caller_config,
1025 const PeerConnectionInterface::RTCConfiguration& callee_config) {
1026 caller_.reset(PeerConnectionWrapper::CreateWithConfig(
1027 "Caller", caller_config, network_thread_.get(), worker_thread_.get()));
1028 callee_.reset(PeerConnectionWrapper::CreateWithConfig(
1029 "Callee", callee_config, network_thread_.get(), worker_thread_.get()));
1030 return caller_ && callee_;
1031 }
1032
1033 bool CreatePeerConnectionWrappersWithOptions(
1034 const PeerConnectionFactory::Options& caller_options,
1035 const PeerConnectionFactory::Options& callee_options) {
1036 caller_.reset(PeerConnectionWrapper::CreateWithOptions(
1037 "Caller", caller_options, network_thread_.get(), worker_thread_.get()));
1038 callee_.reset(PeerConnectionWrapper::CreateWithOptions(
1039 "Callee", callee_options, network_thread_.get(), worker_thread_.get()));
1040 return caller_ && callee_;
1041 }
1042
1043 PeerConnectionWrapper* CreatePeerConnectionWrapperWithAlternateKey() {
1044 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1045 new FakeRTCCertificateGenerator());
1046 cert_generator->use_alternate_key();
1047
1048 // Make sure the new client is using a different certificate.
1049 return PeerConnectionWrapper::CreateWithDtlsIdentityStore(
1050 "New Peer", std::move(cert_generator), network_thread_.get(),
1051 worker_thread_.get());
1052 }
1053
1054 // Once called, SDP blobs and ICE candidates will be automatically signaled
1055 // between PeerConnections.
1056 void ConnectFakeSignaling() {
1057 caller_->set_signaling_message_receiver(callee_.get());
1058 callee_->set_signaling_message_receiver(caller_.get());
1059 }
1060
Steve Antonede9ca52017-10-16 13:04:27 -07001061 // Once called, SDP blobs will be automatically signaled between
1062 // PeerConnections. Note that ICE candidates will not be signaled unless they
1063 // are in the exchanged SDP blobs.
1064 void ConnectFakeSignalingForSdpOnly() {
1065 ConnectFakeSignaling();
1066 SetSignalIceCandidates(false);
1067 }
1068
deadbeef1dcb1642017-03-29 21:08:16 -07001069 void SetSignalingDelayMs(int delay_ms) {
1070 caller_->set_signaling_delay_ms(delay_ms);
1071 callee_->set_signaling_delay_ms(delay_ms);
1072 }
1073
Steve Antonede9ca52017-10-16 13:04:27 -07001074 void SetSignalIceCandidates(bool signal) {
1075 caller_->set_signal_ice_candidates(signal);
1076 callee_->set_signal_ice_candidates(signal);
1077 }
1078
deadbeef1dcb1642017-03-29 21:08:16 -07001079 void EnableVideoDecoderFactory() {
1080 caller_->EnableVideoDecoderFactory();
1081 callee_->EnableVideoDecoderFactory();
1082 }
1083
1084 // Messages may get lost on the unreliable DataChannel, so we send multiple
1085 // times to avoid test flakiness.
1086 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1087 const std::string& data,
1088 int retries) {
1089 for (int i = 0; i < retries; ++i) {
1090 dc->Send(DataBuffer(data));
1091 }
1092 }
1093
1094 rtc::Thread* network_thread() { return network_thread_.get(); }
1095
1096 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1097
1098 PeerConnectionWrapper* caller() { return caller_.get(); }
1099
1100 // Set the |caller_| to the |wrapper| passed in and return the
1101 // original |caller_|.
1102 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1103 PeerConnectionWrapper* wrapper) {
1104 PeerConnectionWrapper* old = caller_.release();
1105 caller_.reset(wrapper);
1106 return old;
1107 }
1108
1109 PeerConnectionWrapper* callee() { return callee_.get(); }
1110
1111 // Set the |callee_| to the |wrapper| passed in and return the
1112 // original |callee_|.
1113 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1114 PeerConnectionWrapper* wrapper) {
1115 PeerConnectionWrapper* old = callee_.release();
1116 callee_.reset(wrapper);
1117 return old;
1118 }
1119
Steve Antonede9ca52017-10-16 13:04:27 -07001120 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1121
deadbeef1dcb1642017-03-29 21:08:16 -07001122 // Expects the provided number of new frames to be received within |wait_ms|.
1123 // "New frames" meaning that it waits for the current frame counts to
1124 // *increase* by the provided values. For video, uses
1125 // RecievedVideoFramesForEachTrack for the case of multiple video tracks
1126 // being received.
1127 void ExpectNewFramesReceivedWithWait(
1128 int expected_caller_received_audio_frames,
1129 int expected_caller_received_video_frames,
1130 int expected_callee_received_audio_frames,
1131 int expected_callee_received_video_frames,
1132 int wait_ms) {
1133 // Add current frame counts to the provided values, in order to wait for
1134 // the frame count to increase.
1135 expected_caller_received_audio_frames += caller()->audio_frames_received();
1136 expected_caller_received_video_frames +=
1137 caller()->min_video_frames_received_per_track();
1138 expected_callee_received_audio_frames += callee()->audio_frames_received();
1139 expected_callee_received_video_frames +=
1140 callee()->min_video_frames_received_per_track();
1141
1142 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
1143 expected_caller_received_audio_frames &&
1144 caller()->min_video_frames_received_per_track() >=
1145 expected_caller_received_video_frames &&
1146 callee()->audio_frames_received() >=
1147 expected_callee_received_audio_frames &&
1148 callee()->min_video_frames_received_per_track() >=
1149 expected_callee_received_video_frames,
1150 wait_ms);
1151
1152 // After the combined wait, do an "expect" for each individual count, to
1153 // print out a more detailed message upon failure.
1154 EXPECT_GE(caller()->audio_frames_received(),
1155 expected_caller_received_audio_frames);
1156 EXPECT_GE(caller()->min_video_frames_received_per_track(),
1157 expected_caller_received_video_frames);
1158 EXPECT_GE(callee()->audio_frames_received(),
1159 expected_callee_received_audio_frames);
1160 EXPECT_GE(callee()->min_video_frames_received_per_track(),
1161 expected_callee_received_video_frames);
1162 }
1163
1164 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1165 bool remote_gcm_enabled,
1166 int expected_cipher_suite) {
1167 PeerConnectionFactory::Options caller_options;
1168 caller_options.crypto_options.enable_gcm_crypto_suites = local_gcm_enabled;
1169 PeerConnectionFactory::Options callee_options;
1170 callee_options.crypto_options.enable_gcm_crypto_suites = remote_gcm_enabled;
1171 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1172 callee_options));
1173 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1174 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1175 caller()->pc()->RegisterUMAObserver(caller_observer);
1176 ConnectFakeSignaling();
1177 caller()->AddAudioVideoMediaStream();
1178 callee()->AddAudioVideoMediaStream();
1179 caller()->CreateAndSetAndSignalOffer();
1180 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1181 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001182 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001183 EXPECT_EQ(
1184 1, caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1185 expected_cipher_suite));
1186 caller()->pc()->RegisterUMAObserver(nullptr);
1187 }
1188
1189 private:
1190 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001191 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001192 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001193 // |network_thread_| and |worker_thread_| are used by both
1194 // |caller_| and |callee_| so they must be destroyed
1195 // later.
1196 std::unique_ptr<rtc::Thread> network_thread_;
1197 std::unique_ptr<rtc::Thread> worker_thread_;
1198 std::unique_ptr<PeerConnectionWrapper> caller_;
1199 std::unique_ptr<PeerConnectionWrapper> callee_;
1200};
1201
1202// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1203// includes testing that the callback is invoked if an observer is connected
1204// after the first packet has already been received.
1205TEST_F(PeerConnectionIntegrationTest,
1206 RtpReceiverObserverOnFirstPacketReceived) {
1207 ASSERT_TRUE(CreatePeerConnectionWrappers());
1208 ConnectFakeSignaling();
1209 caller()->AddAudioVideoMediaStream();
1210 callee()->AddAudioVideoMediaStream();
1211 // Start offer/answer exchange and wait for it to complete.
1212 caller()->CreateAndSetAndSignalOffer();
1213 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1214 // Should be one receiver each for audio/video.
1215 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1216 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1217 // Wait for all "first packet received" callbacks to be fired.
1218 EXPECT_TRUE_WAIT(
1219 std::all_of(caller()->rtp_receiver_observers().begin(),
1220 caller()->rtp_receiver_observers().end(),
1221 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1222 return o->first_packet_received();
1223 }),
1224 kMaxWaitForFramesMs);
1225 EXPECT_TRUE_WAIT(
1226 std::all_of(callee()->rtp_receiver_observers().begin(),
1227 callee()->rtp_receiver_observers().end(),
1228 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1229 return o->first_packet_received();
1230 }),
1231 kMaxWaitForFramesMs);
1232 // If new observers are set after the first packet was already received, the
1233 // callback should still be invoked.
1234 caller()->ResetRtpReceiverObservers();
1235 callee()->ResetRtpReceiverObservers();
1236 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1237 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1238 EXPECT_TRUE(
1239 std::all_of(caller()->rtp_receiver_observers().begin(),
1240 caller()->rtp_receiver_observers().end(),
1241 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1242 return o->first_packet_received();
1243 }));
1244 EXPECT_TRUE(
1245 std::all_of(callee()->rtp_receiver_observers().begin(),
1246 callee()->rtp_receiver_observers().end(),
1247 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1248 return o->first_packet_received();
1249 }));
1250}
1251
1252class DummyDtmfObserver : public DtmfSenderObserverInterface {
1253 public:
1254 DummyDtmfObserver() : completed_(false) {}
1255
1256 // Implements DtmfSenderObserverInterface.
1257 void OnToneChange(const std::string& tone) override {
1258 tones_.push_back(tone);
1259 if (tone.empty()) {
1260 completed_ = true;
1261 }
1262 }
1263
1264 const std::vector<std::string>& tones() const { return tones_; }
1265 bool completed() const { return completed_; }
1266
1267 private:
1268 bool completed_;
1269 std::vector<std::string> tones_;
1270};
1271
1272// Assumes |sender| already has an audio track added and the offer/answer
1273// exchange is done.
1274void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1275 PeerConnectionWrapper* receiver) {
1276 DummyDtmfObserver observer;
1277 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender;
1278
1279 // We should be able to create a DTMF sender from a local track.
1280 webrtc::AudioTrackInterface* localtrack =
1281 sender->local_streams()->at(0)->GetAudioTracks()[0];
1282 dtmf_sender = sender->pc()->CreateDtmfSender(localtrack);
1283 ASSERT_NE(nullptr, dtmf_sender.get());
1284 dtmf_sender->RegisterObserver(&observer);
1285
1286 // Test the DtmfSender object just created.
1287 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1288 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1289
1290 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1291 std::vector<std::string> tones = {"1", "a", ""};
1292 EXPECT_EQ(tones, observer.tones());
1293 dtmf_sender->UnregisterObserver();
1294 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1295}
1296
1297// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1298// direction).
1299TEST_F(PeerConnectionIntegrationTest, DtmfSenderObserver) {
1300 ASSERT_TRUE(CreatePeerConnectionWrappers());
1301 ConnectFakeSignaling();
1302 // Only need audio for DTMF.
1303 caller()->AddAudioOnlyMediaStream();
1304 callee()->AddAudioOnlyMediaStream();
1305 caller()->CreateAndSetAndSignalOffer();
1306 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001307 // DTLS must finish before the DTMF sender can be used reliably.
1308 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001309 TestDtmfFromSenderToReceiver(caller(), callee());
1310 TestDtmfFromSenderToReceiver(callee(), caller());
1311}
1312
1313// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1314// between two connections, using DTLS-SRTP.
1315TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
1316 ASSERT_TRUE(CreatePeerConnectionWrappers());
1317 ConnectFakeSignaling();
1318 // Do normal offer/answer and wait for some frames to be received in each
1319 // direction.
1320 caller()->AddAudioVideoMediaStream();
1321 callee()->AddAudioVideoMediaStream();
1322 caller()->CreateAndSetAndSignalOffer();
1323 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1324 ExpectNewFramesReceivedWithWait(
1325 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1326 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1327 kMaxWaitForFramesMs);
1328}
1329
1330// Uses SDES instead of DTLS for key agreement.
1331TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
1332 PeerConnectionInterface::RTCConfiguration sdes_config;
1333 sdes_config.enable_dtls_srtp.emplace(false);
1334 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1335 ConnectFakeSignaling();
1336
1337 // Do normal offer/answer and wait for some frames to be received in each
1338 // direction.
1339 caller()->AddAudioVideoMediaStream();
1340 callee()->AddAudioVideoMediaStream();
1341 caller()->CreateAndSetAndSignalOffer();
1342 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1343 ExpectNewFramesReceivedWithWait(
1344 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1345 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1346 kMaxWaitForFramesMs);
1347}
1348
Steve Anton8c0f7a72017-10-03 10:03:10 -07001349// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1350// certificate once the DTLS handshake has finished.
1351TEST_F(PeerConnectionIntegrationTest,
1352 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1353 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1354 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1355 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1356 return pc->GetRemoteAudioSSLCertificate();
1357 };
1358
1359 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1360 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1361
1362 // Configure each side with a known certificate so they can be compared later.
1363 PeerConnectionInterface::RTCConfiguration caller_config;
1364 caller_config.enable_dtls_srtp.emplace(true);
1365 caller_config.certificates.push_back(caller_cert);
1366 PeerConnectionInterface::RTCConfiguration callee_config;
1367 callee_config.enable_dtls_srtp.emplace(true);
1368 callee_config.certificates.push_back(callee_cert);
1369 ASSERT_TRUE(
1370 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1371 ConnectFakeSignaling();
1372
1373 // When first initialized, there should not be a remote SSL certificate (and
1374 // calling this method should not crash).
1375 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1376 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
1377
1378 caller()->AddAudioOnlyMediaStream();
1379 callee()->AddAudioOnlyMediaStream();
1380 caller()->CreateAndSetAndSignalOffer();
1381 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1382 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1383
1384 // Once DTLS has been connected, each side should return the other's SSL
1385 // certificate when calling GetRemoteAudioSSLCertificate.
1386
1387 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1388 ASSERT_TRUE(caller_remote_cert);
1389 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1390 caller_remote_cert->ToPEMString());
1391
1392 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1393 ASSERT_TRUE(callee_remote_cert);
1394 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1395 callee_remote_cert->ToPEMString());
1396}
1397
deadbeef1dcb1642017-03-29 21:08:16 -07001398// This test sets up a call between two parties (using DTLS) and tests that we
1399// can get a video aspect ratio of 16:9.
1400TEST_F(PeerConnectionIntegrationTest, SendAndReceive16To9AspectRatio) {
1401 ASSERT_TRUE(CreatePeerConnectionWrappers());
1402 ConnectFakeSignaling();
1403
1404 // Add video tracks with 16:9 constraint.
1405 FakeConstraints constraints;
1406 double requested_ratio = 16.0 / 9;
1407 constraints.SetMandatoryMinAspectRatio(requested_ratio);
1408 caller()->AddMediaStreamFromTracks(
1409 nullptr, caller()->CreateLocalVideoTrackWithConstraints(constraints));
1410 callee()->AddMediaStreamFromTracks(
1411 nullptr, callee()->CreateLocalVideoTrackWithConstraints(constraints));
1412
1413 // Do normal offer/answer and wait for at least one frame to be received in
1414 // each direction.
1415 caller()->CreateAndSetAndSignalOffer();
1416 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1417 callee()->min_video_frames_received_per_track() > 0,
1418 kMaxWaitForFramesMs);
1419
1420 // Check rendered aspect ratio.
1421 EXPECT_EQ(requested_ratio, caller()->local_rendered_aspect_ratio());
1422 EXPECT_EQ(requested_ratio, caller()->rendered_aspect_ratio());
1423 EXPECT_EQ(requested_ratio, callee()->local_rendered_aspect_ratio());
1424 EXPECT_EQ(requested_ratio, callee()->rendered_aspect_ratio());
1425}
1426
1427// This test sets up a call between two parties with a source resolution of
1428// 1280x720 and verifies that a 16:9 aspect ratio is received.
1429TEST_F(PeerConnectionIntegrationTest,
1430 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1431 ASSERT_TRUE(CreatePeerConnectionWrappers());
1432 ConnectFakeSignaling();
1433
1434 // Similar to above test, but uses MandatoryMin[Width/Height] constraint
1435 // instead of aspect ratio constraint.
1436 FakeConstraints constraints;
1437 constraints.SetMandatoryMinWidth(1280);
1438 constraints.SetMandatoryMinHeight(720);
1439 caller()->AddMediaStreamFromTracks(
1440 nullptr, caller()->CreateLocalVideoTrackWithConstraints(constraints));
1441 callee()->AddMediaStreamFromTracks(
1442 nullptr, callee()->CreateLocalVideoTrackWithConstraints(constraints));
1443
1444 // Do normal offer/answer and wait for at least one frame to be received in
1445 // each direction.
1446 caller()->CreateAndSetAndSignalOffer();
1447 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1448 callee()->min_video_frames_received_per_track() > 0,
1449 kMaxWaitForFramesMs);
1450
1451 // Check rendered aspect ratio.
1452 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1453 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1454 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1455 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1456}
1457
1458// This test sets up an one-way call, with media only from caller to
1459// callee.
1460TEST_F(PeerConnectionIntegrationTest, OneWayMediaCall) {
1461 ASSERT_TRUE(CreatePeerConnectionWrappers());
1462 ConnectFakeSignaling();
1463 caller()->AddAudioVideoMediaStream();
1464 caller()->CreateAndSetAndSignalOffer();
1465 int caller_received_frames = 0;
1466 ExpectNewFramesReceivedWithWait(
1467 caller_received_frames, caller_received_frames,
1468 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1469 kMaxWaitForFramesMs);
1470}
1471
1472// This test sets up a audio call initially, with the callee rejecting video
1473// initially. Then later the callee decides to upgrade to audio/video, and
1474// initiates a new offer/answer exchange.
1475TEST_F(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
1476 ASSERT_TRUE(CreatePeerConnectionWrappers());
1477 ConnectFakeSignaling();
1478 // Initially, offer an audio/video stream from the caller, but refuse to
1479 // send/receive video on the callee side.
1480 caller()->AddAudioVideoMediaStream();
deadbeef4389b4d2017-09-07 09:07:36 -07001481 callee()->AddAudioOnlyMediaStream();
deadbeef1dcb1642017-03-29 21:08:16 -07001482 PeerConnectionInterface::RTCOfferAnswerOptions options;
1483 options.offer_to_receive_video = 0;
1484 callee()->SetOfferAnswerOptions(options);
1485 // Do offer/answer and make sure audio is still received end-to-end.
1486 caller()->CreateAndSetAndSignalOffer();
1487 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1488 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1489 kDefaultExpectedAudioFrameCount, 0,
1490 kMaxWaitForFramesMs);
1491 // Sanity check that the callee's description has a rejected video section.
1492 ASSERT_NE(nullptr, callee()->pc()->local_description());
1493 const ContentInfo* callee_video_content =
1494 GetFirstVideoContent(callee()->pc()->local_description()->description());
1495 ASSERT_NE(nullptr, callee_video_content);
1496 EXPECT_TRUE(callee_video_content->rejected);
1497 // Now negotiate with video and ensure negotiation succeeds, with video
1498 // frames and additional audio frames being received.
deadbeefb1a15d72017-09-07 14:12:05 -07001499 callee()->AddVideoOnlyMediaStream();
deadbeef1dcb1642017-03-29 21:08:16 -07001500 options.offer_to_receive_video = 1;
1501 callee()->SetOfferAnswerOptions(options);
1502 callee()->CreateAndSetAndSignalOffer();
1503 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1504 // Expect additional audio frames to be received after the upgrade.
1505 ExpectNewFramesReceivedWithWait(
1506 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1507 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1508 kMaxWaitForFramesMs);
1509}
1510
deadbeef4389b4d2017-09-07 09:07:36 -07001511// Simpler than the above test; just add an audio track to an established
1512// video-only connection.
1513TEST_F(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
1514 ASSERT_TRUE(CreatePeerConnectionWrappers());
1515 ConnectFakeSignaling();
1516 // Do initial offer/answer with just a video track.
1517 caller()->AddVideoOnlyMediaStream();
1518 callee()->AddVideoOnlyMediaStream();
1519 caller()->CreateAndSetAndSignalOffer();
1520 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1521 // Now add an audio track and do another offer/answer.
deadbeefb1a15d72017-09-07 14:12:05 -07001522 caller()->AddAudioOnlyMediaStream();
1523 callee()->AddAudioOnlyMediaStream();
deadbeef4389b4d2017-09-07 09:07:36 -07001524 caller()->CreateAndSetAndSignalOffer();
1525 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1526 // Ensure both audio and video frames are received end-to-end.
1527 ExpectNewFramesReceivedWithWait(
1528 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1529 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1530 kMaxWaitForFramesMs);
1531}
1532
deadbeef1dcb1642017-03-29 21:08:16 -07001533// This test sets up a call that's transferred to a new caller with a different
1534// DTLS fingerprint.
1535TEST_F(PeerConnectionIntegrationTest, CallTransferredForCallee) {
1536 ASSERT_TRUE(CreatePeerConnectionWrappers());
1537 ConnectFakeSignaling();
1538 caller()->AddAudioVideoMediaStream();
1539 callee()->AddAudioVideoMediaStream();
1540 caller()->CreateAndSetAndSignalOffer();
1541 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1542
1543 // Keep the original peer around which will still send packets to the
1544 // receiving client. These SRTP packets will be dropped.
1545 std::unique_ptr<PeerConnectionWrapper> original_peer(
1546 SetCallerPcWrapperAndReturnCurrent(
1547 CreatePeerConnectionWrapperWithAlternateKey()));
1548 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1549 // directly above.
1550 original_peer->pc()->Close();
1551
1552 ConnectFakeSignaling();
1553 caller()->AddAudioVideoMediaStream();
1554 caller()->CreateAndSetAndSignalOffer();
1555 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1556 // Wait for some additional frames to be transmitted end-to-end.
1557 ExpectNewFramesReceivedWithWait(
1558 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1559 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1560 kMaxWaitForFramesMs);
1561}
1562
1563// This test sets up a call that's transferred to a new callee with a different
1564// DTLS fingerprint.
1565TEST_F(PeerConnectionIntegrationTest, CallTransferredForCaller) {
1566 ASSERT_TRUE(CreatePeerConnectionWrappers());
1567 ConnectFakeSignaling();
1568 caller()->AddAudioVideoMediaStream();
1569 callee()->AddAudioVideoMediaStream();
1570 caller()->CreateAndSetAndSignalOffer();
1571 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1572
1573 // Keep the original peer around which will still send packets to the
1574 // receiving client. These SRTP packets will be dropped.
1575 std::unique_ptr<PeerConnectionWrapper> original_peer(
1576 SetCalleePcWrapperAndReturnCurrent(
1577 CreatePeerConnectionWrapperWithAlternateKey()));
1578 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1579 // directly above.
1580 original_peer->pc()->Close();
1581
1582 ConnectFakeSignaling();
1583 callee()->AddAudioVideoMediaStream();
1584 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1585 caller()->CreateAndSetAndSignalOffer();
1586 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1587 // Wait for some additional frames to be transmitted end-to-end.
1588 ExpectNewFramesReceivedWithWait(
1589 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1590 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1591 kMaxWaitForFramesMs);
1592}
1593
1594// This test sets up a non-bundled call and negotiates bundling at the same
1595// time as starting an ICE restart. When bundling is in effect in the restart,
1596// the DTLS-SRTP context should be successfully reset.
1597TEST_F(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
1598 ASSERT_TRUE(CreatePeerConnectionWrappers());
1599 ConnectFakeSignaling();
1600
1601 caller()->AddAudioVideoMediaStream();
1602 callee()->AddAudioVideoMediaStream();
1603 // Remove the bundle group from the SDP received by the callee.
1604 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1605 desc->RemoveGroupByName("BUNDLE");
1606 });
1607 caller()->CreateAndSetAndSignalOffer();
1608 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1609 ExpectNewFramesReceivedWithWait(
1610 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1611 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1612 kMaxWaitForFramesMs);
1613
1614 // Now stop removing the BUNDLE group, and trigger an ICE restart.
1615 callee()->SetReceivedSdpMunger(nullptr);
1616 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1617 caller()->CreateAndSetAndSignalOffer();
1618 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1619
1620 // Expect additional frames to be received after the ICE restart.
1621 ExpectNewFramesReceivedWithWait(
1622 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1623 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1624 kMaxWaitForFramesMs);
1625}
1626
1627// Test CVO (Coordination of Video Orientation). If a video source is rotated
1628// and both peers support the CVO RTP header extension, the actual video frames
1629// don't need to be encoded in different resolutions, since the rotation is
1630// communicated through the RTP header extension.
1631TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
1632 ASSERT_TRUE(CreatePeerConnectionWrappers());
1633 ConnectFakeSignaling();
1634 // Add rotated video tracks.
1635 caller()->AddMediaStreamFromTracks(
1636 nullptr,
1637 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
1638 callee()->AddMediaStreamFromTracks(
1639 nullptr,
1640 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1641
1642 // Wait for video frames to be received by both sides.
1643 caller()->CreateAndSetAndSignalOffer();
1644 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1645 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1646 callee()->min_video_frames_received_per_track() > 0,
1647 kMaxWaitForFramesMs);
1648
1649 // Ensure that the aspect ratio is unmodified.
1650 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1651 // not just assumed.
1652 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
1653 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
1654 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
1655 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
1656 // Ensure that the CVO bits were surfaced to the renderer.
1657 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
1658 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
1659}
1660
1661// Test that when the CVO extension isn't supported, video is rotated the
1662// old-fashioned way, by encoding rotated frames.
1663TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
1664 ASSERT_TRUE(CreatePeerConnectionWrappers());
1665 ConnectFakeSignaling();
1666 // Add rotated video tracks.
1667 caller()->AddMediaStreamFromTracks(
1668 nullptr,
1669 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
1670 callee()->AddMediaStreamFromTracks(
1671 nullptr,
1672 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1673
1674 // Remove the CVO extension from the offered SDP.
1675 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1676 cricket::VideoContentDescription* video =
1677 GetFirstVideoContentDescription(desc);
1678 video->ClearRtpHeaderExtensions();
1679 });
1680 // Wait for video frames to be received by both sides.
1681 caller()->CreateAndSetAndSignalOffer();
1682 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1683 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1684 callee()->min_video_frames_received_per_track() > 0,
1685 kMaxWaitForFramesMs);
1686
1687 // Expect that the aspect ratio is inversed to account for the 90/270 degree
1688 // rotation.
1689 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1690 // not just assumed.
1691 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
1692 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
1693 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
1694 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
1695 // Expect that each endpoint is unaware of the rotation of the other endpoint.
1696 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
1697 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
1698}
1699
1700// TODO(deadbeef): The tests below rely on RTCOfferAnswerOptions to reject an
1701// m= section. When we implement Unified Plan SDP, the right way to do this
1702// would be by stopping an RtpTransceiver.
1703
1704// Test that if the answerer rejects the audio m= section, no audio is sent or
1705// received, but video still can be.
1706TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
1707 ASSERT_TRUE(CreatePeerConnectionWrappers());
1708 ConnectFakeSignaling();
1709 caller()->AddAudioVideoMediaStream();
1710 // Only add video track for callee, and set offer_to_receive_audio to 0, so
1711 // it will reject the audio m= section completely.
1712 PeerConnectionInterface::RTCOfferAnswerOptions options;
1713 options.offer_to_receive_audio = 0;
1714 callee()->SetOfferAnswerOptions(options);
1715 callee()->AddMediaStreamFromTracks(nullptr,
1716 callee()->CreateLocalVideoTrack());
1717 // Do offer/answer and wait for successful end-to-end video frames.
1718 caller()->CreateAndSetAndSignalOffer();
1719 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1720 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount, 0,
1721 kDefaultExpectedVideoFrameCount,
1722 kMaxWaitForFramesMs);
1723 // Shouldn't have received audio frames at any point.
1724 EXPECT_EQ(0, caller()->audio_frames_received());
1725 EXPECT_EQ(0, callee()->audio_frames_received());
1726 // Sanity check that the callee's description has a rejected audio section.
1727 ASSERT_NE(nullptr, callee()->pc()->local_description());
1728 const ContentInfo* callee_audio_content =
1729 GetFirstAudioContent(callee()->pc()->local_description()->description());
1730 ASSERT_NE(nullptr, callee_audio_content);
1731 EXPECT_TRUE(callee_audio_content->rejected);
1732}
1733
1734// Test that if the answerer rejects the video m= section, no video is sent or
1735// received, but audio still can be.
1736TEST_F(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
1737 ASSERT_TRUE(CreatePeerConnectionWrappers());
1738 ConnectFakeSignaling();
1739 caller()->AddAudioVideoMediaStream();
1740 // Only add audio track for callee, and set offer_to_receive_video to 0, so
1741 // it will reject the video m= section completely.
1742 PeerConnectionInterface::RTCOfferAnswerOptions options;
1743 options.offer_to_receive_video = 0;
1744 callee()->SetOfferAnswerOptions(options);
1745 callee()->AddMediaStreamFromTracks(callee()->CreateLocalAudioTrack(),
1746 nullptr);
1747 // Do offer/answer and wait for successful end-to-end audio frames.
1748 caller()->CreateAndSetAndSignalOffer();
1749 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1750 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1751 kDefaultExpectedAudioFrameCount, 0,
1752 kMaxWaitForFramesMs);
1753 // Shouldn't have received video frames at any point.
1754 EXPECT_EQ(0, caller()->total_video_frames_received());
1755 EXPECT_EQ(0, callee()->total_video_frames_received());
1756 // Sanity check that the callee's description has a rejected video section.
1757 ASSERT_NE(nullptr, callee()->pc()->local_description());
1758 const ContentInfo* callee_video_content =
1759 GetFirstVideoContent(callee()->pc()->local_description()->description());
1760 ASSERT_NE(nullptr, callee_video_content);
1761 EXPECT_TRUE(callee_video_content->rejected);
1762}
1763
1764// Test that if the answerer rejects both audio and video m= sections, nothing
1765// bad happens.
1766// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
1767// test anything but the fact that negotiation succeeds, which doesn't mean
1768// much.
1769TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
1770 ASSERT_TRUE(CreatePeerConnectionWrappers());
1771 ConnectFakeSignaling();
1772 caller()->AddAudioVideoMediaStream();
1773 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
1774 // will reject both audio and video m= sections.
1775 PeerConnectionInterface::RTCOfferAnswerOptions options;
1776 options.offer_to_receive_audio = 0;
1777 options.offer_to_receive_video = 0;
1778 callee()->SetOfferAnswerOptions(options);
1779 // Do offer/answer and wait for stable signaling state.
1780 caller()->CreateAndSetAndSignalOffer();
1781 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1782 // Sanity check that the callee's description has rejected m= sections.
1783 ASSERT_NE(nullptr, callee()->pc()->local_description());
1784 const ContentInfo* callee_audio_content =
1785 GetFirstAudioContent(callee()->pc()->local_description()->description());
1786 ASSERT_NE(nullptr, callee_audio_content);
1787 EXPECT_TRUE(callee_audio_content->rejected);
1788 const ContentInfo* callee_video_content =
1789 GetFirstVideoContent(callee()->pc()->local_description()->description());
1790 ASSERT_NE(nullptr, callee_video_content);
1791 EXPECT_TRUE(callee_video_content->rejected);
1792}
1793
1794// This test sets up an audio and video call between two parties. After the
1795// call runs for a while, the caller sends an updated offer with video being
1796// rejected. Once the re-negotiation is done, the video flow should stop and
1797// the audio flow should continue.
1798TEST_F(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
1799 ASSERT_TRUE(CreatePeerConnectionWrappers());
1800 ConnectFakeSignaling();
1801 caller()->AddAudioVideoMediaStream();
1802 callee()->AddAudioVideoMediaStream();
1803 caller()->CreateAndSetAndSignalOffer();
1804 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1805 ExpectNewFramesReceivedWithWait(
1806 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1807 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1808 kMaxWaitForFramesMs);
1809
1810 // Renegotiate, rejecting the video m= section.
1811 // TODO(deadbeef): When an RtpTransceiver API is available, use that to
1812 // reject the video m= section.
1813 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
1814 for (cricket::ContentInfo& content : description->contents()) {
1815 if (cricket::IsVideoContent(&content)) {
1816 content.rejected = true;
1817 }
1818 }
1819 });
1820 caller()->CreateAndSetAndSignalOffer();
1821 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
1822
1823 // Sanity check that the caller's description has a rejected video section.
1824 ASSERT_NE(nullptr, caller()->pc()->local_description());
1825 const ContentInfo* caller_video_content =
1826 GetFirstVideoContent(caller()->pc()->local_description()->description());
1827 ASSERT_NE(nullptr, caller_video_content);
1828 EXPECT_TRUE(caller_video_content->rejected);
1829
1830 int caller_video_received = caller()->total_video_frames_received();
1831 int callee_video_received = callee()->total_video_frames_received();
1832
1833 // Wait for some additional audio frames to be received.
1834 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1835 kDefaultExpectedAudioFrameCount, 0,
1836 kMaxWaitForFramesMs);
1837
1838 // During this time, we shouldn't have received any additional video frames
1839 // for the rejected video tracks.
1840 EXPECT_EQ(caller_video_received, caller()->total_video_frames_received());
1841 EXPECT_EQ(callee_video_received, callee()->total_video_frames_received());
1842}
1843
1844// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
1845// is needed to support legacy endpoints.
1846// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
1847// add a test for an end-to-end test without MID signaling either (basically,
1848// the minimum acceptable SDP).
1849TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
1850 ASSERT_TRUE(CreatePeerConnectionWrappers());
1851 ConnectFakeSignaling();
1852 // Add audio and video, testing that packets can be demuxed on payload type.
1853 caller()->AddAudioVideoMediaStream();
1854 callee()->AddAudioVideoMediaStream();
deadbeefd8ad7882017-04-18 16:01:17 -07001855 // Remove SSRCs and MSIDs from the received offer SDP.
1856 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07001857 caller()->CreateAndSetAndSignalOffer();
1858 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1859 ExpectNewFramesReceivedWithWait(
1860 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1861 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1862 kMaxWaitForFramesMs);
1863}
1864
1865// Test that if two video tracks are sent (from caller to callee, in this test),
1866// they're transmitted correctly end-to-end.
1867TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
1868 ASSERT_TRUE(CreatePeerConnectionWrappers());
1869 ConnectFakeSignaling();
1870 // Add one audio/video stream, and one video-only stream.
1871 caller()->AddAudioVideoMediaStream();
deadbeefb1a15d72017-09-07 14:12:05 -07001872 caller()->AddVideoOnlyMediaStream();
deadbeef1dcb1642017-03-29 21:08:16 -07001873 caller()->CreateAndSetAndSignalOffer();
1874 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1875 ASSERT_EQ(2u, callee()->number_of_remote_streams());
1876 int expected_callee_received_frames = kDefaultExpectedVideoFrameCount;
1877 ExpectNewFramesReceivedWithWait(0, 0, 0, expected_callee_received_frames,
1878 kMaxWaitForFramesMs);
1879}
1880
1881static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
1882 bool first = true;
1883 for (cricket::ContentInfo& content : desc->contents()) {
1884 if (first) {
1885 first = false;
1886 continue;
1887 }
1888 content.bundle_only = true;
1889 }
1890 first = true;
1891 for (cricket::TransportInfo& transport : desc->transport_infos()) {
1892 if (first) {
1893 first = false;
1894 continue;
1895 }
1896 transport.description.ice_ufrag.clear();
1897 transport.description.ice_pwd.clear();
1898 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
1899 transport.description.identity_fingerprint.reset(nullptr);
1900 }
1901}
1902
1903// Test that if applying a true "max bundle" offer, which uses ports of 0,
1904// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
1905// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
1906// successfully and media flows.
1907// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
1908// TODO(deadbeef): Won't need this test once we start generating actual
1909// standards-compliant SDP.
1910TEST_F(PeerConnectionIntegrationTest,
1911 EndToEndCallWithSpecCompliantMaxBundleOffer) {
1912 ASSERT_TRUE(CreatePeerConnectionWrappers());
1913 ConnectFakeSignaling();
1914 caller()->AddAudioVideoMediaStream();
1915 callee()->AddAudioVideoMediaStream();
1916 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
1917 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
1918 // but the first m= section.
1919 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
1920 caller()->CreateAndSetAndSignalOffer();
1921 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1922 ExpectNewFramesReceivedWithWait(
1923 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1924 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1925 kMaxWaitForFramesMs);
1926}
1927
1928// Test that we can receive the audio output level from a remote audio track.
1929// TODO(deadbeef): Use a fake audio source and verify that the output level is
1930// exactly what the source on the other side was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001931TEST_F(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001932 ASSERT_TRUE(CreatePeerConnectionWrappers());
1933 ConnectFakeSignaling();
1934 // Just add an audio track.
1935 caller()->AddMediaStreamFromTracks(caller()->CreateLocalAudioTrack(),
1936 nullptr);
1937 caller()->CreateAndSetAndSignalOffer();
1938 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1939
1940 // Get the audio output level stats. Note that the level is not available
1941 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07001942 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001943 kMaxWaitForFramesMs);
1944}
1945
1946// Test that an audio input level is reported.
1947// TODO(deadbeef): Use a fake audio source and verify that the input level is
1948// exactly what the source was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001949TEST_F(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001950 ASSERT_TRUE(CreatePeerConnectionWrappers());
1951 ConnectFakeSignaling();
1952 // Just add an audio track.
1953 caller()->AddMediaStreamFromTracks(caller()->CreateLocalAudioTrack(),
1954 nullptr);
1955 caller()->CreateAndSetAndSignalOffer();
1956 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1957
1958 // Get the audio input level stats. The level should be available very
1959 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07001960 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001961 kMaxWaitForStatsMs);
1962}
1963
1964// Test that we can get incoming byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001965TEST_F(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001966 ASSERT_TRUE(CreatePeerConnectionWrappers());
1967 ConnectFakeSignaling();
1968 caller()->AddAudioVideoMediaStream();
1969 // Do offer/answer, wait for the callee to receive some frames.
1970 caller()->CreateAndSetAndSignalOffer();
1971 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1972 int expected_caller_received_frames = 0;
1973 ExpectNewFramesReceivedWithWait(
1974 expected_caller_received_frames, expected_caller_received_frames,
1975 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1976 kMaxWaitForFramesMs);
1977
1978 // Get a handle to the remote tracks created, so they can be used as GetStats
1979 // filters.
1980 StreamCollectionInterface* remote_streams = callee()->remote_streams();
1981 ASSERT_EQ(1u, remote_streams->count());
1982 ASSERT_EQ(1u, remote_streams->at(0)->GetAudioTracks().size());
1983 ASSERT_EQ(1u, remote_streams->at(0)->GetVideoTracks().size());
1984 MediaStreamTrackInterface* remote_audio_track =
1985 remote_streams->at(0)->GetAudioTracks()[0];
1986 MediaStreamTrackInterface* remote_video_track =
1987 remote_streams->at(0)->GetVideoTracks()[0];
1988
1989 // We received frames, so we definitely should have nonzero "received bytes"
1990 // stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07001991 EXPECT_GT(callee()->OldGetStatsForTrack(remote_audio_track)->BytesReceived(),
1992 0);
1993 EXPECT_GT(callee()->OldGetStatsForTrack(remote_video_track)->BytesReceived(),
1994 0);
deadbeef1dcb1642017-03-29 21:08:16 -07001995}
1996
1997// Test that we can get outgoing byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001998TEST_F(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001999 ASSERT_TRUE(CreatePeerConnectionWrappers());
2000 ConnectFakeSignaling();
2001 auto audio_track = caller()->CreateLocalAudioTrack();
2002 auto video_track = caller()->CreateLocalVideoTrack();
2003 caller()->AddMediaStreamFromTracks(audio_track, video_track);
2004 // Do offer/answer, wait for the callee to receive some frames.
2005 caller()->CreateAndSetAndSignalOffer();
2006 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2007 int expected_caller_received_frames = 0;
2008 ExpectNewFramesReceivedWithWait(
2009 expected_caller_received_frames, expected_caller_received_frames,
2010 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2011 kMaxWaitForFramesMs);
2012
2013 // The callee received frames, so we definitely should have nonzero "sent
2014 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002015 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2016 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2017}
2018
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002019// Test that we can get capture start ntp time.
2020TEST_F(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
2021 ASSERT_TRUE(CreatePeerConnectionWrappers());
2022 ConnectFakeSignaling();
2023 caller()->AddAudioOnlyMediaStream();
2024
2025 auto audio_track = callee()->CreateLocalAudioTrack();
2026 callee()->AddMediaStreamFromTracks(audio_track, nullptr);
2027
2028 // Do offer/answer, wait for the callee to receive some frames.
2029 caller()->CreateAndSetAndSignalOffer();
2030 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2031
2032 // Get the remote audio track created on the receiver, so they can be used as
2033 // GetStats filters.
2034 StreamCollectionInterface* remote_streams = callee()->remote_streams();
2035 ASSERT_EQ(1u, remote_streams->count());
2036 ASSERT_EQ(1u, remote_streams->at(0)->GetAudioTracks().size());
2037 MediaStreamTrackInterface* remote_audio_track =
2038 remote_streams->at(0)->GetAudioTracks()[0];
2039
2040 // Get the audio output level stats. Note that the level is not available
2041 // until an RTCP packet has been received.
2042 EXPECT_TRUE_WAIT(callee()->OldGetStatsForTrack(remote_audio_track)->
2043 CaptureStartNtpTime() > 0, 2 * kMaxWaitForFramesMs);
2044}
2045
deadbeefd8ad7882017-04-18 16:01:17 -07002046// Test that we can get stats (using the new stats implemnetation) for
2047// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2048// SDP.
2049TEST_F(PeerConnectionIntegrationTest,
2050 GetStatsForUnsignaledStreamWithNewStatsApi) {
2051 ASSERT_TRUE(CreatePeerConnectionWrappers());
2052 ConnectFakeSignaling();
2053 caller()->AddAudioOnlyMediaStream();
2054 // Remove SSRCs and MSIDs from the received offer SDP.
2055 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2056 caller()->CreateAndSetAndSignalOffer();
2057 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2058 // Wait for one audio frame to be received by the callee.
2059 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
2060
2061 // We received a frame, so we should have nonzero "bytes received" stats for
2062 // the unsignaled stream, if stats are working for it.
2063 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2064 callee()->NewGetStats();
2065 ASSERT_NE(nullptr, report);
2066 auto inbound_stream_stats =
2067 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2068 ASSERT_EQ(1U, inbound_stream_stats.size());
2069 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2070 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002071 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2072}
2073
2074// Test that we can successfully get the media related stats (audio level
2075// etc.) for the unsignaled stream.
2076TEST_F(PeerConnectionIntegrationTest,
2077 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2078 ASSERT_TRUE(CreatePeerConnectionWrappers());
2079 ConnectFakeSignaling();
2080 caller()->AddAudioVideoMediaStream();
2081 // Remove SSRCs and MSIDs from the received offer SDP.
2082 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2083 caller()->CreateAndSetAndSignalOffer();
2084 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2085 // Wait for one audio frame to be received by the callee.
2086 ExpectNewFramesReceivedWithWait(0, 0, 1, 1, kMaxWaitForFramesMs);
2087
2088 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2089 callee()->NewGetStats();
2090 ASSERT_NE(nullptr, report);
2091
2092 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2093 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2094 ASSERT_GE(audio_index, 0);
2095 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002096}
2097
deadbeef4e2deab2017-09-20 13:56:21 -07002098// Helper for test below.
2099void ModifySsrcs(cricket::SessionDescription* desc) {
2100 for (ContentInfo& content : desc->contents()) {
2101 MediaContentDescription* media_desc =
2102 static_cast<MediaContentDescription*>(content.description);
2103 for (cricket::StreamParams& stream : media_desc->mutable_streams()) {
2104 for (uint32_t& ssrc : stream.ssrcs) {
2105 ssrc = rtc::CreateRandomId();
2106 }
2107 }
2108 }
2109}
2110
2111// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2112// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2113// This should result in two "RTCInboundRTPStreamStats", but only one
2114// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2115// being reset to 0 once the SSRC change occurs.
2116//
2117// Regression test for this bug:
2118// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2119//
2120// The bug causes the track stats to only represent one of the two streams:
2121// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2122// that the track stat counters would reset to 0 when the new stream is
2123// received, and a 50% chance that they'll stop updating (while
2124// "concealed_samples" continues increasing, due to silence being generated for
2125// the inactive stream).
2126TEST_F(PeerConnectionIntegrationTest,
2127 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
2128 ASSERT_TRUE(CreatePeerConnectionWrappers());
2129 ConnectFakeSignaling();
2130 caller()->AddAudioOnlyMediaStream();
2131 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2132 // that doesn't signal SSRCs (from the callee's perspective).
2133 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2134 caller()->CreateAndSetAndSignalOffer();
2135 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2136 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
2137 ExpectNewFramesReceivedWithWait(0, 0, 25, 0, kMaxWaitForFramesMs);
2138
2139 // Some audio frames were received, so we should have nonzero "samples
2140 // received" for the track.
2141 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2142 callee()->NewGetStats();
2143 ASSERT_NE(nullptr, report);
2144 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2145 ASSERT_EQ(1U, track_stats.size());
2146 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2147 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2148 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2149
2150 // Create a new offer and munge it to cause the caller to use a new SSRC.
2151 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2152 caller()->CreateAndSetAndSignalOffer();
2153 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2154 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2155 // SSRC.
2156 ExpectNewFramesReceivedWithWait(0, 0, 25, 0, kMaxWaitForFramesMs);
2157
2158 report = callee()->NewGetStats();
2159 ASSERT_NE(nullptr, report);
2160 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2161 ASSERT_EQ(1U, track_stats.size());
2162 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2163 // The "total samples received" stat should only be greater than it was
2164 // before.
2165 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2166 // Right now, the new SSRC will cause the counters to reset to 0.
2167 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2168
2169 // Additionally, the percentage of concealed samples (samples generated to
2170 // conceal packet loss) should be less than 25%%. If it's greater, that's a
2171 // good sign that we're seeing stats from the old stream that's no longer
2172 // receiving packets, and is generating concealed samples of silence.
2173 constexpr double kAcceptableConcealedSamplesPercentage = 0.25;
2174 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2175 EXPECT_LT(*track_stats[0]->concealed_samples,
2176 *track_stats[0]->total_samples_received *
2177 kAcceptableConcealedSamplesPercentage);
2178
2179 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2180 // sanity check that the SSRC really changed.
2181 // TODO(deadbeef): This isn't working right now, because we're not returning
2182 // *any* stats for the inactive stream. Uncomment when the bug is completely
2183 // fixed.
2184 // auto inbound_stream_stats =
2185 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2186 // ASSERT_EQ(2U, inbound_stream_stats.size());
2187}
2188
deadbeef1dcb1642017-03-29 21:08:16 -07002189// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
2190TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
2191 PeerConnectionFactory::Options dtls_10_options;
2192 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2193 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2194 dtls_10_options));
2195 ConnectFakeSignaling();
2196 // Do normal offer/answer and wait for some frames to be received in each
2197 // direction.
2198 caller()->AddAudioVideoMediaStream();
2199 callee()->AddAudioVideoMediaStream();
2200 caller()->CreateAndSetAndSignalOffer();
2201 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2202 ExpectNewFramesReceivedWithWait(
2203 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2204 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2205 kMaxWaitForFramesMs);
2206}
2207
2208// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
2209TEST_F(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
2210 PeerConnectionFactory::Options dtls_10_options;
2211 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2212 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2213 dtls_10_options));
2214 ConnectFakeSignaling();
2215 // Register UMA observer before signaling begins.
2216 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
2217 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2218 caller()->pc()->RegisterUMAObserver(caller_observer);
2219 caller()->AddAudioVideoMediaStream();
2220 callee()->AddAudioVideoMediaStream();
2221 caller()->CreateAndSetAndSignalOffer();
2222 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2223 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002224 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002225 kDefaultTimeout);
2226 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002227 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002228 EXPECT_EQ(1,
2229 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2230 kDefaultSrtpCryptoSuite));
2231}
2232
2233// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
2234TEST_F(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
2235 PeerConnectionFactory::Options dtls_12_options;
2236 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2237 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2238 dtls_12_options));
2239 ConnectFakeSignaling();
2240 // Register UMA observer before signaling begins.
2241 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
2242 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2243 caller()->pc()->RegisterUMAObserver(caller_observer);
2244 caller()->AddAudioVideoMediaStream();
2245 callee()->AddAudioVideoMediaStream();
2246 caller()->CreateAndSetAndSignalOffer();
2247 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2248 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002249 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002250 kDefaultTimeout);
2251 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002252 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002253 EXPECT_EQ(1,
2254 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2255 kDefaultSrtpCryptoSuite));
2256}
2257
2258// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2259// callee only supports 1.0.
2260TEST_F(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
2261 PeerConnectionFactory::Options caller_options;
2262 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2263 PeerConnectionFactory::Options callee_options;
2264 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2265 ASSERT_TRUE(
2266 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2267 ConnectFakeSignaling();
2268 // Do normal offer/answer and wait for some frames to be received in each
2269 // direction.
2270 caller()->AddAudioVideoMediaStream();
2271 callee()->AddAudioVideoMediaStream();
2272 caller()->CreateAndSetAndSignalOffer();
2273 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2274 ExpectNewFramesReceivedWithWait(
2275 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2276 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2277 kMaxWaitForFramesMs);
2278}
2279
2280// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2281// callee supports 1.2.
2282TEST_F(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
2283 PeerConnectionFactory::Options caller_options;
2284 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2285 PeerConnectionFactory::Options callee_options;
2286 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2287 ASSERT_TRUE(
2288 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2289 ConnectFakeSignaling();
2290 // Do normal offer/answer and wait for some frames to be received in each
2291 // direction.
2292 caller()->AddAudioVideoMediaStream();
2293 callee()->AddAudioVideoMediaStream();
2294 caller()->CreateAndSetAndSignalOffer();
2295 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2296 ExpectNewFramesReceivedWithWait(
2297 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2298 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2299 kMaxWaitForFramesMs);
2300}
2301
2302// Test that a non-GCM cipher is used if both sides only support non-GCM.
2303TEST_F(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
2304 bool local_gcm_enabled = false;
2305 bool remote_gcm_enabled = false;
2306 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2307 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2308 expected_cipher_suite);
2309}
2310
2311// Test that a GCM cipher is used if both ends support it.
2312TEST_F(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
2313 bool local_gcm_enabled = true;
2314 bool remote_gcm_enabled = true;
2315 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2316 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2317 expected_cipher_suite);
2318}
2319
2320// Test that GCM isn't used if only the offerer supports it.
2321TEST_F(PeerConnectionIntegrationTest,
2322 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2323 bool local_gcm_enabled = true;
2324 bool remote_gcm_enabled = false;
2325 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2326 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2327 expected_cipher_suite);
2328}
2329
2330// Test that GCM isn't used if only the answerer supports it.
2331TEST_F(PeerConnectionIntegrationTest,
2332 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2333 bool local_gcm_enabled = false;
2334 bool remote_gcm_enabled = true;
2335 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2336 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2337 expected_cipher_suite);
2338}
2339
deadbeef7914b8c2017-04-21 03:23:33 -07002340// Verify that media can be transmitted end-to-end when GCM crypto suites are
2341// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
2342// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
2343// works with it.
2344TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
2345 PeerConnectionFactory::Options gcm_options;
2346 gcm_options.crypto_options.enable_gcm_crypto_suites = true;
2347 ASSERT_TRUE(
2348 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
2349 ConnectFakeSignaling();
2350 // Do normal offer/answer and wait for some frames to be received in each
2351 // direction.
2352 caller()->AddAudioVideoMediaStream();
2353 callee()->AddAudioVideoMediaStream();
2354 caller()->CreateAndSetAndSignalOffer();
2355 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2356 ExpectNewFramesReceivedWithWait(
2357 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2358 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2359 kMaxWaitForFramesMs);
2360}
2361
deadbeef1dcb1642017-03-29 21:08:16 -07002362// This test sets up a call between two parties with audio, video and an RTP
2363// data channel.
2364TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
2365 FakeConstraints setup_constraints;
2366 setup_constraints.SetAllowRtpDataChannels();
2367 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2368 &setup_constraints));
2369 ConnectFakeSignaling();
2370 // Expect that data channel created on caller side will show up for callee as
2371 // well.
2372 caller()->CreateDataChannel();
2373 caller()->AddAudioVideoMediaStream();
2374 callee()->AddAudioVideoMediaStream();
2375 caller()->CreateAndSetAndSignalOffer();
2376 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2377 // Ensure the existence of the RTP data channel didn't impede audio/video.
2378 ExpectNewFramesReceivedWithWait(
2379 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2380 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2381 kMaxWaitForFramesMs);
2382 ASSERT_NE(nullptr, caller()->data_channel());
2383 ASSERT_NE(nullptr, callee()->data_channel());
2384 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2385 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2386
2387 // Ensure data can be sent in both directions.
2388 std::string data = "hello world";
2389 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2390 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2391 kDefaultTimeout);
2392 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2393 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2394 kDefaultTimeout);
2395}
2396
2397// Ensure that an RTP data channel is signaled as closed for the caller when
2398// the callee rejects it in a subsequent offer.
2399TEST_F(PeerConnectionIntegrationTest,
2400 RtpDataChannelSignaledClosedInCalleeOffer) {
2401 // Same procedure as above test.
2402 FakeConstraints setup_constraints;
2403 setup_constraints.SetAllowRtpDataChannels();
2404 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2405 &setup_constraints));
2406 ConnectFakeSignaling();
2407 caller()->CreateDataChannel();
2408 caller()->AddAudioVideoMediaStream();
2409 callee()->AddAudioVideoMediaStream();
2410 caller()->CreateAndSetAndSignalOffer();
2411 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2412 ASSERT_NE(nullptr, caller()->data_channel());
2413 ASSERT_NE(nullptr, callee()->data_channel());
2414 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2415 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2416
2417 // Close the data channel on the callee, and do an updated offer/answer.
2418 callee()->data_channel()->Close();
2419 callee()->CreateAndSetAndSignalOffer();
2420 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2421 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2422 EXPECT_FALSE(callee()->data_observer()->IsOpen());
2423}
2424
2425// Tests that data is buffered in an RTP data channel until an observer is
2426// registered for it.
2427//
2428// NOTE: RTP data channels can receive data before the underlying
2429// transport has detected that a channel is writable and thus data can be
2430// received before the data channel state changes to open. That is hard to test
2431// but the same buffering is expected to be used in that case.
2432TEST_F(PeerConnectionIntegrationTest,
2433 DataBufferedUntilRtpDataChannelObserverRegistered) {
2434 // Use fake clock and simulated network delay so that we predictably can wait
2435 // until an SCTP message has been delivered without "sleep()"ing.
2436 rtc::ScopedFakeClock fake_clock;
2437 // Some things use a time of "0" as a special value, so we need to start out
2438 // the fake clock at a nonzero time.
2439 // TODO(deadbeef): Fix this.
2440 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2441 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
2442 virtual_socket_server()->UpdateDelayDistribution();
2443
2444 FakeConstraints constraints;
2445 constraints.SetAllowRtpDataChannels();
2446 ASSERT_TRUE(
2447 CreatePeerConnectionWrappersWithConstraints(&constraints, &constraints));
2448 ConnectFakeSignaling();
2449 caller()->CreateDataChannel();
2450 caller()->CreateAndSetAndSignalOffer();
2451 ASSERT_TRUE(caller()->data_channel() != nullptr);
2452 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
2453 kDefaultTimeout, fake_clock);
2454 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
2455 kDefaultTimeout, fake_clock);
2456 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
2457 callee()->data_channel()->state(), kDefaultTimeout,
2458 fake_clock);
2459
2460 // Unregister the observer which is normally automatically registered.
2461 callee()->data_channel()->UnregisterObserver();
2462 // Send data and advance fake clock until it should have been received.
2463 std::string data = "hello world";
2464 caller()->data_channel()->Send(DataBuffer(data));
2465 SIMULATED_WAIT(false, 50, fake_clock);
2466
2467 // Attach data channel and expect data to be received immediately. Note that
2468 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
2469 // further, but data can be received even if the callback is asynchronous.
2470 MockDataChannelObserver new_observer(callee()->data_channel());
2471 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
2472 fake_clock);
2473}
2474
2475// This test sets up a call between two parties with audio, video and but only
2476// the caller client supports RTP data channels.
2477TEST_F(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
2478 FakeConstraints setup_constraints_1;
2479 setup_constraints_1.SetAllowRtpDataChannels();
2480 // Must disable DTLS to make negotiation succeed.
2481 setup_constraints_1.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2482 false);
2483 FakeConstraints setup_constraints_2;
2484 setup_constraints_2.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2485 false);
2486 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(
2487 &setup_constraints_1, &setup_constraints_2));
2488 ConnectFakeSignaling();
2489 caller()->CreateDataChannel();
2490 caller()->AddAudioVideoMediaStream();
2491 callee()->AddAudioVideoMediaStream();
2492 caller()->CreateAndSetAndSignalOffer();
2493 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2494 // The caller should still have a data channel, but it should be closed, and
2495 // one should ever have been created for the callee.
2496 EXPECT_TRUE(caller()->data_channel() != nullptr);
2497 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2498 EXPECT_EQ(nullptr, callee()->data_channel());
2499}
2500
2501// This test sets up a call between two parties with audio, and video. When
2502// audio and video is setup and flowing, an RTP data channel is negotiated.
2503TEST_F(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
2504 FakeConstraints setup_constraints;
2505 setup_constraints.SetAllowRtpDataChannels();
2506 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2507 &setup_constraints));
2508 ConnectFakeSignaling();
2509 // Do initial offer/answer with audio/video.
2510 caller()->AddAudioVideoMediaStream();
2511 callee()->AddAudioVideoMediaStream();
2512 caller()->CreateAndSetAndSignalOffer();
2513 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2514 // Create data channel and do new offer and answer.
2515 caller()->CreateDataChannel();
2516 caller()->CreateAndSetAndSignalOffer();
2517 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2518 ASSERT_NE(nullptr, caller()->data_channel());
2519 ASSERT_NE(nullptr, callee()->data_channel());
2520 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2521 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2522 // Ensure data can be sent in both directions.
2523 std::string data = "hello world";
2524 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2525 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2526 kDefaultTimeout);
2527 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2528 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2529 kDefaultTimeout);
2530}
2531
2532#ifdef HAVE_SCTP
2533
2534// This test sets up a call between two parties with audio, video and an SCTP
2535// data channel.
2536TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
2537 ASSERT_TRUE(CreatePeerConnectionWrappers());
2538 ConnectFakeSignaling();
2539 // Expect that data channel created on caller side will show up for callee as
2540 // well.
2541 caller()->CreateDataChannel();
2542 caller()->AddAudioVideoMediaStream();
2543 callee()->AddAudioVideoMediaStream();
2544 caller()->CreateAndSetAndSignalOffer();
2545 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2546 // Ensure the existence of the SCTP data channel didn't impede audio/video.
2547 ExpectNewFramesReceivedWithWait(
2548 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2549 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2550 kMaxWaitForFramesMs);
2551 // Caller data channel should already exist (it created one). Callee data
2552 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2553 ASSERT_NE(nullptr, caller()->data_channel());
2554 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2555 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2556 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2557
2558 // Ensure data can be sent in both directions.
2559 std::string data = "hello world";
2560 caller()->data_channel()->Send(DataBuffer(data));
2561 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2562 kDefaultTimeout);
2563 callee()->data_channel()->Send(DataBuffer(data));
2564 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2565 kDefaultTimeout);
2566}
2567
2568// Ensure that when the callee closes an SCTP data channel, the closing
2569// procedure results in the data channel being closed for the caller as well.
2570TEST_F(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
2571 // Same procedure as above test.
2572 ASSERT_TRUE(CreatePeerConnectionWrappers());
2573 ConnectFakeSignaling();
2574 caller()->CreateDataChannel();
2575 caller()->AddAudioVideoMediaStream();
2576 callee()->AddAudioVideoMediaStream();
2577 caller()->CreateAndSetAndSignalOffer();
2578 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2579 ASSERT_NE(nullptr, caller()->data_channel());
2580 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2581 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2582 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2583
2584 // Close the data channel on the callee side, and wait for it to reach the
2585 // "closed" state on both sides.
2586 callee()->data_channel()->Close();
2587 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
2588 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
2589}
2590
2591// Test usrsctp's ability to process unordered data stream, where data actually
2592// arrives out of order using simulated delays. Previously there have been some
2593// bugs in this area.
2594TEST_F(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
2595 // Introduce random network delays.
2596 // Otherwise it's not a true "unordered" test.
2597 virtual_socket_server()->set_delay_mean(20);
2598 virtual_socket_server()->set_delay_stddev(5);
2599 virtual_socket_server()->UpdateDelayDistribution();
2600 // Normal procedure, but with unordered data channel config.
2601 ASSERT_TRUE(CreatePeerConnectionWrappers());
2602 ConnectFakeSignaling();
2603 webrtc::DataChannelInit init;
2604 init.ordered = false;
2605 caller()->CreateDataChannel(&init);
2606 caller()->CreateAndSetAndSignalOffer();
2607 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2608 ASSERT_NE(nullptr, caller()->data_channel());
2609 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2610 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2611 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2612
2613 static constexpr int kNumMessages = 100;
2614 // Deliberately chosen to be larger than the MTU so messages get fragmented.
2615 static constexpr size_t kMaxMessageSize = 4096;
2616 // Create and send random messages.
2617 std::vector<std::string> sent_messages;
2618 for (int i = 0; i < kNumMessages; ++i) {
2619 size_t length =
2620 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
2621 std::string message;
2622 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
2623 caller()->data_channel()->Send(DataBuffer(message));
2624 callee()->data_channel()->Send(DataBuffer(message));
2625 sent_messages.push_back(message);
2626 }
2627
2628 // Wait for all messages to be received.
2629 EXPECT_EQ_WAIT(kNumMessages,
2630 caller()->data_observer()->received_message_count(),
2631 kDefaultTimeout);
2632 EXPECT_EQ_WAIT(kNumMessages,
2633 callee()->data_observer()->received_message_count(),
2634 kDefaultTimeout);
2635
2636 // Sort and compare to make sure none of the messages were corrupted.
2637 std::vector<std::string> caller_received_messages =
2638 caller()->data_observer()->messages();
2639 std::vector<std::string> callee_received_messages =
2640 callee()->data_observer()->messages();
2641 std::sort(sent_messages.begin(), sent_messages.end());
2642 std::sort(caller_received_messages.begin(), caller_received_messages.end());
2643 std::sort(callee_received_messages.begin(), callee_received_messages.end());
2644 EXPECT_EQ(sent_messages, caller_received_messages);
2645 EXPECT_EQ(sent_messages, callee_received_messages);
2646}
2647
2648// This test sets up a call between two parties with audio, and video. When
2649// audio and video are setup and flowing, an SCTP data channel is negotiated.
2650TEST_F(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
2651 ASSERT_TRUE(CreatePeerConnectionWrappers());
2652 ConnectFakeSignaling();
2653 // Do initial offer/answer with audio/video.
2654 caller()->AddAudioVideoMediaStream();
2655 callee()->AddAudioVideoMediaStream();
2656 caller()->CreateAndSetAndSignalOffer();
2657 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2658 // Create data channel and do new offer and answer.
2659 caller()->CreateDataChannel();
2660 caller()->CreateAndSetAndSignalOffer();
2661 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2662 // Caller data channel should already exist (it created one). Callee data
2663 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2664 ASSERT_NE(nullptr, caller()->data_channel());
2665 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2666 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2667 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2668 // Ensure data can be sent in both directions.
2669 std::string data = "hello world";
2670 caller()->data_channel()->Send(DataBuffer(data));
2671 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2672 kDefaultTimeout);
2673 callee()->data_channel()->Send(DataBuffer(data));
2674 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2675 kDefaultTimeout);
2676}
2677
deadbeef7914b8c2017-04-21 03:23:33 -07002678// Set up a connection initially just using SCTP data channels, later upgrading
2679// to audio/video, ensuring frames are received end-to-end. Effectively the
2680// inverse of the test above.
2681// This was broken in M57; see https://crbug.com/711243
2682TEST_F(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
2683 ASSERT_TRUE(CreatePeerConnectionWrappers());
2684 ConnectFakeSignaling();
2685 // Do initial offer/answer with just data channel.
2686 caller()->CreateDataChannel();
2687 caller()->CreateAndSetAndSignalOffer();
2688 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2689 // Wait until data can be sent over the data channel.
2690 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2691 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2692 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2693
2694 // Do subsequent offer/answer with two-way audio and video. Audio and video
2695 // should end up bundled on the DTLS/ICE transport already used for data.
2696 caller()->AddAudioVideoMediaStream();
2697 callee()->AddAudioVideoMediaStream();
2698 caller()->CreateAndSetAndSignalOffer();
2699 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2700 ExpectNewFramesReceivedWithWait(
2701 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2702 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2703 kMaxWaitForFramesMs);
2704}
2705
deadbeef8b7e9ad2017-05-25 09:38:55 -07002706static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
2707 const ContentInfo* dc_offer = GetFirstDataContent(desc);
2708 ASSERT_NE(nullptr, dc_offer);
2709 cricket::DataContentDescription* dcd_offer =
2710 static_cast<cricket::DataContentDescription*>(dc_offer->description);
2711 dcd_offer->set_use_sctpmap(false);
2712 dcd_offer->set_protocol("UDP/DTLS/SCTP");
2713}
2714
2715// Test that the data channel works when a spec-compliant SCTP m= section is
2716// offered (using "a=sctp-port" instead of "a=sctpmap", and using
2717// "UDP/DTLS/SCTP" as the protocol).
2718TEST_F(PeerConnectionIntegrationTest,
2719 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
2720 ASSERT_TRUE(CreatePeerConnectionWrappers());
2721 ConnectFakeSignaling();
2722 caller()->CreateDataChannel();
2723 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
2724 caller()->CreateAndSetAndSignalOffer();
2725 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2726 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2727 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2728 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2729
2730 // Ensure data can be sent in both directions.
2731 std::string data = "hello world";
2732 caller()->data_channel()->Send(DataBuffer(data));
2733 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2734 kDefaultTimeout);
2735 callee()->data_channel()->Send(DataBuffer(data));
2736 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2737 kDefaultTimeout);
2738}
2739
deadbeef1dcb1642017-03-29 21:08:16 -07002740#endif // HAVE_SCTP
2741
2742// Test that the ICE connection and gathering states eventually reach
2743// "complete".
2744TEST_F(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
2745 ASSERT_TRUE(CreatePeerConnectionWrappers());
2746 ConnectFakeSignaling();
2747 // Do normal offer/answer.
2748 caller()->AddAudioVideoMediaStream();
2749 callee()->AddAudioVideoMediaStream();
2750 caller()->CreateAndSetAndSignalOffer();
2751 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2752 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2753 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
2754 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2755 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
2756 // After the best candidate pair is selected and all candidates are signaled,
2757 // the ICE connection state should reach "complete".
2758 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
2759 // answerer/"callee" by default) only reaches "connected". When this is
2760 // fixed, this test should be updated.
2761 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2762 caller()->ice_connection_state(), kDefaultTimeout);
2763 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2764 callee()->ice_connection_state(), kDefaultTimeout);
2765}
2766
Steve Antonede9ca52017-10-16 13:04:27 -07002767// Test that firewalling the ICE connection causes the clients to identify the
2768// disconnected state and then removing the firewall causes them to reconnect.
2769class PeerConnectionIntegrationIceStatesTest
2770 : public PeerConnectionIntegrationTest,
2771 public ::testing::WithParamInterface<std::tuple<std::string, uint32_t>> {
2772 protected:
2773 PeerConnectionIntegrationIceStatesTest() {
2774 port_allocator_flags_ = std::get<1>(GetParam());
2775 }
2776
2777 void StartStunServer(const SocketAddress& server_address) {
2778 stun_server_.reset(
2779 cricket::TestStunServer::Create(network_thread(), server_address));
2780 }
2781
2782 bool TestIPv6() {
2783 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
2784 }
2785
2786 void SetPortAllocatorFlags() {
2787 caller()->port_allocator()->set_flags(port_allocator_flags_);
2788 callee()->port_allocator()->set_flags(port_allocator_flags_);
2789 }
2790
2791 std::vector<SocketAddress> CallerAddresses() {
2792 std::vector<SocketAddress> addresses;
2793 addresses.push_back(SocketAddress("1.1.1.1", 0));
2794 if (TestIPv6()) {
2795 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
2796 }
2797 return addresses;
2798 }
2799
2800 std::vector<SocketAddress> CalleeAddresses() {
2801 std::vector<SocketAddress> addresses;
2802 addresses.push_back(SocketAddress("2.2.2.2", 0));
2803 if (TestIPv6()) {
2804 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
2805 }
2806 return addresses;
2807 }
2808
2809 void SetUpNetworkInterfaces() {
2810 // Remove the default interfaces added by the test infrastructure.
2811 caller()->network()->RemoveInterface(kDefaultLocalAddress);
2812 callee()->network()->RemoveInterface(kDefaultLocalAddress);
2813
2814 // Add network addresses for test.
2815 for (const auto& caller_address : CallerAddresses()) {
2816 caller()->network()->AddInterface(caller_address);
2817 }
2818 for (const auto& callee_address : CalleeAddresses()) {
2819 callee()->network()->AddInterface(callee_address);
2820 }
2821 }
2822
2823 private:
2824 uint32_t port_allocator_flags_;
2825 std::unique_ptr<cricket::TestStunServer> stun_server_;
2826};
2827
2828// Tests that the PeerConnection goes through all the ICE gathering/connection
2829// states over the duration of the call. This includes Disconnected and Failed
2830// states, induced by putting a firewall between the peers and waiting for them
2831// to time out.
2832TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
2833 rtc::ScopedFakeClock fake_clock;
2834 // Some things use a time of "0" as a special value, so we need to start out
2835 // the fake clock at a nonzero time.
2836 // TODO(deadbeef): Fix this.
2837 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2838
2839 const SocketAddress kStunServerAddress =
2840 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
2841 StartStunServer(kStunServerAddress);
2842
2843 PeerConnectionInterface::RTCConfiguration config;
2844 PeerConnectionInterface::IceServer ice_stun_server;
2845 ice_stun_server.urls.push_back(
2846 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
2847 kStunServerAddress.PortAsString());
2848 config.servers.push_back(ice_stun_server);
2849
2850 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
2851 ConnectFakeSignaling();
2852 SetPortAllocatorFlags();
2853 SetUpNetworkInterfaces();
2854 caller()->AddAudioVideoMediaStream();
2855 callee()->AddAudioVideoMediaStream();
2856
2857 // Initial state before anything happens.
2858 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
2859 caller()->ice_gathering_state());
2860 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
2861 caller()->ice_connection_state());
2862
2863 // Start the call by creating the offer, setting it as the local description,
2864 // then sending it to the peer who will respond with an answer. This happens
2865 // asynchronously so that we can watch the states as it runs in the
2866 // background.
2867 caller()->CreateAndSetAndSignalOffer();
2868
2869 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
2870 caller()->ice_connection_state(), kDefaultTimeout,
2871 fake_clock);
2872
2873 // Verify that the observer was notified of the intermediate transitions.
2874 EXPECT_THAT(caller()->ice_connection_state_history(),
2875 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
2876 PeerConnectionInterface::kIceConnectionConnected,
2877 PeerConnectionInterface::kIceConnectionCompleted));
2878 EXPECT_THAT(caller()->ice_gathering_state_history(),
2879 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
2880 PeerConnectionInterface::kIceGatheringComplete));
2881
2882 // Block connections to/from the caller and wait for ICE to become
2883 // disconnected.
2884 for (const auto& caller_address : CallerAddresses()) {
2885 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
2886 }
2887 LOG(LS_INFO) << "Firewall rules applied";
2888 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
2889 caller()->ice_connection_state(), kDefaultTimeout,
2890 fake_clock);
2891
2892 // Let ICE re-establish by removing the firewall rules.
2893 firewall()->ClearRules();
2894 LOG(LS_INFO) << "Firewall rules cleared";
2895 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
2896 caller()->ice_connection_state(), kDefaultTimeout,
2897 fake_clock);
2898
2899 // According to RFC7675, if there is no response within 30 seconds then the
2900 // peer should consider the other side to have rejected the connection. This
2901 // is signalled by the state transitioning to "failed".
2902 constexpr int kConsentTimeout = 30000;
2903 for (const auto& caller_address : CallerAddresses()) {
2904 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
2905 }
2906 LOG(LS_INFO) << "Firewall rules applied again";
2907 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
2908 caller()->ice_connection_state(), kConsentTimeout,
2909 fake_clock);
2910}
2911
2912// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
2913// and that the statistics in the metric observers are updated correctly.
2914TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
2915 ASSERT_TRUE(CreatePeerConnectionWrappers());
2916 ConnectFakeSignaling();
2917 SetPortAllocatorFlags();
2918 SetUpNetworkInterfaces();
2919 caller()->AddAudioVideoMediaStream();
2920 callee()->AddAudioVideoMediaStream();
2921
2922 rtc::scoped_refptr<webrtc::FakeMetricsObserver> metrics_observer(
2923 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>());
2924 caller()->pc()->RegisterUMAObserver(metrics_observer.get());
2925
2926 caller()->CreateAndSetAndSignalOffer();
2927
2928 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2929
2930 const int num_best_ipv4 = metrics_observer->GetEnumCounter(
2931 webrtc::kEnumCounterAddressFamily, webrtc::kBestConnections_IPv4);
2932 const int num_best_ipv6 = metrics_observer->GetEnumCounter(
2933 webrtc::kEnumCounterAddressFamily, webrtc::kBestConnections_IPv6);
2934 if (TestIPv6()) {
2935 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
2936 // connection.
2937 EXPECT_EQ(0u, num_best_ipv4);
2938 EXPECT_EQ(1u, num_best_ipv6);
2939 } else {
2940 EXPECT_EQ(1u, num_best_ipv4);
2941 EXPECT_EQ(0u, num_best_ipv6);
2942 }
2943
2944 EXPECT_EQ(0u, metrics_observer->GetEnumCounter(
2945 webrtc::kEnumCounterIceCandidatePairTypeUdp,
2946 webrtc::kIceCandidatePairHostHost));
2947 EXPECT_EQ(1u, metrics_observer->GetEnumCounter(
2948 webrtc::kEnumCounterIceCandidatePairTypeUdp,
2949 webrtc::kIceCandidatePairHostPublicHostPublic));
2950}
2951
2952constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
2953 cricket::PORTALLOCATOR_DISABLE_STUN |
2954 cricket::PORTALLOCATOR_DISABLE_RELAY;
2955constexpr uint32_t kFlagsIPv6NoStun =
2956 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
2957 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
2958constexpr uint32_t kFlagsIPv4Stun =
2959 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
2960
2961INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
2962 PeerConnectionIntegrationIceStatesTest,
2963 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
2964 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
2965 std::make_pair("IPv4 with STUN",
2966 kFlagsIPv4Stun)));
2967
deadbeef1dcb1642017-03-29 21:08:16 -07002968// This test sets up a call between two parties with audio and video.
2969// During the call, the caller restarts ICE and the test verifies that
2970// new ICE candidates are generated and audio and video still can flow, and the
2971// ICE state reaches completed again.
2972TEST_F(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
2973 ASSERT_TRUE(CreatePeerConnectionWrappers());
2974 ConnectFakeSignaling();
2975 // Do normal offer/answer and wait for ICE to complete.
2976 caller()->AddAudioVideoMediaStream();
2977 callee()->AddAudioVideoMediaStream();
2978 caller()->CreateAndSetAndSignalOffer();
2979 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2980 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2981 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2982 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2983 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2984
2985 // To verify that the ICE restart actually occurs, get
2986 // ufrag/password/candidates before and after restart.
2987 // Create an SDP string of the first audio candidate for both clients.
2988 const webrtc::IceCandidateCollection* audio_candidates_caller =
2989 caller()->pc()->local_description()->candidates(0);
2990 const webrtc::IceCandidateCollection* audio_candidates_callee =
2991 callee()->pc()->local_description()->candidates(0);
2992 ASSERT_GT(audio_candidates_caller->count(), 0u);
2993 ASSERT_GT(audio_candidates_callee->count(), 0u);
2994 std::string caller_candidate_pre_restart;
2995 ASSERT_TRUE(
2996 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
2997 std::string callee_candidate_pre_restart;
2998 ASSERT_TRUE(
2999 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
3000 const cricket::SessionDescription* desc =
3001 caller()->pc()->local_description()->description();
3002 std::string caller_ufrag_pre_restart =
3003 desc->transport_infos()[0].description.ice_ufrag;
3004 desc = callee()->pc()->local_description()->description();
3005 std::string callee_ufrag_pre_restart =
3006 desc->transport_infos()[0].description.ice_ufrag;
3007
3008 // Have the caller initiate an ICE restart.
3009 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
3010 caller()->CreateAndSetAndSignalOffer();
3011 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3012 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3013 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3014 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3015 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3016
3017 // Grab the ufrags/candidates again.
3018 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
3019 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
3020 ASSERT_GT(audio_candidates_caller->count(), 0u);
3021 ASSERT_GT(audio_candidates_callee->count(), 0u);
3022 std::string caller_candidate_post_restart;
3023 ASSERT_TRUE(
3024 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
3025 std::string callee_candidate_post_restart;
3026 ASSERT_TRUE(
3027 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
3028 desc = caller()->pc()->local_description()->description();
3029 std::string caller_ufrag_post_restart =
3030 desc->transport_infos()[0].description.ice_ufrag;
3031 desc = callee()->pc()->local_description()->description();
3032 std::string callee_ufrag_post_restart =
3033 desc->transport_infos()[0].description.ice_ufrag;
3034 // Sanity check that an ICE restart was actually negotiated in SDP.
3035 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
3036 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
3037 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
3038 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
3039
3040 // Ensure that additional frames are received after the ICE restart.
3041 ExpectNewFramesReceivedWithWait(
3042 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3043 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3044 kMaxWaitForFramesMs);
3045}
3046
3047// Verify that audio/video can be received end-to-end when ICE renomination is
3048// enabled.
3049TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
3050 PeerConnectionInterface::RTCConfiguration config;
3051 config.enable_ice_renomination = true;
3052 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3053 ConnectFakeSignaling();
3054 // Do normal offer/answer and wait for some frames to be received in each
3055 // direction.
3056 caller()->AddAudioVideoMediaStream();
3057 callee()->AddAudioVideoMediaStream();
3058 caller()->CreateAndSetAndSignalOffer();
3059 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3060 // Sanity check that ICE renomination was actually negotiated.
3061 const cricket::SessionDescription* desc =
3062 caller()->pc()->local_description()->description();
3063 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003064 ASSERT_NE(
3065 info.description.transport_options.end(),
3066 std::find(info.description.transport_options.begin(),
3067 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003068 }
3069 desc = callee()->pc()->local_description()->description();
3070 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003071 ASSERT_NE(
3072 info.description.transport_options.end(),
3073 std::find(info.description.transport_options.begin(),
3074 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003075 }
3076 ExpectNewFramesReceivedWithWait(
3077 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3078 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3079 kMaxWaitForFramesMs);
3080}
3081
3082// This test sets up a call between two parties with audio and video. It then
3083// renegotiates setting the video m-line to "port 0", then later renegotiates
3084// again, enabling video.
3085TEST_F(PeerConnectionIntegrationTest,
3086 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
3087 ASSERT_TRUE(CreatePeerConnectionWrappers());
3088 ConnectFakeSignaling();
3089
3090 // Do initial negotiation, only sending media from the caller. Will result in
3091 // video and audio recvonly "m=" sections.
3092 caller()->AddAudioVideoMediaStream();
3093 caller()->CreateAndSetAndSignalOffer();
3094 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3095
3096 // Negotiate again, disabling the video "m=" section (the callee will set the
3097 // port to 0 due to offer_to_receive_video = 0).
3098 PeerConnectionInterface::RTCOfferAnswerOptions options;
3099 options.offer_to_receive_video = 0;
3100 callee()->SetOfferAnswerOptions(options);
3101 caller()->CreateAndSetAndSignalOffer();
3102 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3103 // Sanity check that video "m=" section was actually rejected.
3104 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
3105 callee()->pc()->local_description()->description());
3106 ASSERT_NE(nullptr, answer_video_content);
3107 ASSERT_TRUE(answer_video_content->rejected);
3108
3109 // Enable video and do negotiation again, making sure video is received
3110 // end-to-end, also adding media stream to callee.
3111 options.offer_to_receive_video = 1;
3112 callee()->SetOfferAnswerOptions(options);
3113 callee()->AddAudioVideoMediaStream();
3114 caller()->CreateAndSetAndSignalOffer();
3115 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3116 // Verify the caller receives frames from the newly added stream, and the
3117 // callee receives additional frames from the re-enabled video m= section.
3118 ExpectNewFramesReceivedWithWait(
3119 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3120 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3121 kMaxWaitForFramesMs);
3122}
3123
3124// This test sets up a Jsep call between two parties with external
3125// VideoDecoderFactory.
3126// TODO(holmer): Disabled due to sometimes crashing on buildbots.
3127// See issue webrtc/2378.
3128TEST_F(PeerConnectionIntegrationTest,
3129 DISABLED_EndToEndCallWithVideoDecoderFactory) {
3130 ASSERT_TRUE(CreatePeerConnectionWrappers());
3131 EnableVideoDecoderFactory();
3132 ConnectFakeSignaling();
3133 caller()->AddAudioVideoMediaStream();
3134 callee()->AddAudioVideoMediaStream();
3135 caller()->CreateAndSetAndSignalOffer();
3136 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3137 ExpectNewFramesReceivedWithWait(
3138 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3139 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3140 kMaxWaitForFramesMs);
3141}
3142
3143// This tests that if we negotiate after calling CreateSender but before we
3144// have a track, then set a track later, frames from the newly-set track are
3145// received end-to-end.
3146// TODO(deadbeef): Change this test to use AddTransceiver, once that's
3147// implemented.
3148TEST_F(PeerConnectionIntegrationTest,
3149 MediaFlowsAfterEarlyWarmupWithCreateSender) {
3150 ASSERT_TRUE(CreatePeerConnectionWrappers());
3151 ConnectFakeSignaling();
3152 auto caller_audio_sender =
3153 caller()->pc()->CreateSender("audio", "caller_stream");
3154 auto caller_video_sender =
3155 caller()->pc()->CreateSender("video", "caller_stream");
3156 auto callee_audio_sender =
3157 callee()->pc()->CreateSender("audio", "callee_stream");
3158 auto callee_video_sender =
3159 callee()->pc()->CreateSender("video", "callee_stream");
3160 caller()->CreateAndSetAndSignalOffer();
3161 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3162 // Wait for ICE to complete, without any tracks being set.
3163 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3164 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3165 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3166 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3167 // Now set the tracks, and expect frames to immediately start flowing.
3168 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3169 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3170 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3171 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
3172 ExpectNewFramesReceivedWithWait(
3173 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3174 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3175 kMaxWaitForFramesMs);
3176}
3177
3178// This test verifies that a remote video track can be added via AddStream,
3179// and sent end-to-end. For this particular test, it's simply echoed back
3180// from the caller to the callee, rather than being forwarded to a third
3181// PeerConnection.
3182TEST_F(PeerConnectionIntegrationTest, CanSendRemoteVideoTrack) {
3183 ASSERT_TRUE(CreatePeerConnectionWrappers());
3184 ConnectFakeSignaling();
3185 // Just send a video track from the caller.
3186 caller()->AddMediaStreamFromTracks(nullptr,
3187 caller()->CreateLocalVideoTrack());
3188 caller()->CreateAndSetAndSignalOffer();
3189 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3190 ASSERT_EQ(1, callee()->remote_streams()->count());
3191
3192 // Echo the stream back, and do a new offer/anwer (initiated by callee this
3193 // time).
3194 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
3195 callee()->CreateAndSetAndSignalOffer();
3196 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3197
3198 int expected_caller_received_video_frames = kDefaultExpectedVideoFrameCount;
3199 ExpectNewFramesReceivedWithWait(0, expected_caller_received_video_frames, 0,
3200 0, kMaxWaitForFramesMs);
3201}
3202
3203// Test that we achieve the expected end-to-end connection time, using a
3204// fake clock and simulated latency on the media and signaling paths.
3205// We use a TURN<->TURN connection because this is usually the quickest to
3206// set up initially, especially when we're confident the connection will work
3207// and can start sending media before we get a STUN response.
3208//
3209// With various optimizations enabled, here are the network delays we expect to
3210// be on the critical path:
3211// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
3212// signaling answer (with DTLS fingerprint).
3213// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
3214// using TURN<->TURN pair, and DTLS exchange is 4 packets,
3215// the first of which should have arrived before the answer.
3216TEST_F(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
3217 rtc::ScopedFakeClock fake_clock;
3218 // Some things use a time of "0" as a special value, so we need to start out
3219 // the fake clock at a nonzero time.
3220 // TODO(deadbeef): Fix this.
3221 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
3222
3223 static constexpr int media_hop_delay_ms = 50;
3224 static constexpr int signaling_trip_delay_ms = 500;
3225 // For explanation of these values, see comment above.
3226 static constexpr int required_media_hops = 9;
3227 static constexpr int required_signaling_trips = 2;
3228 // For internal delays (such as posting an event asychronously).
3229 static constexpr int allowed_internal_delay_ms = 20;
3230 static constexpr int total_connection_time_ms =
3231 media_hop_delay_ms * required_media_hops +
3232 signaling_trip_delay_ms * required_signaling_trips +
3233 allowed_internal_delay_ms;
3234
3235 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3236 3478};
3237 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3238 0};
3239 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3240 3478};
3241 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3242 0};
3243 cricket::TestTurnServer turn_server_1(network_thread(),
3244 turn_server_1_internal_address,
3245 turn_server_1_external_address);
3246 cricket::TestTurnServer turn_server_2(network_thread(),
3247 turn_server_2_internal_address,
3248 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02003249
deadbeef1dcb1642017-03-29 21:08:16 -07003250 // Bypass permission check on received packets so media can be sent before
3251 // the candidate is signaled.
3252 turn_server_1.set_enable_permission_checks(false);
3253 turn_server_2.set_enable_permission_checks(false);
3254
3255 PeerConnectionInterface::RTCConfiguration client_1_config;
3256 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3257 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3258 ice_server_1.username = "test";
3259 ice_server_1.password = "test";
3260 client_1_config.servers.push_back(ice_server_1);
3261 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3262 client_1_config.presume_writable_when_fully_relayed = true;
3263
3264 PeerConnectionInterface::RTCConfiguration client_2_config;
3265 webrtc::PeerConnectionInterface::IceServer ice_server_2;
3266 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
3267 ice_server_2.username = "test";
3268 ice_server_2.password = "test";
3269 client_2_config.servers.push_back(ice_server_2);
3270 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
3271 client_2_config.presume_writable_when_fully_relayed = true;
3272
3273 ASSERT_TRUE(
3274 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
3275 // Set up the simulated delays.
3276 SetSignalingDelayMs(signaling_trip_delay_ms);
3277 ConnectFakeSignaling();
3278 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
3279 virtual_socket_server()->UpdateDelayDistribution();
3280
3281 // Set "offer to receive audio/video" without adding any tracks, so we just
3282 // set up ICE/DTLS with no media.
3283 PeerConnectionInterface::RTCOfferAnswerOptions options;
3284 options.offer_to_receive_audio = 1;
3285 options.offer_to_receive_video = 1;
3286 caller()->SetOfferAnswerOptions(options);
3287 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07003288 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
3289 fake_clock);
deadbeef1dcb1642017-03-29 21:08:16 -07003290 // Need to free the clients here since they're using things we created on
3291 // the stack.
3292 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
3293 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
3294}
3295
Jonas Orelandbdcee282017-10-10 14:01:40 +02003296// Verify that a TurnCustomizer passed in through RTCConfiguration
3297// is actually used by the underlying TURN candidate pair.
3298// Note that turnport_unittest.cc contains more detailed, lower-level tests.
3299TEST_F(PeerConnectionIntegrationTest, \
3300 TurnCustomizerUsedForTurnConnections) {
3301 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3302 3478};
3303 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3304 0};
3305 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3306 3478};
3307 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3308 0};
3309 cricket::TestTurnServer turn_server_1(network_thread(),
3310 turn_server_1_internal_address,
3311 turn_server_1_external_address);
3312 cricket::TestTurnServer turn_server_2(network_thread(),
3313 turn_server_2_internal_address,
3314 turn_server_2_external_address);
3315
3316 PeerConnectionInterface::RTCConfiguration client_1_config;
3317 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3318 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3319 ice_server_1.username = "test";
3320 ice_server_1.password = "test";
3321 client_1_config.servers.push_back(ice_server_1);
3322 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3323 auto customizer1 = rtc::MakeUnique<cricket::TestTurnCustomizer>();
3324 client_1_config.turn_customizer = customizer1.get();
3325
3326 PeerConnectionInterface::RTCConfiguration client_2_config;
3327 webrtc::PeerConnectionInterface::IceServer ice_server_2;
3328 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
3329 ice_server_2.username = "test";
3330 ice_server_2.password = "test";
3331 client_2_config.servers.push_back(ice_server_2);
3332 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
3333 auto customizer2 = rtc::MakeUnique<cricket::TestTurnCustomizer>();
3334 client_2_config.turn_customizer = customizer2.get();
3335
3336 ASSERT_TRUE(
3337 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
3338 ConnectFakeSignaling();
3339
3340 // Set "offer to receive audio/video" without adding any tracks, so we just
3341 // set up ICE/DTLS with no media.
3342 PeerConnectionInterface::RTCOfferAnswerOptions options;
3343 options.offer_to_receive_audio = 1;
3344 options.offer_to_receive_video = 1;
3345 caller()->SetOfferAnswerOptions(options);
3346 caller()->CreateAndSetAndSignalOffer();
3347 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
3348
3349 EXPECT_GT(customizer1->allow_channel_data_cnt_, 0u);
3350 EXPECT_GT(customizer1->modify_cnt_, 0u);
3351
3352 EXPECT_GT(customizer2->allow_channel_data_cnt_, 0u);
3353 EXPECT_GT(customizer2->modify_cnt_, 0u);
3354
3355 // Need to free the clients here since they're using things we created on
3356 // the stack.
3357 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
3358 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
3359}
3360
deadbeefc964d0b2017-04-03 10:03:35 -07003361// Test that audio and video flow end-to-end when codec names don't use the
3362// expected casing, given that they're supposed to be case insensitive. To test
3363// this, all but one codec is removed from each media description, and its
3364// casing is changed.
3365//
3366// In the past, this has regressed and caused crashes/black video, due to the
3367// fact that code at some layers was doing case-insensitive comparisons and
3368// code at other layers was not.
3369TEST_F(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
3370 ASSERT_TRUE(CreatePeerConnectionWrappers());
3371 ConnectFakeSignaling();
3372 caller()->AddAudioVideoMediaStream();
3373 callee()->AddAudioVideoMediaStream();
3374
3375 // Remove all but one audio/video codec (opus and VP8), and change the
3376 // casing of the caller's generated offer.
3377 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
3378 cricket::AudioContentDescription* audio =
3379 GetFirstAudioContentDescription(description);
3380 ASSERT_NE(nullptr, audio);
3381 auto audio_codecs = audio->codecs();
3382 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
3383 [](const cricket::AudioCodec& codec) {
3384 return codec.name != "opus";
3385 }),
3386 audio_codecs.end());
3387 ASSERT_EQ(1u, audio_codecs.size());
3388 audio_codecs[0].name = "OpUs";
3389 audio->set_codecs(audio_codecs);
3390
3391 cricket::VideoContentDescription* video =
3392 GetFirstVideoContentDescription(description);
3393 ASSERT_NE(nullptr, video);
3394 auto video_codecs = video->codecs();
3395 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
3396 [](const cricket::VideoCodec& codec) {
3397 return codec.name != "VP8";
3398 }),
3399 video_codecs.end());
3400 ASSERT_EQ(1u, video_codecs.size());
3401 video_codecs[0].name = "vP8";
3402 video->set_codecs(video_codecs);
3403 });
3404
3405 caller()->CreateAndSetAndSignalOffer();
3406 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3407
3408 // Verify frames are still received end-to-end.
3409 ExpectNewFramesReceivedWithWait(
3410 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3411 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3412 kMaxWaitForFramesMs);
3413}
3414
hbos8d609f62017-04-10 07:39:05 -07003415TEST_F(PeerConnectionIntegrationTest, GetSources) {
3416 ASSERT_TRUE(CreatePeerConnectionWrappers());
3417 ConnectFakeSignaling();
3418 caller()->AddAudioOnlyMediaStream();
3419 caller()->CreateAndSetAndSignalOffer();
3420 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07003421 // Wait for one audio frame to be received by the callee.
hbos8d609f62017-04-10 07:39:05 -07003422 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
3423 ASSERT_GT(callee()->pc()->GetReceivers().size(), 0u);
3424 auto receiver = callee()->pc()->GetReceivers()[0];
3425 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
3426
3427 auto contributing_sources = receiver->GetSources();
3428 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
3429 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
3430 contributing_sources[0].source_id());
3431}
3432
deadbeef2f425aa2017-04-14 10:41:32 -07003433// Test that if a track is removed and added again with a different stream ID,
3434// the new stream ID is successfully communicated in SDP and media continues to
3435// flow end-to-end.
3436TEST_F(PeerConnectionIntegrationTest, RemoveAndAddTrackWithNewStreamId) {
3437 ASSERT_TRUE(CreatePeerConnectionWrappers());
3438 ConnectFakeSignaling();
3439
3440 rtc::scoped_refptr<MediaStreamInterface> stream_1 =
3441 caller()->pc_factory()->CreateLocalMediaStream("stream_1");
3442 rtc::scoped_refptr<MediaStreamInterface> stream_2 =
3443 caller()->pc_factory()->CreateLocalMediaStream("stream_2");
3444
3445 // Add track using stream 1, do offer/answer.
3446 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
3447 caller()->CreateLocalAudioTrack();
3448 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
3449 caller()->pc()->AddTrack(track, {stream_1.get()});
3450 caller()->CreateAndSetAndSignalOffer();
3451 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3452 // Wait for one audio frame to be received by the callee.
3453 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
3454
3455 // Remove the sender, and create a new one with the new stream.
3456 caller()->pc()->RemoveTrack(sender);
3457 sender = caller()->pc()->AddTrack(track, {stream_2.get()});
3458 caller()->CreateAndSetAndSignalOffer();
3459 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3460 // Wait for additional audio frames to be received by the callee.
3461 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount, 0,
3462 kMaxWaitForFramesMs);
3463}
3464
Elad Alon99c3fe52017-10-13 16:29:40 +02003465TEST_F(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
3466 ASSERT_TRUE(CreatePeerConnectionWrappers());
3467 ConnectFakeSignaling();
3468
3469 auto output = rtc::MakeUnique<testing::NiceMock<MockRtcEventLogOutput>>();
3470 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
3471 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
3472 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
3473 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(std::move(output)));
3474
3475 caller()->AddAudioVideoMediaStream();
3476 caller()->CreateAndSetAndSignalOffer();
3477 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3478}
3479
Steve Antonede9ca52017-10-16 13:04:27 -07003480// Test that if candidates are only signaled by applying full session
3481// descriptions (instead of using AddIceCandidate), the peers can connect to
3482// each other and exchange media.
3483TEST_F(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
3484 ASSERT_TRUE(CreatePeerConnectionWrappers());
3485 // Each side will signal the session descriptions but not candidates.
3486 ConnectFakeSignalingForSdpOnly();
3487
3488 // Add audio video track and exchange the initial offer/answer with media
3489 // information only. This will start ICE gathering on each side.
3490 caller()->AddAudioVideoMediaStream();
3491 callee()->AddAudioVideoMediaStream();
3492 caller()->CreateAndSetAndSignalOffer();
3493
3494 // Wait for all candidates to be gathered on both the caller and callee.
3495 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
3496 caller()->ice_gathering_state(), kDefaultTimeout);
3497 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
3498 callee()->ice_gathering_state(), kDefaultTimeout);
3499
3500 // The candidates will now be included in the session description, so
3501 // signaling them will start the ICE connection.
3502 caller()->CreateAndSetAndSignalOffer();
3503 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3504
3505 // Ensure that media flows in both directions.
3506 ExpectNewFramesReceivedWithWait(
3507 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3508 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3509 kMaxWaitForFramesMs);
3510}
3511
deadbeef1dcb1642017-03-29 21:08:16 -07003512} // namespace
3513
3514#endif // if !defined(THREAD_SANITIZER)