blob: 8decc9603d421ab66a5e21ac8e8d303e824048ae [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
Karl Wiberg1b0eae32017-10-17 14:48:54 +020025#include "api/audio_codecs/builtin_audio_decoder_factory.h"
26#include "api/audio_codecs/builtin_audio_encoder_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "api/fakemetricsobserver.h"
28#include "api/mediastreaminterface.h"
29#include "api/peerconnectioninterface.h"
Steve Anton8c0f7a72017-10-03 10:03:10 -070030#include "api/peerconnectionproxy.h"
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +010031#include "api/rtpreceiverinterface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "api/test/fakeconstraints.h"
33#include "media/engine/fakewebrtcvideoengine.h"
34#include "p2p/base/p2pconstants.h"
35#include "p2p/base/portinterface.h"
Steve Antonede9ca52017-10-16 13:04:27 -070036#include "p2p/base/teststunserver.h"
Jonas Orelandbdcee282017-10-10 14:01:40 +020037#include "p2p/base/testturncustomizer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "p2p/base/testturnserver.h"
39#include "p2p/client/basicportallocator.h"
40#include "pc/dtmfsender.h"
41#include "pc/localaudiosource.h"
42#include "pc/mediasession.h"
43#include "pc/peerconnection.h"
44#include "pc/peerconnectionfactory.h"
Steve Anton4ab68ee2017-12-19 14:26:11 -080045#include "pc/sessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "pc/test/fakeaudiocapturemodule.h"
47#include "pc/test/fakeperiodicvideocapturer.h"
48#include "pc/test/fakertccertificategenerator.h"
49#include "pc/test/fakevideotrackrenderer.h"
50#include "pc/test/mockpeerconnectionobservers.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "rtc_base/fakenetwork.h"
Steve Antonede9ca52017-10-16 13:04:27 -070052#include "rtc_base/firewallsocketserver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020053#include "rtc_base/gunit.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020054#include "rtc_base/virtualsocketserver.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020055#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070056
57using cricket::ContentInfo;
58using cricket::FakeWebRtcVideoDecoder;
59using cricket::FakeWebRtcVideoDecoderFactory;
60using cricket::FakeWebRtcVideoEncoder;
61using cricket::FakeWebRtcVideoEncoderFactory;
62using cricket::MediaContentDescription;
Steve Antonede9ca52017-10-16 13:04:27 -070063using rtc::SocketAddress;
64using ::testing::ElementsAre;
65using ::testing::Values;
deadbeef1dcb1642017-03-29 21:08:16 -070066using webrtc::DataBuffer;
67using webrtc::DataChannelInterface;
68using webrtc::DtmfSender;
69using webrtc::DtmfSenderInterface;
70using webrtc::DtmfSenderObserverInterface;
71using webrtc::FakeConstraints;
Steve Anton15324772018-01-16 10:26:49 -080072using webrtc::FakeVideoTrackRenderer;
deadbeef1dcb1642017-03-29 21:08:16 -070073using webrtc::MediaConstraintsInterface;
74using webrtc::MediaStreamInterface;
75using webrtc::MediaStreamTrackInterface;
76using webrtc::MockCreateSessionDescriptionObserver;
77using webrtc::MockDataChannelObserver;
78using webrtc::MockSetSessionDescriptionObserver;
79using webrtc::MockStatsObserver;
80using webrtc::ObserverInterface;
Steve Anton8c0f7a72017-10-03 10:03:10 -070081using webrtc::PeerConnection;
deadbeef1dcb1642017-03-29 21:08:16 -070082using webrtc::PeerConnectionInterface;
83using webrtc::PeerConnectionFactory;
Steve Anton8c0f7a72017-10-03 10:03:10 -070084using webrtc::PeerConnectionProxy;
Steve Anton15324772018-01-16 10:26:49 -080085using webrtc::RTCErrorType;
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +010086using webrtc::RtpReceiverInterface;
Steve Antona3a92c22017-12-07 10:27:41 -080087using webrtc::SdpType;
deadbeef1dcb1642017-03-29 21:08:16 -070088using webrtc::SessionDescriptionInterface;
89using webrtc::StreamCollectionInterface;
Steve Anton15324772018-01-16 10:26:49 -080090using webrtc::VideoTrackInterface;
deadbeef1dcb1642017-03-29 21:08:16 -070091
92namespace {
93
94static const int kDefaultTimeout = 10000;
95static const int kMaxWaitForStatsMs = 3000;
96static const int kMaxWaitForActivationMs = 5000;
97static const int kMaxWaitForFramesMs = 10000;
98// Default number of audio/video frames to wait for before considering a test
99// successful.
100static const int kDefaultExpectedAudioFrameCount = 3;
101static const int kDefaultExpectedVideoFrameCount = 3;
102
deadbeef1dcb1642017-03-29 21:08:16 -0700103static const char kDataChannelLabel[] = "data_channel";
104
105// SRTP cipher name negotiated by the tests. This must be updated if the
106// default changes.
107static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_32;
108static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
109
Steve Antonede9ca52017-10-16 13:04:27 -0700110static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
111
deadbeef1dcb1642017-03-29 21:08:16 -0700112// Helper function for constructing offer/answer options to initiate an ICE
113// restart.
114PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
115 PeerConnectionInterface::RTCOfferAnswerOptions options;
116 options.ice_restart = true;
117 return options;
118}
119
deadbeefd8ad7882017-04-18 16:01:17 -0700120// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
121// attribute from received SDP, simulating a legacy endpoint.
122void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
123 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800124 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700125 }
126 desc->set_msid_supported(false);
127}
128
zhihuangf8164932017-05-19 13:09:47 -0700129int FindFirstMediaStatsIndexByKind(
130 const std::string& kind,
131 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
132 media_stats_vec) {
133 for (size_t i = 0; i < media_stats_vec.size(); i++) {
134 if (media_stats_vec[i]->kind.ValueToString() == kind) {
135 return i;
136 }
137 }
138 return -1;
139}
140
deadbeef1dcb1642017-03-29 21:08:16 -0700141class SignalingMessageReceiver {
142 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800143 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700144 virtual void ReceiveIceMessage(const std::string& sdp_mid,
145 int sdp_mline_index,
146 const std::string& msg) = 0;
147
148 protected:
149 SignalingMessageReceiver() {}
150 virtual ~SignalingMessageReceiver() {}
151};
152
153class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
154 public:
155 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
156 : expected_media_type_(media_type) {}
157
158 void OnFirstPacketReceived(cricket::MediaType media_type) override {
159 ASSERT_EQ(expected_media_type_, media_type);
160 first_packet_received_ = true;
161 }
162
163 bool first_packet_received() const { return first_packet_received_; }
164
165 virtual ~MockRtpReceiverObserver() {}
166
167 private:
168 bool first_packet_received_ = false;
169 cricket::MediaType expected_media_type_;
170};
171
172// Helper class that wraps a peer connection, observes it, and can accept
173// signaling messages from another wrapper.
174//
175// Uses a fake network, fake A/V capture, and optionally fake
176// encoders/decoders, though they aren't used by default since they don't
177// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700178// TODO(steveanton): See how this could become a subclass of
179// PeerConnectionWrapper defined in peerconnectionwrapper.h .
deadbeef1dcb1642017-03-29 21:08:16 -0700180class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800181 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700182 public:
183 // Different factory methods for convenience.
184 // TODO(deadbeef): Could use the pattern of:
185 //
186 // PeerConnectionWrapper =
187 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
188 //
189 // To reduce some code duplication.
190 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
191 const std::string& debug_name,
192 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
193 rtc::Thread* network_thread,
194 rtc::Thread* worker_thread) {
195 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
196 if (!client->Init(nullptr, nullptr, nullptr, std::move(cert_generator),
197 network_thread, worker_thread)) {
198 delete client;
199 return nullptr;
200 }
201 return client;
202 }
203
204 static PeerConnectionWrapper* CreateWithConfig(
205 const std::string& debug_name,
206 const PeerConnectionInterface::RTCConfiguration& config,
207 rtc::Thread* network_thread,
208 rtc::Thread* worker_thread) {
209 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
210 new FakeRTCCertificateGenerator());
211 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
212 if (!client->Init(nullptr, nullptr, &config, std::move(cert_generator),
213 network_thread, worker_thread)) {
214 delete client;
215 return nullptr;
216 }
217 return client;
218 }
219
220 static PeerConnectionWrapper* CreateWithOptions(
221 const std::string& debug_name,
222 const PeerConnectionFactory::Options& options,
223 rtc::Thread* network_thread,
224 rtc::Thread* worker_thread) {
225 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
226 new FakeRTCCertificateGenerator());
227 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
228 if (!client->Init(nullptr, &options, nullptr, std::move(cert_generator),
229 network_thread, worker_thread)) {
230 delete client;
231 return nullptr;
232 }
233 return client;
234 }
235
236 static PeerConnectionWrapper* CreateWithConstraints(
237 const std::string& debug_name,
238 const MediaConstraintsInterface* constraints,
239 rtc::Thread* network_thread,
240 rtc::Thread* worker_thread) {
241 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
242 new FakeRTCCertificateGenerator());
243 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
244 if (!client->Init(constraints, nullptr, nullptr, std::move(cert_generator),
245 network_thread, worker_thread)) {
246 delete client;
247 return nullptr;
248 }
249 return client;
250 }
251
deadbeef2f425aa2017-04-14 10:41:32 -0700252 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
253 return peer_connection_factory_.get();
254 }
255
deadbeef1dcb1642017-03-29 21:08:16 -0700256 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
257
258 // If a signaling message receiver is set (via ConnectFakeSignaling), this
259 // will set the whole offer/answer exchange in motion. Just need to wait for
260 // the signaling state to reach "stable".
261 void CreateAndSetAndSignalOffer() {
262 auto offer = CreateOffer();
263 ASSERT_NE(nullptr, offer);
264 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
265 }
266
267 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
268 // when a remote offer is received (via fake signaling) and an answer is
269 // generated. By default, uses default options.
270 void SetOfferAnswerOptions(
271 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
272 offer_answer_options_ = options;
273 }
274
275 // Set a callback to be invoked when SDP is received via the fake signaling
276 // channel, which provides an opportunity to munge (modify) the SDP. This is
277 // used to test SDP being applied that a PeerConnection would normally not
278 // generate, but a non-JSEP endpoint might.
279 void SetReceivedSdpMunger(
280 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100281 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700282 }
283
deadbeefc964d0b2017-04-03 10:03:35 -0700284 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700285 // generated.
286 void SetGeneratedSdpMunger(
287 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100288 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700289 }
290
Steve Antonede9ca52017-10-16 13:04:27 -0700291 // Every ICE connection state in order that has been seen by the observer.
292 std::vector<PeerConnectionInterface::IceConnectionState>
293 ice_connection_state_history() const {
294 return ice_connection_state_history_;
295 }
Steve Anton6f25b092017-10-23 09:39:20 -0700296 void clear_ice_connection_state_history() {
297 ice_connection_state_history_.clear();
298 }
Steve Antonede9ca52017-10-16 13:04:27 -0700299
300 // Every ICE gathering state in order that has been seen by the observer.
301 std::vector<PeerConnectionInterface::IceGatheringState>
302 ice_gathering_state_history() const {
303 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700304 }
305
Steve Anton15324772018-01-16 10:26:49 -0800306 void AddAudioVideoTracks() {
307 AddAudioTrack();
308 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700309 }
310
Steve Anton15324772018-01-16 10:26:49 -0800311 void AddAudioTrack() { AddTrack(CreateLocalAudioTrack()); }
deadbeef1dcb1642017-03-29 21:08:16 -0700312
Steve Anton15324772018-01-16 10:26:49 -0800313 void AddVideoTrack() { AddTrack(CreateLocalVideoTrack()); }
deadbeef1dcb1642017-03-29 21:08:16 -0700314
315 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
316 FakeConstraints constraints;
317 // Disable highpass filter so that we can get all the test audio frames.
318 constraints.AddMandatory(MediaConstraintsInterface::kHighpassFilter, false);
319 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
320 peer_connection_factory_->CreateAudioSource(&constraints);
321 // TODO(perkj): Test audio source when it is implemented. Currently audio
322 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700323 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700324 source);
325 }
326
327 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
deadbeefb1a15d72017-09-07 14:12:05 -0700328 return CreateLocalVideoTrackInternal(FakeConstraints(),
329 webrtc::kVideoRotation_0);
deadbeef1dcb1642017-03-29 21:08:16 -0700330 }
331
332 rtc::scoped_refptr<webrtc::VideoTrackInterface>
333 CreateLocalVideoTrackWithConstraints(const FakeConstraints& constraints) {
deadbeefb1a15d72017-09-07 14:12:05 -0700334 return CreateLocalVideoTrackInternal(constraints, webrtc::kVideoRotation_0);
deadbeef1dcb1642017-03-29 21:08:16 -0700335 }
336
337 rtc::scoped_refptr<webrtc::VideoTrackInterface>
338 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
deadbeefb1a15d72017-09-07 14:12:05 -0700339 return CreateLocalVideoTrackInternal(FakeConstraints(), rotation);
deadbeef1dcb1642017-03-29 21:08:16 -0700340 }
341
Steve Anton15324772018-01-16 10:26:49 -0800342 void AddTrack(rtc::scoped_refptr<MediaStreamTrackInterface> track,
343 const std::vector<std::string>& stream_labels = {}) {
344 auto result = pc()->AddTrack(track, stream_labels);
345 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
deadbeef1dcb1642017-03-29 21:08:16 -0700346 }
347
348 bool SignalingStateStable() {
349 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
350 }
351
352 void CreateDataChannel() { CreateDataChannel(nullptr); }
353
354 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700355 CreateDataChannel(kDataChannelLabel, init);
356 }
357
358 void CreateDataChannel(const std::string& label,
359 const webrtc::DataChannelInit* init) {
360 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700361 ASSERT_TRUE(data_channel_.get() != nullptr);
362 data_observer_.reset(new MockDataChannelObserver(data_channel_));
363 }
364
365 DataChannelInterface* data_channel() { return data_channel_; }
366 const MockDataChannelObserver* data_observer() const {
367 return data_observer_.get();
368 }
369
370 int audio_frames_received() const {
371 return fake_audio_capture_module_->frames_received();
372 }
373
374 // Takes minimum of video frames received for each track.
375 //
376 // Can be used like:
377 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
378 //
379 // To ensure that all video tracks received at least a certain number of
380 // frames.
381 int min_video_frames_received_per_track() const {
382 int min_frames = INT_MAX;
383 if (video_decoder_factory_enabled_) {
384 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
385 fake_video_decoder_factory_->decoders();
386 if (decoders.empty()) {
387 return 0;
388 }
389 for (FakeWebRtcVideoDecoder* decoder : decoders) {
390 min_frames = std::min(min_frames, decoder->GetNumFramesReceived());
391 }
392 return min_frames;
393 } else {
394 if (fake_video_renderers_.empty()) {
395 return 0;
396 }
397
398 for (const auto& pair : fake_video_renderers_) {
399 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
400 }
401 return min_frames;
402 }
403 }
404
405 // In contrast to the above, sums the video frames received for all tracks.
406 // Can be used to verify that no video frames were received, or that the
407 // counts didn't increase.
408 int total_video_frames_received() const {
409 int total = 0;
410 if (video_decoder_factory_enabled_) {
411 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
412 fake_video_decoder_factory_->decoders();
413 for (const FakeWebRtcVideoDecoder* decoder : decoders) {
414 total += decoder->GetNumFramesReceived();
415 }
416 } else {
417 for (const auto& pair : fake_video_renderers_) {
418 total += pair.second->num_rendered_frames();
419 }
420 for (const auto& renderer : removed_fake_video_renderers_) {
421 total += renderer->num_rendered_frames();
422 }
423 }
424 return total;
425 }
426
427 // Returns a MockStatsObserver in a state after stats gathering finished,
428 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700429 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700430 webrtc::MediaStreamTrackInterface* track) {
431 rtc::scoped_refptr<MockStatsObserver> observer(
432 new rtc::RefCountedObject<MockStatsObserver>());
433 EXPECT_TRUE(peer_connection_->GetStats(
434 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
435 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
436 return observer;
437 }
438
439 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700440 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
441 return OldGetStatsForTrack(nullptr);
442 }
443
444 // Synchronously gets stats and returns them. If it times out, fails the test
445 // and returns null.
446 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
447 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
448 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
449 peer_connection_->GetStats(callback);
450 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
451 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700452 }
453
454 int rendered_width() {
455 EXPECT_FALSE(fake_video_renderers_.empty());
456 return fake_video_renderers_.empty()
457 ? 0
458 : fake_video_renderers_.begin()->second->width();
459 }
460
461 int rendered_height() {
462 EXPECT_FALSE(fake_video_renderers_.empty());
463 return fake_video_renderers_.empty()
464 ? 0
465 : fake_video_renderers_.begin()->second->height();
466 }
467
468 double rendered_aspect_ratio() {
469 if (rendered_height() == 0) {
470 return 0.0;
471 }
472 return static_cast<double>(rendered_width()) / rendered_height();
473 }
474
475 webrtc::VideoRotation rendered_rotation() {
476 EXPECT_FALSE(fake_video_renderers_.empty());
477 return fake_video_renderers_.empty()
478 ? webrtc::kVideoRotation_0
479 : fake_video_renderers_.begin()->second->rotation();
480 }
481
482 int local_rendered_width() {
483 return local_video_renderer_ ? local_video_renderer_->width() : 0;
484 }
485
486 int local_rendered_height() {
487 return local_video_renderer_ ? local_video_renderer_->height() : 0;
488 }
489
490 double local_rendered_aspect_ratio() {
491 if (local_rendered_height() == 0) {
492 return 0.0;
493 }
494 return static_cast<double>(local_rendered_width()) /
495 local_rendered_height();
496 }
497
498 size_t number_of_remote_streams() {
499 if (!pc()) {
500 return 0;
501 }
502 return pc()->remote_streams()->count();
503 }
504
505 StreamCollectionInterface* remote_streams() const {
506 if (!pc()) {
507 ADD_FAILURE();
508 return nullptr;
509 }
510 return pc()->remote_streams();
511 }
512
513 StreamCollectionInterface* local_streams() {
514 if (!pc()) {
515 ADD_FAILURE();
516 return nullptr;
517 }
518 return pc()->local_streams();
519 }
520
521 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
522 return pc()->signaling_state();
523 }
524
525 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
526 return pc()->ice_connection_state();
527 }
528
529 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
530 return pc()->ice_gathering_state();
531 }
532
533 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
534 // GetReceivers. They're updated automatically when a remote offer/answer
535 // from the fake signaling channel is applied, or when
536 // ResetRtpReceiverObservers below is called.
537 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
538 rtp_receiver_observers() {
539 return rtp_receiver_observers_;
540 }
541
542 void ResetRtpReceiverObservers() {
543 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100544 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
545 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700546 std::unique_ptr<MockRtpReceiverObserver> observer(
547 new MockRtpReceiverObserver(receiver->media_type()));
548 receiver->SetObserver(observer.get());
549 rtp_receiver_observers_.push_back(std::move(observer));
550 }
551 }
552
Steve Antonede9ca52017-10-16 13:04:27 -0700553 rtc::FakeNetworkManager* network() const {
554 return fake_network_manager_.get();
555 }
556 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
557
deadbeef1dcb1642017-03-29 21:08:16 -0700558 private:
559 explicit PeerConnectionWrapper(const std::string& debug_name)
560 : debug_name_(debug_name) {}
561
562 bool Init(
563 const MediaConstraintsInterface* constraints,
564 const PeerConnectionFactory::Options* options,
565 const PeerConnectionInterface::RTCConfiguration* config,
566 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
567 rtc::Thread* network_thread,
568 rtc::Thread* worker_thread) {
569 // There's an error in this test code if Init ends up being called twice.
570 RTC_DCHECK(!peer_connection_);
571 RTC_DCHECK(!peer_connection_factory_);
572
573 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700574 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700575
576 std::unique_ptr<cricket::PortAllocator> port_allocator(
577 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700578 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700579 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
580 if (!fake_audio_capture_module_) {
581 return false;
582 }
583 // Note that these factories don't end up getting used unless supported
584 // codecs are added to them.
585 fake_video_decoder_factory_ = new FakeWebRtcVideoDecoderFactory();
586 fake_video_encoder_factory_ = new FakeWebRtcVideoEncoderFactory();
587 rtc::Thread* const signaling_thread = rtc::Thread::Current();
588 peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(
589 network_thread, worker_thread, signaling_thread,
Karl Wiberg1b0eae32017-10-17 14:48:54 +0200590 fake_audio_capture_module_, webrtc::CreateBuiltinAudioEncoderFactory(),
591 webrtc::CreateBuiltinAudioDecoderFactory(), fake_video_encoder_factory_,
deadbeef1dcb1642017-03-29 21:08:16 -0700592 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) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100669 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800670 std::unique_ptr<SessionDescriptionInterface> desc =
671 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700672 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) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100686 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800687 std::unique_ptr<SessionDescriptionInterface> desc =
688 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700689 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(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100715 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700716 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>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100736 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800737 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700738 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>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100751 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700752 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).
Steve Antona3a92c22017-12-07 10:27:41 -0800759 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700760 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
Steve Antona3a92c22017-12-07 10:27:41 -0800771 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700772 if (signaling_message_receiver_) {
773 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
774 }
775 }
776
777 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
778 // default).
779 void SendIceMessage(const std::string& sdp_mid,
780 int sdp_mline_index,
781 const std::string& msg) {
782 if (signaling_delay_ms_ == 0) {
783 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
784 } else {
785 invoker_.AsyncInvokeDelayed<void>(
786 RTC_FROM_HERE, rtc::Thread::Current(),
787 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
788 this, sdp_mid, sdp_mline_index, msg),
789 signaling_delay_ms_);
790 }
791 }
792
793 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
794 int sdp_mline_index,
795 const std::string& msg) {
796 if (signaling_message_receiver_) {
797 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
798 msg);
799 }
800 }
801
802 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800803 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
804 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700805 HandleIncomingOffer(msg);
806 } else {
807 HandleIncomingAnswer(msg);
808 }
809 }
810
811 void ReceiveIceMessage(const std::string& sdp_mid,
812 int sdp_mline_index,
813 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100814 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700815 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
816 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
817 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
818 }
819
820 // PeerConnectionObserver callbacks.
821 void OnSignalingChange(
822 webrtc::PeerConnectionInterface::SignalingState new_state) override {
823 EXPECT_EQ(pc()->signaling_state(), new_state);
824 }
Steve Anton15324772018-01-16 10:26:49 -0800825 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
826 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
827 streams) override {
828 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
829 rtc::scoped_refptr<VideoTrackInterface> video_track(
830 static_cast<VideoTrackInterface*>(receiver->track().get()));
831 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700832 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800833 fake_video_renderers_[video_track->id()] =
834 rtc::MakeUnique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700835 }
836 }
Steve Anton15324772018-01-16 10:26:49 -0800837 void OnRemoveTrack(
838 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
839 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
840 auto it = fake_video_renderers_.find(receiver->track()->id());
841 RTC_DCHECK(it != fake_video_renderers_.end());
842 fake_video_renderers_.erase(it);
843 }
844 }
deadbeef1dcb1642017-03-29 21:08:16 -0700845 void OnRenegotiationNeeded() override {}
846 void OnIceConnectionChange(
847 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
848 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700849 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700850 }
851 void OnIceGatheringChange(
852 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700853 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700854 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700855 }
856 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100857 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700858
859 std::string ice_sdp;
860 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700861 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700862 // Remote party may be deleted.
863 return;
864 }
865 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
866 }
867 void OnDataChannel(
868 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100869 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700870 data_channel_ = data_channel;
871 data_observer_.reset(new MockDataChannelObserver(data_channel));
872 }
873
deadbeef1dcb1642017-03-29 21:08:16 -0700874 std::string debug_name_;
875
876 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
877
878 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
879 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
880 peer_connection_factory_;
881
Steve Antonede9ca52017-10-16 13:04:27 -0700882 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700883 // Needed to keep track of number of frames sent.
884 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
885 // Needed to keep track of number of frames received.
886 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
887 fake_video_renderers_;
888 // Needed to ensure frames aren't received for removed tracks.
889 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
890 removed_fake_video_renderers_;
891 // Needed to keep track of number of frames received when external decoder
892 // used.
893 FakeWebRtcVideoDecoderFactory* fake_video_decoder_factory_ = nullptr;
894 FakeWebRtcVideoEncoderFactory* fake_video_encoder_factory_ = nullptr;
895 bool video_decoder_factory_enabled_ = false;
896
897 // For remote peer communication.
898 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
899 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -0700900 bool signal_ice_candidates_ = true;
deadbeef1dcb1642017-03-29 21:08:16 -0700901
902 // Store references to the video capturers we've created, so that we can stop
903 // them, if required.
904 std::vector<cricket::FakeVideoCapturer*> video_capturers_;
905 // |local_video_renderer_| attached to the first created local video track.
906 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
907
908 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
909 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
910 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
911
912 rtc::scoped_refptr<DataChannelInterface> data_channel_;
913 std::unique_ptr<MockDataChannelObserver> data_observer_;
914
915 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
916
Steve Antonede9ca52017-10-16 13:04:27 -0700917 std::vector<PeerConnectionInterface::IceConnectionState>
918 ice_connection_state_history_;
919 std::vector<PeerConnectionInterface::IceGatheringState>
920 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700921
922 rtc::AsyncInvoker invoker_;
923
924 friend class PeerConnectionIntegrationTest;
925};
926
Elad Alon99c3fe52017-10-13 16:29:40 +0200927class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
928 public:
929 virtual ~MockRtcEventLogOutput() = default;
930 MOCK_CONST_METHOD0(IsActive, bool());
931 MOCK_METHOD1(Write, bool(const std::string&));
932};
933
deadbeef1dcb1642017-03-29 21:08:16 -0700934// Tests two PeerConnections connecting to each other end-to-end, using a
935// virtual network, fake A/V capture and fake encoder/decoders. The
936// PeerConnections share the threads/socket servers, but use separate versions
937// of everything else (including "PeerConnectionFactory"s).
938class PeerConnectionIntegrationTest : public testing::Test {
939 public:
940 PeerConnectionIntegrationTest()
deadbeef98e186c2017-05-16 18:00:06 -0700941 : ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -0700942 fss_(new rtc::FirewallSocketServer(ss_.get())),
943 network_thread_(new rtc::Thread(fss_.get())),
deadbeef1dcb1642017-03-29 21:08:16 -0700944 worker_thread_(rtc::Thread::Create()) {
945 RTC_CHECK(network_thread_->Start());
946 RTC_CHECK(worker_thread_->Start());
947 }
948
949 ~PeerConnectionIntegrationTest() {
950 if (caller_) {
951 caller_->set_signaling_message_receiver(nullptr);
952 }
953 if (callee_) {
954 callee_->set_signaling_message_receiver(nullptr);
955 }
956 }
957
958 bool SignalingStateStable() {
959 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
960 }
961
deadbeef71452802017-05-07 17:21:01 -0700962 bool DtlsConnected() {
963 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
964 // are connected. This is an important distinction. Once we have separate
965 // ICE and DTLS state, this check needs to use the DTLS state.
966 return (callee()->ice_connection_state() ==
967 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
968 callee()->ice_connection_state() ==
969 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
970 (caller()->ice_connection_state() ==
971 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
972 caller()->ice_connection_state() ==
973 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
974 }
975
deadbeef1dcb1642017-03-29 21:08:16 -0700976 bool CreatePeerConnectionWrappers() {
977 return CreatePeerConnectionWrappersWithConfig(
978 PeerConnectionInterface::RTCConfiguration(),
979 PeerConnectionInterface::RTCConfiguration());
980 }
981
982 bool CreatePeerConnectionWrappersWithConstraints(
983 MediaConstraintsInterface* caller_constraints,
984 MediaConstraintsInterface* callee_constraints) {
985 caller_.reset(PeerConnectionWrapper::CreateWithConstraints(
986 "Caller", caller_constraints, network_thread_.get(),
987 worker_thread_.get()));
988 callee_.reset(PeerConnectionWrapper::CreateWithConstraints(
989 "Callee", callee_constraints, network_thread_.get(),
990 worker_thread_.get()));
991 return caller_ && callee_;
992 }
993
994 bool CreatePeerConnectionWrappersWithConfig(
995 const PeerConnectionInterface::RTCConfiguration& caller_config,
996 const PeerConnectionInterface::RTCConfiguration& callee_config) {
997 caller_.reset(PeerConnectionWrapper::CreateWithConfig(
998 "Caller", caller_config, network_thread_.get(), worker_thread_.get()));
999 callee_.reset(PeerConnectionWrapper::CreateWithConfig(
1000 "Callee", callee_config, network_thread_.get(), worker_thread_.get()));
1001 return caller_ && callee_;
1002 }
1003
1004 bool CreatePeerConnectionWrappersWithOptions(
1005 const PeerConnectionFactory::Options& caller_options,
1006 const PeerConnectionFactory::Options& callee_options) {
1007 caller_.reset(PeerConnectionWrapper::CreateWithOptions(
1008 "Caller", caller_options, network_thread_.get(), worker_thread_.get()));
1009 callee_.reset(PeerConnectionWrapper::CreateWithOptions(
1010 "Callee", callee_options, network_thread_.get(), worker_thread_.get()));
1011 return caller_ && callee_;
1012 }
1013
1014 PeerConnectionWrapper* CreatePeerConnectionWrapperWithAlternateKey() {
1015 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1016 new FakeRTCCertificateGenerator());
1017 cert_generator->use_alternate_key();
1018
1019 // Make sure the new client is using a different certificate.
1020 return PeerConnectionWrapper::CreateWithDtlsIdentityStore(
1021 "New Peer", std::move(cert_generator), network_thread_.get(),
1022 worker_thread_.get());
1023 }
1024
1025 // Once called, SDP blobs and ICE candidates will be automatically signaled
1026 // between PeerConnections.
1027 void ConnectFakeSignaling() {
1028 caller_->set_signaling_message_receiver(callee_.get());
1029 callee_->set_signaling_message_receiver(caller_.get());
1030 }
1031
Steve Antonede9ca52017-10-16 13:04:27 -07001032 // Once called, SDP blobs will be automatically signaled between
1033 // PeerConnections. Note that ICE candidates will not be signaled unless they
1034 // are in the exchanged SDP blobs.
1035 void ConnectFakeSignalingForSdpOnly() {
1036 ConnectFakeSignaling();
1037 SetSignalIceCandidates(false);
1038 }
1039
deadbeef1dcb1642017-03-29 21:08:16 -07001040 void SetSignalingDelayMs(int delay_ms) {
1041 caller_->set_signaling_delay_ms(delay_ms);
1042 callee_->set_signaling_delay_ms(delay_ms);
1043 }
1044
Steve Antonede9ca52017-10-16 13:04:27 -07001045 void SetSignalIceCandidates(bool signal) {
1046 caller_->set_signal_ice_candidates(signal);
1047 callee_->set_signal_ice_candidates(signal);
1048 }
1049
deadbeef1dcb1642017-03-29 21:08:16 -07001050 void EnableVideoDecoderFactory() {
1051 caller_->EnableVideoDecoderFactory();
1052 callee_->EnableVideoDecoderFactory();
1053 }
1054
1055 // Messages may get lost on the unreliable DataChannel, so we send multiple
1056 // times to avoid test flakiness.
1057 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1058 const std::string& data,
1059 int retries) {
1060 for (int i = 0; i < retries; ++i) {
1061 dc->Send(DataBuffer(data));
1062 }
1063 }
1064
1065 rtc::Thread* network_thread() { return network_thread_.get(); }
1066
1067 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1068
1069 PeerConnectionWrapper* caller() { return caller_.get(); }
1070
1071 // Set the |caller_| to the |wrapper| passed in and return the
1072 // original |caller_|.
1073 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1074 PeerConnectionWrapper* wrapper) {
1075 PeerConnectionWrapper* old = caller_.release();
1076 caller_.reset(wrapper);
1077 return old;
1078 }
1079
1080 PeerConnectionWrapper* callee() { return callee_.get(); }
1081
1082 // Set the |callee_| to the |wrapper| passed in and return the
1083 // original |callee_|.
1084 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1085 PeerConnectionWrapper* wrapper) {
1086 PeerConnectionWrapper* old = callee_.release();
1087 callee_.reset(wrapper);
1088 return old;
1089 }
1090
Steve Antonede9ca52017-10-16 13:04:27 -07001091 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1092
deadbeef1dcb1642017-03-29 21:08:16 -07001093 // Expects the provided number of new frames to be received within |wait_ms|.
1094 // "New frames" meaning that it waits for the current frame counts to
1095 // *increase* by the provided values. For video, uses
1096 // RecievedVideoFramesForEachTrack for the case of multiple video tracks
1097 // being received.
1098 void ExpectNewFramesReceivedWithWait(
1099 int expected_caller_received_audio_frames,
1100 int expected_caller_received_video_frames,
1101 int expected_callee_received_audio_frames,
1102 int expected_callee_received_video_frames,
1103 int wait_ms) {
1104 // Add current frame counts to the provided values, in order to wait for
1105 // the frame count to increase.
1106 expected_caller_received_audio_frames += caller()->audio_frames_received();
1107 expected_caller_received_video_frames +=
1108 caller()->min_video_frames_received_per_track();
1109 expected_callee_received_audio_frames += callee()->audio_frames_received();
1110 expected_callee_received_video_frames +=
1111 callee()->min_video_frames_received_per_track();
1112
1113 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
1114 expected_caller_received_audio_frames &&
1115 caller()->min_video_frames_received_per_track() >=
1116 expected_caller_received_video_frames &&
1117 callee()->audio_frames_received() >=
1118 expected_callee_received_audio_frames &&
1119 callee()->min_video_frames_received_per_track() >=
1120 expected_callee_received_video_frames,
1121 wait_ms);
1122
1123 // After the combined wait, do an "expect" for each individual count, to
1124 // print out a more detailed message upon failure.
1125 EXPECT_GE(caller()->audio_frames_received(),
1126 expected_caller_received_audio_frames);
1127 EXPECT_GE(caller()->min_video_frames_received_per_track(),
1128 expected_caller_received_video_frames);
1129 EXPECT_GE(callee()->audio_frames_received(),
1130 expected_callee_received_audio_frames);
1131 EXPECT_GE(callee()->min_video_frames_received_per_track(),
1132 expected_callee_received_video_frames);
1133 }
1134
1135 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1136 bool remote_gcm_enabled,
1137 int expected_cipher_suite) {
1138 PeerConnectionFactory::Options caller_options;
1139 caller_options.crypto_options.enable_gcm_crypto_suites = local_gcm_enabled;
1140 PeerConnectionFactory::Options callee_options;
1141 callee_options.crypto_options.enable_gcm_crypto_suites = remote_gcm_enabled;
1142 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1143 callee_options));
1144 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1145 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1146 caller()->pc()->RegisterUMAObserver(caller_observer);
1147 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001148 caller()->AddAudioVideoTracks();
1149 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001150 caller()->CreateAndSetAndSignalOffer();
1151 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1152 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001153 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001154 EXPECT_EQ(
1155 1, caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1156 expected_cipher_suite));
1157 caller()->pc()->RegisterUMAObserver(nullptr);
1158 }
1159
1160 private:
1161 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001162 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001163 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001164 // |network_thread_| and |worker_thread_| are used by both
1165 // |caller_| and |callee_| so they must be destroyed
1166 // later.
1167 std::unique_ptr<rtc::Thread> network_thread_;
1168 std::unique_ptr<rtc::Thread> worker_thread_;
1169 std::unique_ptr<PeerConnectionWrapper> caller_;
1170 std::unique_ptr<PeerConnectionWrapper> callee_;
1171};
1172
1173// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1174// includes testing that the callback is invoked if an observer is connected
1175// after the first packet has already been received.
1176TEST_F(PeerConnectionIntegrationTest,
1177 RtpReceiverObserverOnFirstPacketReceived) {
1178 ASSERT_TRUE(CreatePeerConnectionWrappers());
1179 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001180 caller()->AddAudioVideoTracks();
1181 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001182 // Start offer/answer exchange and wait for it to complete.
1183 caller()->CreateAndSetAndSignalOffer();
1184 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1185 // Should be one receiver each for audio/video.
1186 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1187 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1188 // Wait for all "first packet received" callbacks to be fired.
1189 EXPECT_TRUE_WAIT(
1190 std::all_of(caller()->rtp_receiver_observers().begin(),
1191 caller()->rtp_receiver_observers().end(),
1192 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1193 return o->first_packet_received();
1194 }),
1195 kMaxWaitForFramesMs);
1196 EXPECT_TRUE_WAIT(
1197 std::all_of(callee()->rtp_receiver_observers().begin(),
1198 callee()->rtp_receiver_observers().end(),
1199 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1200 return o->first_packet_received();
1201 }),
1202 kMaxWaitForFramesMs);
1203 // If new observers are set after the first packet was already received, the
1204 // callback should still be invoked.
1205 caller()->ResetRtpReceiverObservers();
1206 callee()->ResetRtpReceiverObservers();
1207 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1208 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1209 EXPECT_TRUE(
1210 std::all_of(caller()->rtp_receiver_observers().begin(),
1211 caller()->rtp_receiver_observers().end(),
1212 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1213 return o->first_packet_received();
1214 }));
1215 EXPECT_TRUE(
1216 std::all_of(callee()->rtp_receiver_observers().begin(),
1217 callee()->rtp_receiver_observers().end(),
1218 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1219 return o->first_packet_received();
1220 }));
1221}
1222
1223class DummyDtmfObserver : public DtmfSenderObserverInterface {
1224 public:
1225 DummyDtmfObserver() : completed_(false) {}
1226
1227 // Implements DtmfSenderObserverInterface.
1228 void OnToneChange(const std::string& tone) override {
1229 tones_.push_back(tone);
1230 if (tone.empty()) {
1231 completed_ = true;
1232 }
1233 }
1234
1235 const std::vector<std::string>& tones() const { return tones_; }
1236 bool completed() const { return completed_; }
1237
1238 private:
1239 bool completed_;
1240 std::vector<std::string> tones_;
1241};
1242
1243// Assumes |sender| already has an audio track added and the offer/answer
1244// exchange is done.
1245void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1246 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001247 // We should be able to get a DTMF sender from the local sender.
1248 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1249 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1250 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001251 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001252 dtmf_sender->RegisterObserver(&observer);
1253
1254 // Test the DtmfSender object just created.
1255 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1256 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1257
1258 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1259 std::vector<std::string> tones = {"1", "a", ""};
1260 EXPECT_EQ(tones, observer.tones());
1261 dtmf_sender->UnregisterObserver();
1262 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1263}
1264
1265// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1266// direction).
1267TEST_F(PeerConnectionIntegrationTest, DtmfSenderObserver) {
1268 ASSERT_TRUE(CreatePeerConnectionWrappers());
1269 ConnectFakeSignaling();
1270 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001271 caller()->AddAudioTrack();
1272 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001273 caller()->CreateAndSetAndSignalOffer();
1274 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001275 // DTLS must finish before the DTMF sender can be used reliably.
1276 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001277 TestDtmfFromSenderToReceiver(caller(), callee());
1278 TestDtmfFromSenderToReceiver(callee(), caller());
1279}
1280
1281// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1282// between two connections, using DTLS-SRTP.
1283TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
1284 ASSERT_TRUE(CreatePeerConnectionWrappers());
1285 ConnectFakeSignaling();
1286 // Do normal offer/answer and wait for some frames to be received in each
1287 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001288 caller()->AddAudioVideoTracks();
1289 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001290 caller()->CreateAndSetAndSignalOffer();
1291 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1292 ExpectNewFramesReceivedWithWait(
1293 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1294 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1295 kMaxWaitForFramesMs);
1296}
1297
1298// Uses SDES instead of DTLS for key agreement.
1299TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
1300 PeerConnectionInterface::RTCConfiguration sdes_config;
1301 sdes_config.enable_dtls_srtp.emplace(false);
1302 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1303 ConnectFakeSignaling();
1304
1305 // Do normal offer/answer and wait for some frames to be received in each
1306 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001307 caller()->AddAudioVideoTracks();
1308 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001309 caller()->CreateAndSetAndSignalOffer();
1310 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1311 ExpectNewFramesReceivedWithWait(
1312 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1313 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1314 kMaxWaitForFramesMs);
1315}
1316
Steve Anton8c0f7a72017-10-03 10:03:10 -07001317// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1318// certificate once the DTLS handshake has finished.
1319TEST_F(PeerConnectionIntegrationTest,
1320 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1321 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1322 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1323 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1324 return pc->GetRemoteAudioSSLCertificate();
1325 };
1326
1327 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1328 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1329
1330 // Configure each side with a known certificate so they can be compared later.
1331 PeerConnectionInterface::RTCConfiguration caller_config;
1332 caller_config.enable_dtls_srtp.emplace(true);
1333 caller_config.certificates.push_back(caller_cert);
1334 PeerConnectionInterface::RTCConfiguration callee_config;
1335 callee_config.enable_dtls_srtp.emplace(true);
1336 callee_config.certificates.push_back(callee_cert);
1337 ASSERT_TRUE(
1338 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1339 ConnectFakeSignaling();
1340
1341 // When first initialized, there should not be a remote SSL certificate (and
1342 // calling this method should not crash).
1343 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1344 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
1345
Steve Anton15324772018-01-16 10:26:49 -08001346 caller()->AddAudioTrack();
1347 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001348 caller()->CreateAndSetAndSignalOffer();
1349 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1350 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1351
1352 // Once DTLS has been connected, each side should return the other's SSL
1353 // certificate when calling GetRemoteAudioSSLCertificate.
1354
1355 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1356 ASSERT_TRUE(caller_remote_cert);
1357 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1358 caller_remote_cert->ToPEMString());
1359
1360 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1361 ASSERT_TRUE(callee_remote_cert);
1362 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1363 callee_remote_cert->ToPEMString());
1364}
1365
deadbeef1dcb1642017-03-29 21:08:16 -07001366// This test sets up a call between two parties (using DTLS) and tests that we
1367// can get a video aspect ratio of 16:9.
1368TEST_F(PeerConnectionIntegrationTest, SendAndReceive16To9AspectRatio) {
1369 ASSERT_TRUE(CreatePeerConnectionWrappers());
1370 ConnectFakeSignaling();
1371
1372 // Add video tracks with 16:9 constraint.
1373 FakeConstraints constraints;
1374 double requested_ratio = 16.0 / 9;
1375 constraints.SetMandatoryMinAspectRatio(requested_ratio);
Steve Anton15324772018-01-16 10:26:49 -08001376 caller()->AddTrack(
1377 caller()->CreateLocalVideoTrackWithConstraints(constraints));
1378 callee()->AddTrack(
1379 callee()->CreateLocalVideoTrackWithConstraints(constraints));
deadbeef1dcb1642017-03-29 21:08:16 -07001380
1381 // Do normal offer/answer and wait for at least one frame to be received in
1382 // each direction.
1383 caller()->CreateAndSetAndSignalOffer();
1384 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1385 callee()->min_video_frames_received_per_track() > 0,
1386 kMaxWaitForFramesMs);
1387
1388 // Check rendered aspect ratio.
1389 EXPECT_EQ(requested_ratio, caller()->local_rendered_aspect_ratio());
1390 EXPECT_EQ(requested_ratio, caller()->rendered_aspect_ratio());
1391 EXPECT_EQ(requested_ratio, callee()->local_rendered_aspect_ratio());
1392 EXPECT_EQ(requested_ratio, callee()->rendered_aspect_ratio());
1393}
1394
1395// This test sets up a call between two parties with a source resolution of
1396// 1280x720 and verifies that a 16:9 aspect ratio is received.
1397TEST_F(PeerConnectionIntegrationTest,
1398 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1399 ASSERT_TRUE(CreatePeerConnectionWrappers());
1400 ConnectFakeSignaling();
1401
1402 // Similar to above test, but uses MandatoryMin[Width/Height] constraint
1403 // instead of aspect ratio constraint.
1404 FakeConstraints constraints;
1405 constraints.SetMandatoryMinWidth(1280);
1406 constraints.SetMandatoryMinHeight(720);
Steve Anton15324772018-01-16 10:26:49 -08001407 caller()->AddTrack(
1408 caller()->CreateLocalVideoTrackWithConstraints(constraints));
1409 callee()->AddTrack(
1410 callee()->CreateLocalVideoTrackWithConstraints(constraints));
deadbeef1dcb1642017-03-29 21:08:16 -07001411
1412 // Do normal offer/answer and wait for at least one frame to be received in
1413 // each direction.
1414 caller()->CreateAndSetAndSignalOffer();
1415 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1416 callee()->min_video_frames_received_per_track() > 0,
1417 kMaxWaitForFramesMs);
1418
1419 // Check rendered aspect ratio.
1420 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1421 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1422 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1423 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1424}
1425
1426// This test sets up an one-way call, with media only from caller to
1427// callee.
1428TEST_F(PeerConnectionIntegrationTest, OneWayMediaCall) {
1429 ASSERT_TRUE(CreatePeerConnectionWrappers());
1430 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001431 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001432 caller()->CreateAndSetAndSignalOffer();
1433 int caller_received_frames = 0;
1434 ExpectNewFramesReceivedWithWait(
1435 caller_received_frames, caller_received_frames,
1436 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1437 kMaxWaitForFramesMs);
1438}
1439
1440// This test sets up a audio call initially, with the callee rejecting video
1441// initially. Then later the callee decides to upgrade to audio/video, and
1442// initiates a new offer/answer exchange.
1443TEST_F(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
1444 ASSERT_TRUE(CreatePeerConnectionWrappers());
1445 ConnectFakeSignaling();
1446 // Initially, offer an audio/video stream from the caller, but refuse to
1447 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001448 caller()->AddAudioVideoTracks();
1449 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001450 PeerConnectionInterface::RTCOfferAnswerOptions options;
1451 options.offer_to_receive_video = 0;
1452 callee()->SetOfferAnswerOptions(options);
1453 // Do offer/answer and make sure audio is still received end-to-end.
1454 caller()->CreateAndSetAndSignalOffer();
1455 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1456 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1457 kDefaultExpectedAudioFrameCount, 0,
1458 kMaxWaitForFramesMs);
1459 // Sanity check that the callee's description has a rejected video section.
1460 ASSERT_NE(nullptr, callee()->pc()->local_description());
1461 const ContentInfo* callee_video_content =
1462 GetFirstVideoContent(callee()->pc()->local_description()->description());
1463 ASSERT_NE(nullptr, callee_video_content);
1464 EXPECT_TRUE(callee_video_content->rejected);
1465 // Now negotiate with video and ensure negotiation succeeds, with video
1466 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001467 callee()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001468 options.offer_to_receive_video = 1;
1469 callee()->SetOfferAnswerOptions(options);
1470 callee()->CreateAndSetAndSignalOffer();
1471 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1472 // Expect additional audio frames to be received after the upgrade.
1473 ExpectNewFramesReceivedWithWait(
1474 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1475 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1476 kMaxWaitForFramesMs);
1477}
1478
deadbeef4389b4d2017-09-07 09:07:36 -07001479// Simpler than the above test; just add an audio track to an established
1480// video-only connection.
1481TEST_F(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
1482 ASSERT_TRUE(CreatePeerConnectionWrappers());
1483 ConnectFakeSignaling();
1484 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08001485 caller()->AddVideoTrack();
1486 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001487 caller()->CreateAndSetAndSignalOffer();
1488 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1489 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08001490 caller()->AddAudioTrack();
1491 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001492 caller()->CreateAndSetAndSignalOffer();
1493 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1494 // Ensure both audio and video frames are received end-to-end.
1495 ExpectNewFramesReceivedWithWait(
1496 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1497 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1498 kMaxWaitForFramesMs);
1499}
1500
deadbeef1dcb1642017-03-29 21:08:16 -07001501// This test sets up a call that's transferred to a new caller with a different
1502// DTLS fingerprint.
1503TEST_F(PeerConnectionIntegrationTest, CallTransferredForCallee) {
1504 ASSERT_TRUE(CreatePeerConnectionWrappers());
1505 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001506 caller()->AddAudioVideoTracks();
1507 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001508 caller()->CreateAndSetAndSignalOffer();
1509 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1510
1511 // Keep the original peer around which will still send packets to the
1512 // receiving client. These SRTP packets will be dropped.
1513 std::unique_ptr<PeerConnectionWrapper> original_peer(
1514 SetCallerPcWrapperAndReturnCurrent(
1515 CreatePeerConnectionWrapperWithAlternateKey()));
1516 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1517 // directly above.
1518 original_peer->pc()->Close();
1519
1520 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001521 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001522 caller()->CreateAndSetAndSignalOffer();
1523 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1524 // Wait for some additional frames to be transmitted end-to-end.
1525 ExpectNewFramesReceivedWithWait(
1526 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1527 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1528 kMaxWaitForFramesMs);
1529}
1530
1531// This test sets up a call that's transferred to a new callee with a different
1532// DTLS fingerprint.
1533TEST_F(PeerConnectionIntegrationTest, CallTransferredForCaller) {
1534 ASSERT_TRUE(CreatePeerConnectionWrappers());
1535 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001536 caller()->AddAudioVideoTracks();
1537 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001538 caller()->CreateAndSetAndSignalOffer();
1539 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1540
1541 // Keep the original peer around which will still send packets to the
1542 // receiving client. These SRTP packets will be dropped.
1543 std::unique_ptr<PeerConnectionWrapper> original_peer(
1544 SetCalleePcWrapperAndReturnCurrent(
1545 CreatePeerConnectionWrapperWithAlternateKey()));
1546 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1547 // directly above.
1548 original_peer->pc()->Close();
1549
1550 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001551 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001552 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1553 caller()->CreateAndSetAndSignalOffer();
1554 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1555 // Wait for some additional frames to be transmitted end-to-end.
1556 ExpectNewFramesReceivedWithWait(
1557 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1558 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1559 kMaxWaitForFramesMs);
1560}
1561
1562// This test sets up a non-bundled call and negotiates bundling at the same
1563// time as starting an ICE restart. When bundling is in effect in the restart,
1564// the DTLS-SRTP context should be successfully reset.
1565TEST_F(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
1566 ASSERT_TRUE(CreatePeerConnectionWrappers());
1567 ConnectFakeSignaling();
1568
Steve Anton15324772018-01-16 10:26:49 -08001569 caller()->AddAudioVideoTracks();
1570 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001571 // Remove the bundle group from the SDP received by the callee.
1572 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1573 desc->RemoveGroupByName("BUNDLE");
1574 });
1575 caller()->CreateAndSetAndSignalOffer();
1576 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1577 ExpectNewFramesReceivedWithWait(
1578 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1579 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1580 kMaxWaitForFramesMs);
1581
1582 // Now stop removing the BUNDLE group, and trigger an ICE restart.
1583 callee()->SetReceivedSdpMunger(nullptr);
1584 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1585 caller()->CreateAndSetAndSignalOffer();
1586 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1587
1588 // Expect additional frames to be received after the ICE restart.
1589 ExpectNewFramesReceivedWithWait(
1590 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1591 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1592 kMaxWaitForFramesMs);
1593}
1594
1595// Test CVO (Coordination of Video Orientation). If a video source is rotated
1596// and both peers support the CVO RTP header extension, the actual video frames
1597// don't need to be encoded in different resolutions, since the rotation is
1598// communicated through the RTP header extension.
1599TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
1600 ASSERT_TRUE(CreatePeerConnectionWrappers());
1601 ConnectFakeSignaling();
1602 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08001603 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001604 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08001605 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001606 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1607
1608 // Wait for video frames to be received by both sides.
1609 caller()->CreateAndSetAndSignalOffer();
1610 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1611 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1612 callee()->min_video_frames_received_per_track() > 0,
1613 kMaxWaitForFramesMs);
1614
1615 // Ensure that the aspect ratio is unmodified.
1616 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1617 // not just assumed.
1618 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
1619 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
1620 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
1621 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
1622 // Ensure that the CVO bits were surfaced to the renderer.
1623 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
1624 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
1625}
1626
1627// Test that when the CVO extension isn't supported, video is rotated the
1628// old-fashioned way, by encoding rotated frames.
1629TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
1630 ASSERT_TRUE(CreatePeerConnectionWrappers());
1631 ConnectFakeSignaling();
1632 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08001633 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001634 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08001635 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001636 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1637
1638 // Remove the CVO extension from the offered SDP.
1639 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1640 cricket::VideoContentDescription* video =
1641 GetFirstVideoContentDescription(desc);
1642 video->ClearRtpHeaderExtensions();
1643 });
1644 // Wait for video frames to be received by both sides.
1645 caller()->CreateAndSetAndSignalOffer();
1646 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1647 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1648 callee()->min_video_frames_received_per_track() > 0,
1649 kMaxWaitForFramesMs);
1650
1651 // Expect that the aspect ratio is inversed to account for the 90/270 degree
1652 // rotation.
1653 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1654 // not just assumed.
1655 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
1656 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
1657 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
1658 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
1659 // Expect that each endpoint is unaware of the rotation of the other endpoint.
1660 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
1661 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
1662}
1663
1664// TODO(deadbeef): The tests below rely on RTCOfferAnswerOptions to reject an
1665// m= section. When we implement Unified Plan SDP, the right way to do this
1666// would be by stopping an RtpTransceiver.
1667
1668// Test that if the answerer rejects the audio m= section, no audio is sent or
1669// received, but video still can be.
1670TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
1671 ASSERT_TRUE(CreatePeerConnectionWrappers());
1672 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001673 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001674 // Only add video track for callee, and set offer_to_receive_audio to 0, so
1675 // it will reject the audio m= section completely.
1676 PeerConnectionInterface::RTCOfferAnswerOptions options;
1677 options.offer_to_receive_audio = 0;
1678 callee()->SetOfferAnswerOptions(options);
Steve Anton15324772018-01-16 10:26:49 -08001679 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07001680 // Do offer/answer and wait for successful end-to-end video frames.
1681 caller()->CreateAndSetAndSignalOffer();
1682 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1683 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount, 0,
1684 kDefaultExpectedVideoFrameCount,
1685 kMaxWaitForFramesMs);
1686 // Shouldn't have received audio frames at any point.
1687 EXPECT_EQ(0, caller()->audio_frames_received());
1688 EXPECT_EQ(0, callee()->audio_frames_received());
1689 // Sanity check that the callee's description has a rejected audio section.
1690 ASSERT_NE(nullptr, callee()->pc()->local_description());
1691 const ContentInfo* callee_audio_content =
1692 GetFirstAudioContent(callee()->pc()->local_description()->description());
1693 ASSERT_NE(nullptr, callee_audio_content);
1694 EXPECT_TRUE(callee_audio_content->rejected);
1695}
1696
1697// Test that if the answerer rejects the video m= section, no video is sent or
1698// received, but audio still can be.
1699TEST_F(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
1700 ASSERT_TRUE(CreatePeerConnectionWrappers());
1701 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001702 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001703 // Only add audio track for callee, and set offer_to_receive_video to 0, so
1704 // it will reject the video m= section completely.
1705 PeerConnectionInterface::RTCOfferAnswerOptions options;
1706 options.offer_to_receive_video = 0;
1707 callee()->SetOfferAnswerOptions(options);
Steve Anton15324772018-01-16 10:26:49 -08001708 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07001709 // Do offer/answer and wait for successful end-to-end audio frames.
1710 caller()->CreateAndSetAndSignalOffer();
1711 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1712 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1713 kDefaultExpectedAudioFrameCount, 0,
1714 kMaxWaitForFramesMs);
1715 // Shouldn't have received video frames at any point.
1716 EXPECT_EQ(0, caller()->total_video_frames_received());
1717 EXPECT_EQ(0, callee()->total_video_frames_received());
1718 // Sanity check that the callee's description has a rejected video section.
1719 ASSERT_NE(nullptr, callee()->pc()->local_description());
1720 const ContentInfo* callee_video_content =
1721 GetFirstVideoContent(callee()->pc()->local_description()->description());
1722 ASSERT_NE(nullptr, callee_video_content);
1723 EXPECT_TRUE(callee_video_content->rejected);
1724}
1725
1726// Test that if the answerer rejects both audio and video m= sections, nothing
1727// bad happens.
1728// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
1729// test anything but the fact that negotiation succeeds, which doesn't mean
1730// much.
1731TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
1732 ASSERT_TRUE(CreatePeerConnectionWrappers());
1733 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001734 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001735 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
1736 // will reject both audio and video m= sections.
1737 PeerConnectionInterface::RTCOfferAnswerOptions options;
1738 options.offer_to_receive_audio = 0;
1739 options.offer_to_receive_video = 0;
1740 callee()->SetOfferAnswerOptions(options);
1741 // Do offer/answer and wait for stable signaling state.
1742 caller()->CreateAndSetAndSignalOffer();
1743 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1744 // Sanity check that the callee's description has rejected m= sections.
1745 ASSERT_NE(nullptr, callee()->pc()->local_description());
1746 const ContentInfo* callee_audio_content =
1747 GetFirstAudioContent(callee()->pc()->local_description()->description());
1748 ASSERT_NE(nullptr, callee_audio_content);
1749 EXPECT_TRUE(callee_audio_content->rejected);
1750 const ContentInfo* callee_video_content =
1751 GetFirstVideoContent(callee()->pc()->local_description()->description());
1752 ASSERT_NE(nullptr, callee_video_content);
1753 EXPECT_TRUE(callee_video_content->rejected);
1754}
1755
1756// This test sets up an audio and video call between two parties. After the
1757// call runs for a while, the caller sends an updated offer with video being
1758// rejected. Once the re-negotiation is done, the video flow should stop and
1759// the audio flow should continue.
1760TEST_F(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
1761 ASSERT_TRUE(CreatePeerConnectionWrappers());
1762 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001763 caller()->AddAudioVideoTracks();
1764 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001765 caller()->CreateAndSetAndSignalOffer();
1766 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1767 ExpectNewFramesReceivedWithWait(
1768 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1769 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1770 kMaxWaitForFramesMs);
1771
1772 // Renegotiate, rejecting the video m= section.
1773 // TODO(deadbeef): When an RtpTransceiver API is available, use that to
1774 // reject the video m= section.
1775 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
1776 for (cricket::ContentInfo& content : description->contents()) {
1777 if (cricket::IsVideoContent(&content)) {
1778 content.rejected = true;
1779 }
1780 }
1781 });
1782 caller()->CreateAndSetAndSignalOffer();
1783 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
1784
1785 // Sanity check that the caller's description has a rejected video section.
1786 ASSERT_NE(nullptr, caller()->pc()->local_description());
1787 const ContentInfo* caller_video_content =
1788 GetFirstVideoContent(caller()->pc()->local_description()->description());
1789 ASSERT_NE(nullptr, caller_video_content);
1790 EXPECT_TRUE(caller_video_content->rejected);
1791
1792 int caller_video_received = caller()->total_video_frames_received();
1793 int callee_video_received = callee()->total_video_frames_received();
1794
1795 // Wait for some additional audio frames to be received.
1796 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1797 kDefaultExpectedAudioFrameCount, 0,
1798 kMaxWaitForFramesMs);
1799
1800 // During this time, we shouldn't have received any additional video frames
1801 // for the rejected video tracks.
1802 EXPECT_EQ(caller_video_received, caller()->total_video_frames_received());
1803 EXPECT_EQ(callee_video_received, callee()->total_video_frames_received());
1804}
1805
1806// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
1807// is needed to support legacy endpoints.
1808// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
1809// add a test for an end-to-end test without MID signaling either (basically,
1810// the minimum acceptable SDP).
1811TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
1812 ASSERT_TRUE(CreatePeerConnectionWrappers());
1813 ConnectFakeSignaling();
1814 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08001815 caller()->AddAudioVideoTracks();
1816 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07001817 // Remove SSRCs and MSIDs from the received offer SDP.
1818 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07001819 caller()->CreateAndSetAndSignalOffer();
1820 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1821 ExpectNewFramesReceivedWithWait(
1822 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1823 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1824 kMaxWaitForFramesMs);
1825}
1826
1827// Test that if two video tracks are sent (from caller to callee, in this test),
1828// they're transmitted correctly end-to-end.
1829TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
1830 ASSERT_TRUE(CreatePeerConnectionWrappers());
1831 ConnectFakeSignaling();
1832 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08001833 caller()->AddAudioVideoTracks();
1834 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001835 caller()->CreateAndSetAndSignalOffer();
1836 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08001837 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001838 int expected_callee_received_frames = kDefaultExpectedVideoFrameCount;
1839 ExpectNewFramesReceivedWithWait(0, 0, 0, expected_callee_received_frames,
1840 kMaxWaitForFramesMs);
1841}
1842
1843static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
1844 bool first = true;
1845 for (cricket::ContentInfo& content : desc->contents()) {
1846 if (first) {
1847 first = false;
1848 continue;
1849 }
1850 content.bundle_only = true;
1851 }
1852 first = true;
1853 for (cricket::TransportInfo& transport : desc->transport_infos()) {
1854 if (first) {
1855 first = false;
1856 continue;
1857 }
1858 transport.description.ice_ufrag.clear();
1859 transport.description.ice_pwd.clear();
1860 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
1861 transport.description.identity_fingerprint.reset(nullptr);
1862 }
1863}
1864
1865// Test that if applying a true "max bundle" offer, which uses ports of 0,
1866// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
1867// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
1868// successfully and media flows.
1869// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
1870// TODO(deadbeef): Won't need this test once we start generating actual
1871// standards-compliant SDP.
1872TEST_F(PeerConnectionIntegrationTest,
1873 EndToEndCallWithSpecCompliantMaxBundleOffer) {
1874 ASSERT_TRUE(CreatePeerConnectionWrappers());
1875 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001876 caller()->AddAudioVideoTracks();
1877 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001878 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
1879 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
1880 // but the first m= section.
1881 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
1882 caller()->CreateAndSetAndSignalOffer();
1883 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1884 ExpectNewFramesReceivedWithWait(
1885 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1886 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1887 kMaxWaitForFramesMs);
1888}
1889
1890// Test that we can receive the audio output level from a remote audio track.
1891// TODO(deadbeef): Use a fake audio source and verify that the output level is
1892// exactly what the source on the other side was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001893TEST_F(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001894 ASSERT_TRUE(CreatePeerConnectionWrappers());
1895 ConnectFakeSignaling();
1896 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08001897 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001898 caller()->CreateAndSetAndSignalOffer();
1899 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1900
1901 // Get the audio output level stats. Note that the level is not available
1902 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07001903 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001904 kMaxWaitForFramesMs);
1905}
1906
1907// Test that an audio input level is reported.
1908// TODO(deadbeef): Use a fake audio source and verify that the input level is
1909// exactly what the source was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001910TEST_F(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001911 ASSERT_TRUE(CreatePeerConnectionWrappers());
1912 ConnectFakeSignaling();
1913 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08001914 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001915 caller()->CreateAndSetAndSignalOffer();
1916 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1917
1918 // Get the audio input level stats. The level should be available very
1919 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07001920 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001921 kMaxWaitForStatsMs);
1922}
1923
1924// Test that we can get incoming byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001925TEST_F(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001926 ASSERT_TRUE(CreatePeerConnectionWrappers());
1927 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001928 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001929 // Do offer/answer, wait for the callee to receive some frames.
1930 caller()->CreateAndSetAndSignalOffer();
1931 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1932 int expected_caller_received_frames = 0;
1933 ExpectNewFramesReceivedWithWait(
1934 expected_caller_received_frames, expected_caller_received_frames,
1935 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1936 kMaxWaitForFramesMs);
1937
1938 // Get a handle to the remote tracks created, so they can be used as GetStats
1939 // filters.
Steve Anton15324772018-01-16 10:26:49 -08001940 for (auto receiver : callee()->pc()->GetReceivers()) {
1941 // We received frames, so we definitely should have nonzero "received bytes"
1942 // stats at this point.
1943 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
1944 0);
1945 }
deadbeef1dcb1642017-03-29 21:08:16 -07001946}
1947
1948// Test that we can get outgoing byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001949TEST_F(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001950 ASSERT_TRUE(CreatePeerConnectionWrappers());
1951 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001952 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001953 auto audio_track = caller()->CreateLocalAudioTrack();
1954 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08001955 caller()->AddTrack(audio_track);
1956 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07001957 // Do offer/answer, wait for the callee to receive some frames.
1958 caller()->CreateAndSetAndSignalOffer();
1959 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1960 int expected_caller_received_frames = 0;
1961 ExpectNewFramesReceivedWithWait(
1962 expected_caller_received_frames, expected_caller_received_frames,
1963 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1964 kMaxWaitForFramesMs);
1965
1966 // The callee received frames, so we definitely should have nonzero "sent
1967 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07001968 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
1969 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
1970}
1971
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02001972// Test that we can get capture start ntp time.
1973TEST_F(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
1974 ASSERT_TRUE(CreatePeerConnectionWrappers());
1975 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001976 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02001977
Steve Anton15324772018-01-16 10:26:49 -08001978 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02001979
1980 // Do offer/answer, wait for the callee to receive some frames.
1981 caller()->CreateAndSetAndSignalOffer();
1982 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1983
1984 // Get the remote audio track created on the receiver, so they can be used as
1985 // GetStats filters.
1986 StreamCollectionInterface* remote_streams = callee()->remote_streams();
1987 ASSERT_EQ(1u, remote_streams->count());
1988 ASSERT_EQ(1u, remote_streams->at(0)->GetAudioTracks().size());
1989 MediaStreamTrackInterface* remote_audio_track =
1990 remote_streams->at(0)->GetAudioTracks()[0];
1991
1992 // Get the audio output level stats. Note that the level is not available
1993 // until an RTCP packet has been received.
1994 EXPECT_TRUE_WAIT(callee()->OldGetStatsForTrack(remote_audio_track)->
1995 CaptureStartNtpTime() > 0, 2 * kMaxWaitForFramesMs);
1996}
1997
deadbeefd8ad7882017-04-18 16:01:17 -07001998// Test that we can get stats (using the new stats implemnetation) for
1999// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2000// SDP.
2001TEST_F(PeerConnectionIntegrationTest,
2002 GetStatsForUnsignaledStreamWithNewStatsApi) {
2003 ASSERT_TRUE(CreatePeerConnectionWrappers());
2004 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002005 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002006 // Remove SSRCs and MSIDs from the received offer SDP.
2007 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2008 caller()->CreateAndSetAndSignalOffer();
2009 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2010 // Wait for one audio frame to be received by the callee.
2011 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
2012
2013 // We received a frame, so we should have nonzero "bytes received" stats for
2014 // the unsignaled stream, if stats are working for it.
2015 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2016 callee()->NewGetStats();
2017 ASSERT_NE(nullptr, report);
2018 auto inbound_stream_stats =
2019 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2020 ASSERT_EQ(1U, inbound_stream_stats.size());
2021 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2022 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002023 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2024}
2025
2026// Test that we can successfully get the media related stats (audio level
2027// etc.) for the unsignaled stream.
2028TEST_F(PeerConnectionIntegrationTest,
2029 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2030 ASSERT_TRUE(CreatePeerConnectionWrappers());
2031 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002032 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002033 // Remove SSRCs and MSIDs from the received offer SDP.
2034 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2035 caller()->CreateAndSetAndSignalOffer();
2036 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2037 // Wait for one audio frame to be received by the callee.
2038 ExpectNewFramesReceivedWithWait(0, 0, 1, 1, kMaxWaitForFramesMs);
2039
2040 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2041 callee()->NewGetStats();
2042 ASSERT_NE(nullptr, report);
2043
2044 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2045 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2046 ASSERT_GE(audio_index, 0);
2047 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002048}
2049
deadbeef4e2deab2017-09-20 13:56:21 -07002050// Helper for test below.
2051void ModifySsrcs(cricket::SessionDescription* desc) {
2052 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002053 for (cricket::StreamParams& stream :
2054 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002055 for (uint32_t& ssrc : stream.ssrcs) {
2056 ssrc = rtc::CreateRandomId();
2057 }
2058 }
2059 }
2060}
2061
2062// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2063// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2064// This should result in two "RTCInboundRTPStreamStats", but only one
2065// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2066// being reset to 0 once the SSRC change occurs.
2067//
2068// Regression test for this bug:
2069// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2070//
2071// The bug causes the track stats to only represent one of the two streams:
2072// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2073// that the track stat counters would reset to 0 when the new stream is
2074// received, and a 50% chance that they'll stop updating (while
2075// "concealed_samples" continues increasing, due to silence being generated for
2076// the inactive stream).
2077TEST_F(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002078 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002079 ASSERT_TRUE(CreatePeerConnectionWrappers());
2080 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002081 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002082 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2083 // that doesn't signal SSRCs (from the callee's perspective).
2084 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2085 caller()->CreateAndSetAndSignalOffer();
2086 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2087 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
2088 ExpectNewFramesReceivedWithWait(0, 0, 25, 0, kMaxWaitForFramesMs);
2089
2090 // Some audio frames were received, so we should have nonzero "samples
2091 // received" for the track.
2092 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2093 callee()->NewGetStats();
2094 ASSERT_NE(nullptr, report);
2095 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2096 ASSERT_EQ(1U, track_stats.size());
2097 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2098 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2099 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2100
2101 // Create a new offer and munge it to cause the caller to use a new SSRC.
2102 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2103 caller()->CreateAndSetAndSignalOffer();
2104 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2105 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2106 // SSRC.
2107 ExpectNewFramesReceivedWithWait(0, 0, 25, 0, kMaxWaitForFramesMs);
2108
2109 report = callee()->NewGetStats();
2110 ASSERT_NE(nullptr, report);
2111 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2112 ASSERT_EQ(1U, track_stats.size());
2113 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2114 // The "total samples received" stat should only be greater than it was
2115 // before.
2116 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2117 // Right now, the new SSRC will cause the counters to reset to 0.
2118 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2119
2120 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002121 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002122 // good sign that we're seeing stats from the old stream that's no longer
2123 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002124 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002125 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2126 EXPECT_LT(*track_stats[0]->concealed_samples,
2127 *track_stats[0]->total_samples_received *
2128 kAcceptableConcealedSamplesPercentage);
2129
2130 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2131 // sanity check that the SSRC really changed.
2132 // TODO(deadbeef): This isn't working right now, because we're not returning
2133 // *any* stats for the inactive stream. Uncomment when the bug is completely
2134 // fixed.
2135 // auto inbound_stream_stats =
2136 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2137 // ASSERT_EQ(2U, inbound_stream_stats.size());
2138}
2139
deadbeef1dcb1642017-03-29 21:08:16 -07002140// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
2141TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
2142 PeerConnectionFactory::Options dtls_10_options;
2143 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2144 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2145 dtls_10_options));
2146 ConnectFakeSignaling();
2147 // Do normal offer/answer and wait for some frames to be received in each
2148 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002149 caller()->AddAudioVideoTracks();
2150 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002151 caller()->CreateAndSetAndSignalOffer();
2152 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2153 ExpectNewFramesReceivedWithWait(
2154 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2155 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2156 kMaxWaitForFramesMs);
2157}
2158
2159// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
2160TEST_F(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
2161 PeerConnectionFactory::Options dtls_10_options;
2162 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2163 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2164 dtls_10_options));
2165 ConnectFakeSignaling();
2166 // Register UMA observer before signaling begins.
2167 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
2168 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2169 caller()->pc()->RegisterUMAObserver(caller_observer);
Steve Anton15324772018-01-16 10:26:49 -08002170 caller()->AddAudioVideoTracks();
2171 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002172 caller()->CreateAndSetAndSignalOffer();
2173 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2174 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002175 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002176 kDefaultTimeout);
2177 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002178 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002179 EXPECT_EQ(1,
2180 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2181 kDefaultSrtpCryptoSuite));
2182}
2183
2184// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
2185TEST_F(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
2186 PeerConnectionFactory::Options dtls_12_options;
2187 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2188 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2189 dtls_12_options));
2190 ConnectFakeSignaling();
2191 // Register UMA observer before signaling begins.
2192 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
2193 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2194 caller()->pc()->RegisterUMAObserver(caller_observer);
Steve Anton15324772018-01-16 10:26:49 -08002195 caller()->AddAudioVideoTracks();
2196 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002197 caller()->CreateAndSetAndSignalOffer();
2198 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2199 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002200 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002201 kDefaultTimeout);
2202 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002203 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002204 EXPECT_EQ(1,
2205 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2206 kDefaultSrtpCryptoSuite));
2207}
2208
2209// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2210// callee only supports 1.0.
2211TEST_F(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
2212 PeerConnectionFactory::Options caller_options;
2213 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2214 PeerConnectionFactory::Options callee_options;
2215 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2216 ASSERT_TRUE(
2217 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2218 ConnectFakeSignaling();
2219 // Do normal offer/answer and wait for some frames to be received in each
2220 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002221 caller()->AddAudioVideoTracks();
2222 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002223 caller()->CreateAndSetAndSignalOffer();
2224 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2225 ExpectNewFramesReceivedWithWait(
2226 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2227 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2228 kMaxWaitForFramesMs);
2229}
2230
2231// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2232// callee supports 1.2.
2233TEST_F(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
2234 PeerConnectionFactory::Options caller_options;
2235 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2236 PeerConnectionFactory::Options callee_options;
2237 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2238 ASSERT_TRUE(
2239 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2240 ConnectFakeSignaling();
2241 // Do normal offer/answer and wait for some frames to be received in each
2242 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002243 caller()->AddAudioVideoTracks();
2244 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002245 caller()->CreateAndSetAndSignalOffer();
2246 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2247 ExpectNewFramesReceivedWithWait(
2248 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2249 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2250 kMaxWaitForFramesMs);
2251}
2252
2253// Test that a non-GCM cipher is used if both sides only support non-GCM.
2254TEST_F(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
2255 bool local_gcm_enabled = false;
2256 bool remote_gcm_enabled = false;
2257 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2258 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2259 expected_cipher_suite);
2260}
2261
2262// Test that a GCM cipher is used if both ends support it.
2263TEST_F(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
2264 bool local_gcm_enabled = true;
2265 bool remote_gcm_enabled = true;
2266 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2267 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2268 expected_cipher_suite);
2269}
2270
2271// Test that GCM isn't used if only the offerer supports it.
2272TEST_F(PeerConnectionIntegrationTest,
2273 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2274 bool local_gcm_enabled = true;
2275 bool remote_gcm_enabled = false;
2276 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2277 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2278 expected_cipher_suite);
2279}
2280
2281// Test that GCM isn't used if only the answerer supports it.
2282TEST_F(PeerConnectionIntegrationTest,
2283 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2284 bool local_gcm_enabled = false;
2285 bool remote_gcm_enabled = true;
2286 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2287 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2288 expected_cipher_suite);
2289}
2290
deadbeef7914b8c2017-04-21 03:23:33 -07002291// Verify that media can be transmitted end-to-end when GCM crypto suites are
2292// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
2293// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
2294// works with it.
2295TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
2296 PeerConnectionFactory::Options gcm_options;
2297 gcm_options.crypto_options.enable_gcm_crypto_suites = true;
2298 ASSERT_TRUE(
2299 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
2300 ConnectFakeSignaling();
2301 // Do normal offer/answer and wait for some frames to be received in each
2302 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002303 caller()->AddAudioVideoTracks();
2304 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002305 caller()->CreateAndSetAndSignalOffer();
2306 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2307 ExpectNewFramesReceivedWithWait(
2308 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2309 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2310 kMaxWaitForFramesMs);
2311}
2312
deadbeef1dcb1642017-03-29 21:08:16 -07002313// This test sets up a call between two parties with audio, video and an RTP
2314// data channel.
2315TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
2316 FakeConstraints setup_constraints;
2317 setup_constraints.SetAllowRtpDataChannels();
2318 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2319 &setup_constraints));
2320 ConnectFakeSignaling();
2321 // Expect that data channel created on caller side will show up for callee as
2322 // well.
2323 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002324 caller()->AddAudioVideoTracks();
2325 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002326 caller()->CreateAndSetAndSignalOffer();
2327 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2328 // Ensure the existence of the RTP data channel didn't impede audio/video.
2329 ExpectNewFramesReceivedWithWait(
2330 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2331 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2332 kMaxWaitForFramesMs);
2333 ASSERT_NE(nullptr, caller()->data_channel());
2334 ASSERT_NE(nullptr, callee()->data_channel());
2335 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2336 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2337
2338 // Ensure data can be sent in both directions.
2339 std::string data = "hello world";
2340 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2341 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2342 kDefaultTimeout);
2343 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2344 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2345 kDefaultTimeout);
2346}
2347
2348// Ensure that an RTP data channel is signaled as closed for the caller when
2349// the callee rejects it in a subsequent offer.
2350TEST_F(PeerConnectionIntegrationTest,
2351 RtpDataChannelSignaledClosedInCalleeOffer) {
2352 // Same procedure as above test.
2353 FakeConstraints setup_constraints;
2354 setup_constraints.SetAllowRtpDataChannels();
2355 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2356 &setup_constraints));
2357 ConnectFakeSignaling();
2358 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002359 caller()->AddAudioVideoTracks();
2360 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002361 caller()->CreateAndSetAndSignalOffer();
2362 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2363 ASSERT_NE(nullptr, caller()->data_channel());
2364 ASSERT_NE(nullptr, callee()->data_channel());
2365 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2366 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2367
2368 // Close the data channel on the callee, and do an updated offer/answer.
2369 callee()->data_channel()->Close();
2370 callee()->CreateAndSetAndSignalOffer();
2371 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2372 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2373 EXPECT_FALSE(callee()->data_observer()->IsOpen());
2374}
2375
2376// Tests that data is buffered in an RTP data channel until an observer is
2377// registered for it.
2378//
2379// NOTE: RTP data channels can receive data before the underlying
2380// transport has detected that a channel is writable and thus data can be
2381// received before the data channel state changes to open. That is hard to test
2382// but the same buffering is expected to be used in that case.
2383TEST_F(PeerConnectionIntegrationTest,
2384 DataBufferedUntilRtpDataChannelObserverRegistered) {
2385 // Use fake clock and simulated network delay so that we predictably can wait
2386 // until an SCTP message has been delivered without "sleep()"ing.
2387 rtc::ScopedFakeClock fake_clock;
2388 // Some things use a time of "0" as a special value, so we need to start out
2389 // the fake clock at a nonzero time.
2390 // TODO(deadbeef): Fix this.
2391 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2392 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
2393 virtual_socket_server()->UpdateDelayDistribution();
2394
2395 FakeConstraints constraints;
2396 constraints.SetAllowRtpDataChannels();
2397 ASSERT_TRUE(
2398 CreatePeerConnectionWrappersWithConstraints(&constraints, &constraints));
2399 ConnectFakeSignaling();
2400 caller()->CreateDataChannel();
2401 caller()->CreateAndSetAndSignalOffer();
2402 ASSERT_TRUE(caller()->data_channel() != nullptr);
2403 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
2404 kDefaultTimeout, fake_clock);
2405 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
2406 kDefaultTimeout, fake_clock);
2407 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
2408 callee()->data_channel()->state(), kDefaultTimeout,
2409 fake_clock);
2410
2411 // Unregister the observer which is normally automatically registered.
2412 callee()->data_channel()->UnregisterObserver();
2413 // Send data and advance fake clock until it should have been received.
2414 std::string data = "hello world";
2415 caller()->data_channel()->Send(DataBuffer(data));
2416 SIMULATED_WAIT(false, 50, fake_clock);
2417
2418 // Attach data channel and expect data to be received immediately. Note that
2419 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
2420 // further, but data can be received even if the callback is asynchronous.
2421 MockDataChannelObserver new_observer(callee()->data_channel());
2422 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
2423 fake_clock);
2424}
2425
2426// This test sets up a call between two parties with audio, video and but only
2427// the caller client supports RTP data channels.
2428TEST_F(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
2429 FakeConstraints setup_constraints_1;
2430 setup_constraints_1.SetAllowRtpDataChannels();
2431 // Must disable DTLS to make negotiation succeed.
2432 setup_constraints_1.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2433 false);
2434 FakeConstraints setup_constraints_2;
2435 setup_constraints_2.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2436 false);
2437 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(
2438 &setup_constraints_1, &setup_constraints_2));
2439 ConnectFakeSignaling();
2440 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002441 caller()->AddAudioVideoTracks();
2442 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002443 caller()->CreateAndSetAndSignalOffer();
2444 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2445 // The caller should still have a data channel, but it should be closed, and
2446 // one should ever have been created for the callee.
2447 EXPECT_TRUE(caller()->data_channel() != nullptr);
2448 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2449 EXPECT_EQ(nullptr, callee()->data_channel());
2450}
2451
2452// This test sets up a call between two parties with audio, and video. When
2453// audio and video is setup and flowing, an RTP data channel is negotiated.
2454TEST_F(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
2455 FakeConstraints setup_constraints;
2456 setup_constraints.SetAllowRtpDataChannels();
2457 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2458 &setup_constraints));
2459 ConnectFakeSignaling();
2460 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08002461 caller()->AddAudioVideoTracks();
2462 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002463 caller()->CreateAndSetAndSignalOffer();
2464 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2465 // Create data channel and do new offer and answer.
2466 caller()->CreateDataChannel();
2467 caller()->CreateAndSetAndSignalOffer();
2468 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2469 ASSERT_NE(nullptr, caller()->data_channel());
2470 ASSERT_NE(nullptr, callee()->data_channel());
2471 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2472 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2473 // Ensure data can be sent in both directions.
2474 std::string data = "hello world";
2475 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2476 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2477 kDefaultTimeout);
2478 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2479 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2480 kDefaultTimeout);
2481}
2482
2483#ifdef HAVE_SCTP
2484
2485// This test sets up a call between two parties with audio, video and an SCTP
2486// data channel.
2487TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
2488 ASSERT_TRUE(CreatePeerConnectionWrappers());
2489 ConnectFakeSignaling();
2490 // Expect that data channel created on caller side will show up for callee as
2491 // well.
2492 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002493 caller()->AddAudioVideoTracks();
2494 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002495 caller()->CreateAndSetAndSignalOffer();
2496 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2497 // Ensure the existence of the SCTP data channel didn't impede audio/video.
2498 ExpectNewFramesReceivedWithWait(
2499 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2500 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2501 kMaxWaitForFramesMs);
2502 // Caller data channel should already exist (it created one). Callee data
2503 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2504 ASSERT_NE(nullptr, caller()->data_channel());
2505 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2506 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2507 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2508
2509 // Ensure data can be sent in both directions.
2510 std::string data = "hello world";
2511 caller()->data_channel()->Send(DataBuffer(data));
2512 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2513 kDefaultTimeout);
2514 callee()->data_channel()->Send(DataBuffer(data));
2515 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2516 kDefaultTimeout);
2517}
2518
2519// Ensure that when the callee closes an SCTP data channel, the closing
2520// procedure results in the data channel being closed for the caller as well.
2521TEST_F(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
2522 // Same procedure as above test.
2523 ASSERT_TRUE(CreatePeerConnectionWrappers());
2524 ConnectFakeSignaling();
2525 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002526 caller()->AddAudioVideoTracks();
2527 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002528 caller()->CreateAndSetAndSignalOffer();
2529 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2530 ASSERT_NE(nullptr, caller()->data_channel());
2531 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2532 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2533 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2534
2535 // Close the data channel on the callee side, and wait for it to reach the
2536 // "closed" state on both sides.
2537 callee()->data_channel()->Close();
2538 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
2539 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
2540}
2541
Steve Antonda6c0952017-10-23 11:41:54 -07002542TEST_F(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
2543 ASSERT_TRUE(CreatePeerConnectionWrappers());
2544 ConnectFakeSignaling();
2545 webrtc::DataChannelInit init;
2546 init.id = 53;
2547 init.maxRetransmits = 52;
2548 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08002549 caller()->AddAudioVideoTracks();
2550 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07002551 caller()->CreateAndSetAndSignalOffer();
2552 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07002553 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2554 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07002555 EXPECT_EQ(init.id, callee()->data_channel()->id());
2556 EXPECT_EQ("data-channel", callee()->data_channel()->label());
2557 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
2558 EXPECT_FALSE(callee()->data_channel()->negotiated());
2559}
2560
deadbeef1dcb1642017-03-29 21:08:16 -07002561// Test usrsctp's ability to process unordered data stream, where data actually
2562// arrives out of order using simulated delays. Previously there have been some
2563// bugs in this area.
2564TEST_F(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
2565 // Introduce random network delays.
2566 // Otherwise it's not a true "unordered" test.
2567 virtual_socket_server()->set_delay_mean(20);
2568 virtual_socket_server()->set_delay_stddev(5);
2569 virtual_socket_server()->UpdateDelayDistribution();
2570 // Normal procedure, but with unordered data channel config.
2571 ASSERT_TRUE(CreatePeerConnectionWrappers());
2572 ConnectFakeSignaling();
2573 webrtc::DataChannelInit init;
2574 init.ordered = false;
2575 caller()->CreateDataChannel(&init);
2576 caller()->CreateAndSetAndSignalOffer();
2577 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2578 ASSERT_NE(nullptr, caller()->data_channel());
2579 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2580 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2581 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2582
2583 static constexpr int kNumMessages = 100;
2584 // Deliberately chosen to be larger than the MTU so messages get fragmented.
2585 static constexpr size_t kMaxMessageSize = 4096;
2586 // Create and send random messages.
2587 std::vector<std::string> sent_messages;
2588 for (int i = 0; i < kNumMessages; ++i) {
2589 size_t length =
2590 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
2591 std::string message;
2592 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
2593 caller()->data_channel()->Send(DataBuffer(message));
2594 callee()->data_channel()->Send(DataBuffer(message));
2595 sent_messages.push_back(message);
2596 }
2597
2598 // Wait for all messages to be received.
2599 EXPECT_EQ_WAIT(kNumMessages,
2600 caller()->data_observer()->received_message_count(),
2601 kDefaultTimeout);
2602 EXPECT_EQ_WAIT(kNumMessages,
2603 callee()->data_observer()->received_message_count(),
2604 kDefaultTimeout);
2605
2606 // Sort and compare to make sure none of the messages were corrupted.
2607 std::vector<std::string> caller_received_messages =
2608 caller()->data_observer()->messages();
2609 std::vector<std::string> callee_received_messages =
2610 callee()->data_observer()->messages();
2611 std::sort(sent_messages.begin(), sent_messages.end());
2612 std::sort(caller_received_messages.begin(), caller_received_messages.end());
2613 std::sort(callee_received_messages.begin(), callee_received_messages.end());
2614 EXPECT_EQ(sent_messages, caller_received_messages);
2615 EXPECT_EQ(sent_messages, callee_received_messages);
2616}
2617
2618// This test sets up a call between two parties with audio, and video. When
2619// audio and video are setup and flowing, an SCTP data channel is negotiated.
2620TEST_F(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
2621 ASSERT_TRUE(CreatePeerConnectionWrappers());
2622 ConnectFakeSignaling();
2623 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08002624 caller()->AddAudioVideoTracks();
2625 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002626 caller()->CreateAndSetAndSignalOffer();
2627 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2628 // Create data channel and do new offer and answer.
2629 caller()->CreateDataChannel();
2630 caller()->CreateAndSetAndSignalOffer();
2631 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2632 // Caller data channel should already exist (it created one). Callee data
2633 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2634 ASSERT_NE(nullptr, caller()->data_channel());
2635 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2636 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2637 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2638 // Ensure data can be sent in both directions.
2639 std::string data = "hello world";
2640 caller()->data_channel()->Send(DataBuffer(data));
2641 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2642 kDefaultTimeout);
2643 callee()->data_channel()->Send(DataBuffer(data));
2644 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2645 kDefaultTimeout);
2646}
2647
deadbeef7914b8c2017-04-21 03:23:33 -07002648// Set up a connection initially just using SCTP data channels, later upgrading
2649// to audio/video, ensuring frames are received end-to-end. Effectively the
2650// inverse of the test above.
2651// This was broken in M57; see https://crbug.com/711243
2652TEST_F(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
2653 ASSERT_TRUE(CreatePeerConnectionWrappers());
2654 ConnectFakeSignaling();
2655 // Do initial offer/answer with just data channel.
2656 caller()->CreateDataChannel();
2657 caller()->CreateAndSetAndSignalOffer();
2658 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2659 // Wait until data can be sent over the data channel.
2660 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2661 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2662 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2663
2664 // Do subsequent offer/answer with two-way audio and video. Audio and video
2665 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08002666 caller()->AddAudioVideoTracks();
2667 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002668 caller()->CreateAndSetAndSignalOffer();
2669 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2670 ExpectNewFramesReceivedWithWait(
2671 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2672 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2673 kMaxWaitForFramesMs);
2674}
2675
deadbeef8b7e9ad2017-05-25 09:38:55 -07002676static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07002677 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08002678 GetFirstDataContentDescription(desc);
2679 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07002680 dcd_offer->set_use_sctpmap(false);
2681 dcd_offer->set_protocol("UDP/DTLS/SCTP");
2682}
2683
2684// Test that the data channel works when a spec-compliant SCTP m= section is
2685// offered (using "a=sctp-port" instead of "a=sctpmap", and using
2686// "UDP/DTLS/SCTP" as the protocol).
2687TEST_F(PeerConnectionIntegrationTest,
2688 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
2689 ASSERT_TRUE(CreatePeerConnectionWrappers());
2690 ConnectFakeSignaling();
2691 caller()->CreateDataChannel();
2692 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
2693 caller()->CreateAndSetAndSignalOffer();
2694 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2695 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2696 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2697 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2698
2699 // Ensure data can be sent in both directions.
2700 std::string data = "hello world";
2701 caller()->data_channel()->Send(DataBuffer(data));
2702 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2703 kDefaultTimeout);
2704 callee()->data_channel()->Send(DataBuffer(data));
2705 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2706 kDefaultTimeout);
2707}
2708
deadbeef1dcb1642017-03-29 21:08:16 -07002709#endif // HAVE_SCTP
2710
2711// Test that the ICE connection and gathering states eventually reach
2712// "complete".
2713TEST_F(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
2714 ASSERT_TRUE(CreatePeerConnectionWrappers());
2715 ConnectFakeSignaling();
2716 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002717 caller()->AddAudioVideoTracks();
2718 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002719 caller()->CreateAndSetAndSignalOffer();
2720 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2721 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2722 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
2723 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2724 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
2725 // After the best candidate pair is selected and all candidates are signaled,
2726 // the ICE connection state should reach "complete".
2727 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
2728 // answerer/"callee" by default) only reaches "connected". When this is
2729 // fixed, this test should be updated.
2730 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2731 caller()->ice_connection_state(), kDefaultTimeout);
2732 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2733 callee()->ice_connection_state(), kDefaultTimeout);
2734}
2735
Steve Antonede9ca52017-10-16 13:04:27 -07002736// Test that firewalling the ICE connection causes the clients to identify the
2737// disconnected state and then removing the firewall causes them to reconnect.
2738class PeerConnectionIntegrationIceStatesTest
2739 : public PeerConnectionIntegrationTest,
2740 public ::testing::WithParamInterface<std::tuple<std::string, uint32_t>> {
2741 protected:
2742 PeerConnectionIntegrationIceStatesTest() {
2743 port_allocator_flags_ = std::get<1>(GetParam());
2744 }
2745
2746 void StartStunServer(const SocketAddress& server_address) {
2747 stun_server_.reset(
2748 cricket::TestStunServer::Create(network_thread(), server_address));
2749 }
2750
2751 bool TestIPv6() {
2752 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
2753 }
2754
2755 void SetPortAllocatorFlags() {
2756 caller()->port_allocator()->set_flags(port_allocator_flags_);
2757 callee()->port_allocator()->set_flags(port_allocator_flags_);
2758 }
2759
2760 std::vector<SocketAddress> CallerAddresses() {
2761 std::vector<SocketAddress> addresses;
2762 addresses.push_back(SocketAddress("1.1.1.1", 0));
2763 if (TestIPv6()) {
2764 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
2765 }
2766 return addresses;
2767 }
2768
2769 std::vector<SocketAddress> CalleeAddresses() {
2770 std::vector<SocketAddress> addresses;
2771 addresses.push_back(SocketAddress("2.2.2.2", 0));
2772 if (TestIPv6()) {
2773 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
2774 }
2775 return addresses;
2776 }
2777
2778 void SetUpNetworkInterfaces() {
2779 // Remove the default interfaces added by the test infrastructure.
2780 caller()->network()->RemoveInterface(kDefaultLocalAddress);
2781 callee()->network()->RemoveInterface(kDefaultLocalAddress);
2782
2783 // Add network addresses for test.
2784 for (const auto& caller_address : CallerAddresses()) {
2785 caller()->network()->AddInterface(caller_address);
2786 }
2787 for (const auto& callee_address : CalleeAddresses()) {
2788 callee()->network()->AddInterface(callee_address);
2789 }
2790 }
2791
2792 private:
2793 uint32_t port_allocator_flags_;
2794 std::unique_ptr<cricket::TestStunServer> stun_server_;
2795};
2796
2797// Tests that the PeerConnection goes through all the ICE gathering/connection
2798// states over the duration of the call. This includes Disconnected and Failed
2799// states, induced by putting a firewall between the peers and waiting for them
2800// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08002801TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
2802 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
2803 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
2804 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07002805
2806 const SocketAddress kStunServerAddress =
2807 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
2808 StartStunServer(kStunServerAddress);
2809
2810 PeerConnectionInterface::RTCConfiguration config;
2811 PeerConnectionInterface::IceServer ice_stun_server;
2812 ice_stun_server.urls.push_back(
2813 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
2814 kStunServerAddress.PortAsString());
2815 config.servers.push_back(ice_stun_server);
2816
2817 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
2818 ConnectFakeSignaling();
2819 SetPortAllocatorFlags();
2820 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08002821 caller()->AddAudioVideoTracks();
2822 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07002823
2824 // Initial state before anything happens.
2825 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
2826 caller()->ice_gathering_state());
2827 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
2828 caller()->ice_connection_state());
2829
2830 // Start the call by creating the offer, setting it as the local description,
2831 // then sending it to the peer who will respond with an answer. This happens
2832 // asynchronously so that we can watch the states as it runs in the
2833 // background.
2834 caller()->CreateAndSetAndSignalOffer();
2835
Steve Anton83119dd2017-11-10 16:19:52 -08002836 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
2837 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002838
2839 // Verify that the observer was notified of the intermediate transitions.
2840 EXPECT_THAT(caller()->ice_connection_state_history(),
2841 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
2842 PeerConnectionInterface::kIceConnectionConnected,
2843 PeerConnectionInterface::kIceConnectionCompleted));
2844 EXPECT_THAT(caller()->ice_gathering_state_history(),
2845 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
2846 PeerConnectionInterface::kIceGatheringComplete));
2847
2848 // Block connections to/from the caller and wait for ICE to become
2849 // disconnected.
2850 for (const auto& caller_address : CallerAddresses()) {
2851 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
2852 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002853 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08002854 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
2855 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002856
2857 // Let ICE re-establish by removing the firewall rules.
2858 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01002859 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08002860 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
2861 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002862
2863 // According to RFC7675, if there is no response within 30 seconds then the
2864 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08002865 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07002866 constexpr int kConsentTimeout = 30000;
2867 for (const auto& caller_address : CallerAddresses()) {
2868 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
2869 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002870 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08002871 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
2872 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002873}
2874
2875// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
2876// and that the statistics in the metric observers are updated correctly.
2877TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
2878 ASSERT_TRUE(CreatePeerConnectionWrappers());
2879 ConnectFakeSignaling();
2880 SetPortAllocatorFlags();
2881 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08002882 caller()->AddAudioVideoTracks();
2883 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07002884
2885 rtc::scoped_refptr<webrtc::FakeMetricsObserver> metrics_observer(
2886 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>());
2887 caller()->pc()->RegisterUMAObserver(metrics_observer.get());
2888
2889 caller()->CreateAndSetAndSignalOffer();
2890
2891 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2892
2893 const int num_best_ipv4 = metrics_observer->GetEnumCounter(
2894 webrtc::kEnumCounterAddressFamily, webrtc::kBestConnections_IPv4);
2895 const int num_best_ipv6 = metrics_observer->GetEnumCounter(
2896 webrtc::kEnumCounterAddressFamily, webrtc::kBestConnections_IPv6);
2897 if (TestIPv6()) {
2898 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
2899 // connection.
2900 EXPECT_EQ(0u, num_best_ipv4);
2901 EXPECT_EQ(1u, num_best_ipv6);
2902 } else {
2903 EXPECT_EQ(1u, num_best_ipv4);
2904 EXPECT_EQ(0u, num_best_ipv6);
2905 }
2906
2907 EXPECT_EQ(0u, metrics_observer->GetEnumCounter(
2908 webrtc::kEnumCounterIceCandidatePairTypeUdp,
2909 webrtc::kIceCandidatePairHostHost));
2910 EXPECT_EQ(1u, metrics_observer->GetEnumCounter(
2911 webrtc::kEnumCounterIceCandidatePairTypeUdp,
2912 webrtc::kIceCandidatePairHostPublicHostPublic));
2913}
2914
2915constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
2916 cricket::PORTALLOCATOR_DISABLE_STUN |
2917 cricket::PORTALLOCATOR_DISABLE_RELAY;
2918constexpr uint32_t kFlagsIPv6NoStun =
2919 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
2920 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
2921constexpr uint32_t kFlagsIPv4Stun =
2922 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
2923
2924INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
2925 PeerConnectionIntegrationIceStatesTest,
2926 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
2927 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
2928 std::make_pair("IPv4 with STUN",
2929 kFlagsIPv4Stun)));
2930
deadbeef1dcb1642017-03-29 21:08:16 -07002931// This test sets up a call between two parties with audio and video.
2932// During the call, the caller restarts ICE and the test verifies that
2933// new ICE candidates are generated and audio and video still can flow, and the
2934// ICE state reaches completed again.
2935TEST_F(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
2936 ASSERT_TRUE(CreatePeerConnectionWrappers());
2937 ConnectFakeSignaling();
2938 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08002939 caller()->AddAudioVideoTracks();
2940 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002941 caller()->CreateAndSetAndSignalOffer();
2942 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2943 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2944 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2945 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2946 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2947
2948 // To verify that the ICE restart actually occurs, get
2949 // ufrag/password/candidates before and after restart.
2950 // Create an SDP string of the first audio candidate for both clients.
2951 const webrtc::IceCandidateCollection* audio_candidates_caller =
2952 caller()->pc()->local_description()->candidates(0);
2953 const webrtc::IceCandidateCollection* audio_candidates_callee =
2954 callee()->pc()->local_description()->candidates(0);
2955 ASSERT_GT(audio_candidates_caller->count(), 0u);
2956 ASSERT_GT(audio_candidates_callee->count(), 0u);
2957 std::string caller_candidate_pre_restart;
2958 ASSERT_TRUE(
2959 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
2960 std::string callee_candidate_pre_restart;
2961 ASSERT_TRUE(
2962 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
2963 const cricket::SessionDescription* desc =
2964 caller()->pc()->local_description()->description();
2965 std::string caller_ufrag_pre_restart =
2966 desc->transport_infos()[0].description.ice_ufrag;
2967 desc = callee()->pc()->local_description()->description();
2968 std::string callee_ufrag_pre_restart =
2969 desc->transport_infos()[0].description.ice_ufrag;
2970
2971 // Have the caller initiate an ICE restart.
2972 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2973 caller()->CreateAndSetAndSignalOffer();
2974 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2975 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2976 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2977 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2978 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2979
2980 // Grab the ufrags/candidates again.
2981 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
2982 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
2983 ASSERT_GT(audio_candidates_caller->count(), 0u);
2984 ASSERT_GT(audio_candidates_callee->count(), 0u);
2985 std::string caller_candidate_post_restart;
2986 ASSERT_TRUE(
2987 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
2988 std::string callee_candidate_post_restart;
2989 ASSERT_TRUE(
2990 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
2991 desc = caller()->pc()->local_description()->description();
2992 std::string caller_ufrag_post_restart =
2993 desc->transport_infos()[0].description.ice_ufrag;
2994 desc = callee()->pc()->local_description()->description();
2995 std::string callee_ufrag_post_restart =
2996 desc->transport_infos()[0].description.ice_ufrag;
2997 // Sanity check that an ICE restart was actually negotiated in SDP.
2998 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
2999 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
3000 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
3001 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
3002
3003 // Ensure that additional frames are received after the ICE restart.
3004 ExpectNewFramesReceivedWithWait(
3005 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3006 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3007 kMaxWaitForFramesMs);
3008}
3009
3010// Verify that audio/video can be received end-to-end when ICE renomination is
3011// enabled.
3012TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
3013 PeerConnectionInterface::RTCConfiguration config;
3014 config.enable_ice_renomination = true;
3015 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3016 ConnectFakeSignaling();
3017 // Do normal offer/answer and wait for some frames to be received in each
3018 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003019 caller()->AddAudioVideoTracks();
3020 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003021 caller()->CreateAndSetAndSignalOffer();
3022 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3023 // Sanity check that ICE renomination was actually negotiated.
3024 const cricket::SessionDescription* desc =
3025 caller()->pc()->local_description()->description();
3026 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003027 ASSERT_NE(
3028 info.description.transport_options.end(),
3029 std::find(info.description.transport_options.begin(),
3030 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003031 }
3032 desc = callee()->pc()->local_description()->description();
3033 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003034 ASSERT_NE(
3035 info.description.transport_options.end(),
3036 std::find(info.description.transport_options.begin(),
3037 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003038 }
3039 ExpectNewFramesReceivedWithWait(
3040 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3041 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3042 kMaxWaitForFramesMs);
3043}
3044
Steve Anton6f25b092017-10-23 09:39:20 -07003045// With a max bundle policy and RTCP muxing, adding a new media description to
3046// the connection should not affect ICE at all because the new media will use
3047// the existing connection.
3048TEST_F(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003049 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07003050 PeerConnectionInterface::RTCConfiguration config;
3051 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3052 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3053 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
3054 config, PeerConnectionInterface::RTCConfiguration()));
3055 ConnectFakeSignaling();
3056
Steve Anton15324772018-01-16 10:26:49 -08003057 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003058 caller()->CreateAndSetAndSignalOffer();
3059 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07003060 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3061 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07003062
3063 caller()->clear_ice_connection_state_history();
3064
Steve Anton15324772018-01-16 10:26:49 -08003065 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003066 caller()->CreateAndSetAndSignalOffer();
3067 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3068
3069 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
3070}
3071
deadbeef1dcb1642017-03-29 21:08:16 -07003072// This test sets up a call between two parties with audio and video. It then
3073// renegotiates setting the video m-line to "port 0", then later renegotiates
3074// again, enabling video.
3075TEST_F(PeerConnectionIntegrationTest,
3076 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
3077 ASSERT_TRUE(CreatePeerConnectionWrappers());
3078 ConnectFakeSignaling();
3079
3080 // Do initial negotiation, only sending media from the caller. Will result in
3081 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08003082 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003083 caller()->CreateAndSetAndSignalOffer();
3084 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3085
3086 // Negotiate again, disabling the video "m=" section (the callee will set the
3087 // port to 0 due to offer_to_receive_video = 0).
3088 PeerConnectionInterface::RTCOfferAnswerOptions options;
3089 options.offer_to_receive_video = 0;
3090 callee()->SetOfferAnswerOptions(options);
3091 caller()->CreateAndSetAndSignalOffer();
3092 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3093 // Sanity check that video "m=" section was actually rejected.
3094 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
3095 callee()->pc()->local_description()->description());
3096 ASSERT_NE(nullptr, answer_video_content);
3097 ASSERT_TRUE(answer_video_content->rejected);
3098
3099 // Enable video and do negotiation again, making sure video is received
3100 // end-to-end, also adding media stream to callee.
3101 options.offer_to_receive_video = 1;
3102 callee()->SetOfferAnswerOptions(options);
Steve Anton15324772018-01-16 10:26:49 -08003103 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003104 caller()->CreateAndSetAndSignalOffer();
3105 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3106 // Verify the caller receives frames from the newly added stream, and the
3107 // callee receives additional frames from the re-enabled video m= section.
3108 ExpectNewFramesReceivedWithWait(
3109 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3110 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3111 kMaxWaitForFramesMs);
3112}
3113
3114// This test sets up a Jsep call between two parties with external
3115// VideoDecoderFactory.
3116// TODO(holmer): Disabled due to sometimes crashing on buildbots.
3117// See issue webrtc/2378.
3118TEST_F(PeerConnectionIntegrationTest,
3119 DISABLED_EndToEndCallWithVideoDecoderFactory) {
3120 ASSERT_TRUE(CreatePeerConnectionWrappers());
3121 EnableVideoDecoderFactory();
3122 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003123 caller()->AddAudioVideoTracks();
3124 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003125 caller()->CreateAndSetAndSignalOffer();
3126 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3127 ExpectNewFramesReceivedWithWait(
3128 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3129 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3130 kMaxWaitForFramesMs);
3131}
3132
3133// This tests that if we negotiate after calling CreateSender but before we
3134// have a track, then set a track later, frames from the newly-set track are
3135// received end-to-end.
3136// TODO(deadbeef): Change this test to use AddTransceiver, once that's
3137// implemented.
3138TEST_F(PeerConnectionIntegrationTest,
3139 MediaFlowsAfterEarlyWarmupWithCreateSender) {
3140 ASSERT_TRUE(CreatePeerConnectionWrappers());
3141 ConnectFakeSignaling();
3142 auto caller_audio_sender =
3143 caller()->pc()->CreateSender("audio", "caller_stream");
3144 auto caller_video_sender =
3145 caller()->pc()->CreateSender("video", "caller_stream");
3146 auto callee_audio_sender =
3147 callee()->pc()->CreateSender("audio", "callee_stream");
3148 auto callee_video_sender =
3149 callee()->pc()->CreateSender("video", "callee_stream");
3150 caller()->CreateAndSetAndSignalOffer();
3151 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3152 // Wait for ICE to complete, without any tracks being set.
3153 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3154 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3155 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3156 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3157 // Now set the tracks, and expect frames to immediately start flowing.
3158 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3159 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3160 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3161 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
3162 ExpectNewFramesReceivedWithWait(
3163 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3164 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3165 kMaxWaitForFramesMs);
3166}
3167
3168// This test verifies that a remote video track can be added via AddStream,
3169// and sent end-to-end. For this particular test, it's simply echoed back
3170// from the caller to the callee, rather than being forwarded to a third
3171// PeerConnection.
3172TEST_F(PeerConnectionIntegrationTest, CanSendRemoteVideoTrack) {
3173 ASSERT_TRUE(CreatePeerConnectionWrappers());
3174 ConnectFakeSignaling();
3175 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08003176 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07003177 caller()->CreateAndSetAndSignalOffer();
3178 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3179 ASSERT_EQ(1, callee()->remote_streams()->count());
3180
3181 // Echo the stream back, and do a new offer/anwer (initiated by callee this
3182 // time).
3183 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
3184 callee()->CreateAndSetAndSignalOffer();
3185 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3186
3187 int expected_caller_received_video_frames = kDefaultExpectedVideoFrameCount;
3188 ExpectNewFramesReceivedWithWait(0, expected_caller_received_video_frames, 0,
3189 0, kMaxWaitForFramesMs);
3190}
3191
3192// Test that we achieve the expected end-to-end connection time, using a
3193// fake clock and simulated latency on the media and signaling paths.
3194// We use a TURN<->TURN connection because this is usually the quickest to
3195// set up initially, especially when we're confident the connection will work
3196// and can start sending media before we get a STUN response.
3197//
3198// With various optimizations enabled, here are the network delays we expect to
3199// be on the critical path:
3200// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
3201// signaling answer (with DTLS fingerprint).
3202// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
3203// using TURN<->TURN pair, and DTLS exchange is 4 packets,
3204// the first of which should have arrived before the answer.
3205TEST_F(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
3206 rtc::ScopedFakeClock fake_clock;
3207 // Some things use a time of "0" as a special value, so we need to start out
3208 // the fake clock at a nonzero time.
3209 // TODO(deadbeef): Fix this.
3210 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
3211
3212 static constexpr int media_hop_delay_ms = 50;
3213 static constexpr int signaling_trip_delay_ms = 500;
3214 // For explanation of these values, see comment above.
3215 static constexpr int required_media_hops = 9;
3216 static constexpr int required_signaling_trips = 2;
3217 // For internal delays (such as posting an event asychronously).
3218 static constexpr int allowed_internal_delay_ms = 20;
3219 static constexpr int total_connection_time_ms =
3220 media_hop_delay_ms * required_media_hops +
3221 signaling_trip_delay_ms * required_signaling_trips +
3222 allowed_internal_delay_ms;
3223
3224 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3225 3478};
3226 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3227 0};
3228 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3229 3478};
3230 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3231 0};
3232 cricket::TestTurnServer turn_server_1(network_thread(),
3233 turn_server_1_internal_address,
3234 turn_server_1_external_address);
3235 cricket::TestTurnServer turn_server_2(network_thread(),
3236 turn_server_2_internal_address,
3237 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02003238
deadbeef1dcb1642017-03-29 21:08:16 -07003239 // Bypass permission check on received packets so media can be sent before
3240 // the candidate is signaled.
3241 turn_server_1.set_enable_permission_checks(false);
3242 turn_server_2.set_enable_permission_checks(false);
3243
3244 PeerConnectionInterface::RTCConfiguration client_1_config;
3245 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3246 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3247 ice_server_1.username = "test";
3248 ice_server_1.password = "test";
3249 client_1_config.servers.push_back(ice_server_1);
3250 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3251 client_1_config.presume_writable_when_fully_relayed = true;
3252
3253 PeerConnectionInterface::RTCConfiguration client_2_config;
3254 webrtc::PeerConnectionInterface::IceServer ice_server_2;
3255 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
3256 ice_server_2.username = "test";
3257 ice_server_2.password = "test";
3258 client_2_config.servers.push_back(ice_server_2);
3259 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
3260 client_2_config.presume_writable_when_fully_relayed = true;
3261
3262 ASSERT_TRUE(
3263 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
3264 // Set up the simulated delays.
3265 SetSignalingDelayMs(signaling_trip_delay_ms);
3266 ConnectFakeSignaling();
3267 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
3268 virtual_socket_server()->UpdateDelayDistribution();
3269
3270 // Set "offer to receive audio/video" without adding any tracks, so we just
3271 // set up ICE/DTLS with no media.
3272 PeerConnectionInterface::RTCOfferAnswerOptions options;
3273 options.offer_to_receive_audio = 1;
3274 options.offer_to_receive_video = 1;
3275 caller()->SetOfferAnswerOptions(options);
3276 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07003277 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
3278 fake_clock);
deadbeef1dcb1642017-03-29 21:08:16 -07003279 // Need to free the clients here since they're using things we created on
3280 // the stack.
3281 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
3282 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
3283}
3284
Jonas Orelandbdcee282017-10-10 14:01:40 +02003285// Verify that a TurnCustomizer passed in through RTCConfiguration
3286// is actually used by the underlying TURN candidate pair.
3287// Note that turnport_unittest.cc contains more detailed, lower-level tests.
3288TEST_F(PeerConnectionIntegrationTest, \
3289 TurnCustomizerUsedForTurnConnections) {
3290 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3291 3478};
3292 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3293 0};
3294 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3295 3478};
3296 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3297 0};
3298 cricket::TestTurnServer turn_server_1(network_thread(),
3299 turn_server_1_internal_address,
3300 turn_server_1_external_address);
3301 cricket::TestTurnServer turn_server_2(network_thread(),
3302 turn_server_2_internal_address,
3303 turn_server_2_external_address);
3304
3305 PeerConnectionInterface::RTCConfiguration client_1_config;
3306 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3307 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3308 ice_server_1.username = "test";
3309 ice_server_1.password = "test";
3310 client_1_config.servers.push_back(ice_server_1);
3311 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3312 auto customizer1 = rtc::MakeUnique<cricket::TestTurnCustomizer>();
3313 client_1_config.turn_customizer = customizer1.get();
3314
3315 PeerConnectionInterface::RTCConfiguration client_2_config;
3316 webrtc::PeerConnectionInterface::IceServer ice_server_2;
3317 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
3318 ice_server_2.username = "test";
3319 ice_server_2.password = "test";
3320 client_2_config.servers.push_back(ice_server_2);
3321 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
3322 auto customizer2 = rtc::MakeUnique<cricket::TestTurnCustomizer>();
3323 client_2_config.turn_customizer = customizer2.get();
3324
3325 ASSERT_TRUE(
3326 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
3327 ConnectFakeSignaling();
3328
3329 // Set "offer to receive audio/video" without adding any tracks, so we just
3330 // set up ICE/DTLS with no media.
3331 PeerConnectionInterface::RTCOfferAnswerOptions options;
3332 options.offer_to_receive_audio = 1;
3333 options.offer_to_receive_video = 1;
3334 caller()->SetOfferAnswerOptions(options);
3335 caller()->CreateAndSetAndSignalOffer();
3336 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
3337
3338 EXPECT_GT(customizer1->allow_channel_data_cnt_, 0u);
3339 EXPECT_GT(customizer1->modify_cnt_, 0u);
3340
3341 EXPECT_GT(customizer2->allow_channel_data_cnt_, 0u);
3342 EXPECT_GT(customizer2->modify_cnt_, 0u);
3343
3344 // Need to free the clients here since they're using things we created on
3345 // the stack.
3346 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
3347 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
3348}
3349
deadbeefc964d0b2017-04-03 10:03:35 -07003350// Test that audio and video flow end-to-end when codec names don't use the
3351// expected casing, given that they're supposed to be case insensitive. To test
3352// this, all but one codec is removed from each media description, and its
3353// casing is changed.
3354//
3355// In the past, this has regressed and caused crashes/black video, due to the
3356// fact that code at some layers was doing case-insensitive comparisons and
3357// code at other layers was not.
3358TEST_F(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
3359 ASSERT_TRUE(CreatePeerConnectionWrappers());
3360 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003361 caller()->AddAudioVideoTracks();
3362 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07003363
3364 // Remove all but one audio/video codec (opus and VP8), and change the
3365 // casing of the caller's generated offer.
3366 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
3367 cricket::AudioContentDescription* audio =
3368 GetFirstAudioContentDescription(description);
3369 ASSERT_NE(nullptr, audio);
3370 auto audio_codecs = audio->codecs();
3371 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
3372 [](const cricket::AudioCodec& codec) {
3373 return codec.name != "opus";
3374 }),
3375 audio_codecs.end());
3376 ASSERT_EQ(1u, audio_codecs.size());
3377 audio_codecs[0].name = "OpUs";
3378 audio->set_codecs(audio_codecs);
3379
3380 cricket::VideoContentDescription* video =
3381 GetFirstVideoContentDescription(description);
3382 ASSERT_NE(nullptr, video);
3383 auto video_codecs = video->codecs();
3384 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
3385 [](const cricket::VideoCodec& codec) {
3386 return codec.name != "VP8";
3387 }),
3388 video_codecs.end());
3389 ASSERT_EQ(1u, video_codecs.size());
3390 video_codecs[0].name = "vP8";
3391 video->set_codecs(video_codecs);
3392 });
3393
3394 caller()->CreateAndSetAndSignalOffer();
3395 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3396
3397 // Verify frames are still received end-to-end.
3398 ExpectNewFramesReceivedWithWait(
3399 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3400 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3401 kMaxWaitForFramesMs);
3402}
3403
hbos8d609f62017-04-10 07:39:05 -07003404TEST_F(PeerConnectionIntegrationTest, GetSources) {
3405 ASSERT_TRUE(CreatePeerConnectionWrappers());
3406 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003407 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07003408 caller()->CreateAndSetAndSignalOffer();
3409 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07003410 // Wait for one audio frame to be received by the callee.
hbos8d609f62017-04-10 07:39:05 -07003411 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
3412 ASSERT_GT(callee()->pc()->GetReceivers().size(), 0u);
3413 auto receiver = callee()->pc()->GetReceivers()[0];
3414 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
3415
3416 auto contributing_sources = receiver->GetSources();
3417 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
3418 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
3419 contributing_sources[0].source_id());
3420}
3421
deadbeef2f425aa2017-04-14 10:41:32 -07003422// Test that if a track is removed and added again with a different stream ID,
3423// the new stream ID is successfully communicated in SDP and media continues to
3424// flow end-to-end.
3425TEST_F(PeerConnectionIntegrationTest, RemoveAndAddTrackWithNewStreamId) {
3426 ASSERT_TRUE(CreatePeerConnectionWrappers());
3427 ConnectFakeSignaling();
3428
3429 rtc::scoped_refptr<MediaStreamInterface> stream_1 =
3430 caller()->pc_factory()->CreateLocalMediaStream("stream_1");
3431 rtc::scoped_refptr<MediaStreamInterface> stream_2 =
3432 caller()->pc_factory()->CreateLocalMediaStream("stream_2");
3433
3434 // Add track using stream 1, do offer/answer.
3435 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
3436 caller()->CreateLocalAudioTrack();
3437 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
3438 caller()->pc()->AddTrack(track, {stream_1.get()});
3439 caller()->CreateAndSetAndSignalOffer();
3440 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3441 // Wait for one audio frame to be received by the callee.
3442 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
3443
3444 // Remove the sender, and create a new one with the new stream.
3445 caller()->pc()->RemoveTrack(sender);
3446 sender = caller()->pc()->AddTrack(track, {stream_2.get()});
3447 caller()->CreateAndSetAndSignalOffer();
3448 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3449 // Wait for additional audio frames to be received by the callee.
3450 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount, 0,
3451 kMaxWaitForFramesMs);
3452}
3453
Elad Alon99c3fe52017-10-13 16:29:40 +02003454TEST_F(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
3455 ASSERT_TRUE(CreatePeerConnectionWrappers());
3456 ConnectFakeSignaling();
3457
3458 auto output = rtc::MakeUnique<testing::NiceMock<MockRtcEventLogOutput>>();
3459 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
3460 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
3461 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01003462 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
3463 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02003464
Steve Anton15324772018-01-16 10:26:49 -08003465 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02003466 caller()->CreateAndSetAndSignalOffer();
3467 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3468}
3469
Steve Antonede9ca52017-10-16 13:04:27 -07003470// Test that if candidates are only signaled by applying full session
3471// descriptions (instead of using AddIceCandidate), the peers can connect to
3472// each other and exchange media.
3473TEST_F(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
3474 ASSERT_TRUE(CreatePeerConnectionWrappers());
3475 // Each side will signal the session descriptions but not candidates.
3476 ConnectFakeSignalingForSdpOnly();
3477
3478 // Add audio video track and exchange the initial offer/answer with media
3479 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08003480 caller()->AddAudioVideoTracks();
3481 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003482 caller()->CreateAndSetAndSignalOffer();
3483
3484 // Wait for all candidates to be gathered on both the caller and callee.
3485 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
3486 caller()->ice_gathering_state(), kDefaultTimeout);
3487 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
3488 callee()->ice_gathering_state(), kDefaultTimeout);
3489
3490 // The candidates will now be included in the session description, so
3491 // signaling them will start the ICE connection.
3492 caller()->CreateAndSetAndSignalOffer();
3493 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3494
3495 // Ensure that media flows in both directions.
3496 ExpectNewFramesReceivedWithWait(
3497 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3498 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3499 kMaxWaitForFramesMs);
3500}
3501
henrika5f6bf242017-11-01 11:06:56 +01003502// Test that SetAudioPlayout can be used to disable audio playout from the
3503// start, then later enable it. This may be useful, for example, if the caller
3504// needs to play a local ringtone until some event occurs, after which it
3505// switches to playing the received audio.
3506TEST_F(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
3507 ASSERT_TRUE(CreatePeerConnectionWrappers());
3508 ConnectFakeSignaling();
3509
3510 // Set up audio-only call where audio playout is disabled on caller's side.
3511 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08003512 caller()->AddAudioTrack();
3513 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01003514 caller()->CreateAndSetAndSignalOffer();
3515 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3516
3517 // Pump messages for a second.
3518 WAIT(false, 1000);
3519 // Since audio playout is disabled, the caller shouldn't have received
3520 // anything (at the playout level, at least).
3521 EXPECT_EQ(0, caller()->audio_frames_received());
3522 // As a sanity check, make sure the callee (for which playout isn't disabled)
3523 // did still see frames on its audio level.
3524 ASSERT_GT(callee()->audio_frames_received(), 0);
3525
3526 // Enable playout again, and ensure audio starts flowing.
3527 caller()->pc()->SetAudioPlayout(true);
3528 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
3529 kDefaultExpectedAudioFrameCount, 0,
3530 kMaxWaitForFramesMs);
3531}
3532
3533double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
3534 auto report = pc->NewGetStats();
3535 auto track_stats_list =
3536 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3537 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
3538 for (const auto* track_stats : track_stats_list) {
3539 if (track_stats->remote_source.is_defined() &&
3540 *track_stats->remote_source) {
3541 remote_track_stats = track_stats;
3542 break;
3543 }
3544 }
3545
3546 if (!remote_track_stats->total_audio_energy.is_defined()) {
3547 return 0.0;
3548 }
3549 return *remote_track_stats->total_audio_energy;
3550}
3551
3552// Test that if audio playout is disabled via the SetAudioPlayout() method, then
3553// incoming audio is still processed and statistics are generated.
3554TEST_F(PeerConnectionIntegrationTest,
3555 DisableAudioPlayoutStillGeneratesAudioStats) {
3556 ASSERT_TRUE(CreatePeerConnectionWrappers());
3557 ConnectFakeSignaling();
3558
3559 // Set up audio-only call where playout is disabled but audio-processing is
3560 // still active.
Steve Anton15324772018-01-16 10:26:49 -08003561 caller()->AddAudioTrack();
3562 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01003563 caller()->pc()->SetAudioPlayout(false);
3564
3565 caller()->CreateAndSetAndSignalOffer();
3566 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3567
3568 // Wait for the callee to receive audio stats.
3569 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
3570}
3571
henrika4f167df2017-11-01 14:45:55 +01003572// Test that SetAudioRecording can be used to disable audio recording from the
3573// start, then later enable it. This may be useful, for example, if the caller
3574// wants to ensure that no audio resources are active before a certain state
3575// is reached.
3576TEST_F(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
3577 ASSERT_TRUE(CreatePeerConnectionWrappers());
3578 ConnectFakeSignaling();
3579
3580 // Set up audio-only call where audio recording is disabled on caller's side.
3581 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08003582 caller()->AddAudioTrack();
3583 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01003584 caller()->CreateAndSetAndSignalOffer();
3585 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3586
3587 // Pump messages for a second.
3588 WAIT(false, 1000);
3589 // Since caller has disabled audio recording, the callee shouldn't have
3590 // received anything.
3591 EXPECT_EQ(0, callee()->audio_frames_received());
3592 // As a sanity check, make sure the caller did still see frames on its
3593 // audio level since audio recording is enabled on the calle side.
3594 ASSERT_GT(caller()->audio_frames_received(), 0);
3595
3596 // Enable audio recording again, and ensure audio starts flowing.
3597 caller()->pc()->SetAudioRecording(true);
3598 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
3599 kDefaultExpectedAudioFrameCount, 0,
3600 kMaxWaitForFramesMs);
3601}
3602
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08003603// Test that after closing PeerConnections, they stop sending any packets (ICE,
3604// DTLS, RTP...).
3605TEST_F(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
3606 // Set up audio/video/data, wait for some frames to be received.
3607 ASSERT_TRUE(CreatePeerConnectionWrappers());
3608 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003609 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08003610#ifdef HAVE_SCTP
3611 caller()->CreateDataChannel();
3612#endif
3613 caller()->CreateAndSetAndSignalOffer();
3614 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3615 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount,
3616 kDefaultExpectedAudioFrameCount,
3617 kMaxWaitForFramesMs);
3618 // Close PeerConnections.
3619 caller()->pc()->Close();
3620 callee()->pc()->Close();
3621 // Pump messages for a second, and ensure no new packets end up sent.
3622 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
3623 WAIT(false, 1000);
3624 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
3625 EXPECT_EQ(sent_packets_a, sent_packets_b);
3626}
3627
deadbeef1dcb1642017-03-29 21:08:16 -07003628} // namespace
3629
3630#endif // if !defined(THREAD_SANITIZER)