blob: 788b432eddadf0193910c19dd2e05782ead64029 [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;
Steve Anton74255ff2018-01-24 18:32:57 -080083using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -070084using webrtc::PeerConnectionFactory;
Steve Anton8c0f7a72017-10-03 10:03:10 -070085using webrtc::PeerConnectionProxy;
Steve Anton15324772018-01-16 10:26:49 -080086using webrtc::RTCErrorType;
Steve Anton74255ff2018-01-24 18:32:57 -080087using webrtc::RtpSenderInterface;
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +010088using webrtc::RtpReceiverInterface;
Steve Antond3679212018-01-17 17:41:02 -080089using webrtc::SdpSemantics;
Steve Antona3a92c22017-12-07 10:27:41 -080090using webrtc::SdpType;
deadbeef1dcb1642017-03-29 21:08:16 -070091using webrtc::SessionDescriptionInterface;
92using webrtc::StreamCollectionInterface;
Steve Anton15324772018-01-16 10:26:49 -080093using webrtc::VideoTrackInterface;
deadbeef1dcb1642017-03-29 21:08:16 -070094
95namespace {
96
97static const int kDefaultTimeout = 10000;
98static const int kMaxWaitForStatsMs = 3000;
99static const int kMaxWaitForActivationMs = 5000;
100static const int kMaxWaitForFramesMs = 10000;
101// Default number of audio/video frames to wait for before considering a test
102// successful.
103static const int kDefaultExpectedAudioFrameCount = 3;
104static const int kDefaultExpectedVideoFrameCount = 3;
105
deadbeef1dcb1642017-03-29 21:08:16 -0700106static const char kDataChannelLabel[] = "data_channel";
107
108// SRTP cipher name negotiated by the tests. This must be updated if the
109// default changes.
Tommi8e545ee2018-02-08 16:25:20 +0000110static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_32;
deadbeef1dcb1642017-03-29 21:08:16 -0700111static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
112
Steve Antonede9ca52017-10-16 13:04:27 -0700113static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
114
deadbeef1dcb1642017-03-29 21:08:16 -0700115// Helper function for constructing offer/answer options to initiate an ICE
116// restart.
117PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
118 PeerConnectionInterface::RTCOfferAnswerOptions options;
119 options.ice_restart = true;
120 return options;
121}
122
deadbeefd8ad7882017-04-18 16:01:17 -0700123// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
124// attribute from received SDP, simulating a legacy endpoint.
125void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
126 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800127 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700128 }
129 desc->set_msid_supported(false);
130}
131
zhihuangf8164932017-05-19 13:09:47 -0700132int FindFirstMediaStatsIndexByKind(
133 const std::string& kind,
134 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
135 media_stats_vec) {
136 for (size_t i = 0; i < media_stats_vec.size(); i++) {
137 if (media_stats_vec[i]->kind.ValueToString() == kind) {
138 return i;
139 }
140 }
141 return -1;
142}
143
deadbeef1dcb1642017-03-29 21:08:16 -0700144class SignalingMessageReceiver {
145 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800146 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700147 virtual void ReceiveIceMessage(const std::string& sdp_mid,
148 int sdp_mline_index,
149 const std::string& msg) = 0;
150
151 protected:
152 SignalingMessageReceiver() {}
153 virtual ~SignalingMessageReceiver() {}
154};
155
156class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
157 public:
158 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
159 : expected_media_type_(media_type) {}
160
161 void OnFirstPacketReceived(cricket::MediaType media_type) override {
162 ASSERT_EQ(expected_media_type_, media_type);
163 first_packet_received_ = true;
164 }
165
166 bool first_packet_received() const { return first_packet_received_; }
167
168 virtual ~MockRtpReceiverObserver() {}
169
170 private:
171 bool first_packet_received_ = false;
172 cricket::MediaType expected_media_type_;
173};
174
175// Helper class that wraps a peer connection, observes it, and can accept
176// signaling messages from another wrapper.
177//
178// Uses a fake network, fake A/V capture, and optionally fake
179// encoders/decoders, though they aren't used by default since they don't
180// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700181// TODO(steveanton): See how this could become a subclass of
182// PeerConnectionWrapper defined in peerconnectionwrapper.h .
deadbeef1dcb1642017-03-29 21:08:16 -0700183class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800184 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700185 public:
186 // Different factory methods for convenience.
187 // TODO(deadbeef): Could use the pattern of:
188 //
189 // PeerConnectionWrapper =
190 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
191 //
192 // To reduce some code duplication.
193 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
194 const std::string& debug_name,
195 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
196 rtc::Thread* network_thread,
197 rtc::Thread* worker_thread) {
198 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
199 if (!client->Init(nullptr, nullptr, nullptr, std::move(cert_generator),
200 network_thread, worker_thread)) {
201 delete client;
202 return nullptr;
203 }
204 return client;
205 }
206
207 static PeerConnectionWrapper* CreateWithConfig(
208 const std::string& debug_name,
209 const PeerConnectionInterface::RTCConfiguration& config,
210 rtc::Thread* network_thread,
211 rtc::Thread* worker_thread) {
212 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
213 new FakeRTCCertificateGenerator());
214 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
215 if (!client->Init(nullptr, nullptr, &config, std::move(cert_generator),
216 network_thread, worker_thread)) {
217 delete client;
218 return nullptr;
219 }
220 return client;
221 }
222
223 static PeerConnectionWrapper* CreateWithOptions(
224 const std::string& debug_name,
225 const PeerConnectionFactory::Options& options,
226 rtc::Thread* network_thread,
227 rtc::Thread* worker_thread) {
228 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
229 new FakeRTCCertificateGenerator());
230 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
231 if (!client->Init(nullptr, &options, nullptr, std::move(cert_generator),
232 network_thread, worker_thread)) {
233 delete client;
234 return nullptr;
235 }
236 return client;
237 }
238
239 static PeerConnectionWrapper* CreateWithConstraints(
240 const std::string& debug_name,
241 const MediaConstraintsInterface* constraints,
242 rtc::Thread* network_thread,
243 rtc::Thread* worker_thread) {
244 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
245 new FakeRTCCertificateGenerator());
246 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
247 if (!client->Init(constraints, nullptr, nullptr, std::move(cert_generator),
248 network_thread, worker_thread)) {
249 delete client;
250 return nullptr;
251 }
252 return client;
253 }
254
deadbeef2f425aa2017-04-14 10:41:32 -0700255 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
256 return peer_connection_factory_.get();
257 }
258
deadbeef1dcb1642017-03-29 21:08:16 -0700259 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
260
261 // If a signaling message receiver is set (via ConnectFakeSignaling), this
262 // will set the whole offer/answer exchange in motion. Just need to wait for
263 // the signaling state to reach "stable".
264 void CreateAndSetAndSignalOffer() {
265 auto offer = CreateOffer();
266 ASSERT_NE(nullptr, offer);
267 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
268 }
269
270 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
271 // when a remote offer is received (via fake signaling) and an answer is
272 // generated. By default, uses default options.
273 void SetOfferAnswerOptions(
274 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
275 offer_answer_options_ = options;
276 }
277
278 // Set a callback to be invoked when SDP is received via the fake signaling
279 // channel, which provides an opportunity to munge (modify) the SDP. This is
280 // used to test SDP being applied that a PeerConnection would normally not
281 // generate, but a non-JSEP endpoint might.
282 void SetReceivedSdpMunger(
283 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100284 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700285 }
286
deadbeefc964d0b2017-04-03 10:03:35 -0700287 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700288 // generated.
289 void SetGeneratedSdpMunger(
290 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100291 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700292 }
293
Steve Antonede9ca52017-10-16 13:04:27 -0700294 // Every ICE connection state in order that has been seen by the observer.
295 std::vector<PeerConnectionInterface::IceConnectionState>
296 ice_connection_state_history() const {
297 return ice_connection_state_history_;
298 }
Steve Anton6f25b092017-10-23 09:39:20 -0700299 void clear_ice_connection_state_history() {
300 ice_connection_state_history_.clear();
301 }
Steve Antonede9ca52017-10-16 13:04:27 -0700302
303 // Every ICE gathering state in order that has been seen by the observer.
304 std::vector<PeerConnectionInterface::IceGatheringState>
305 ice_gathering_state_history() const {
306 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700307 }
308
Steve Anton15324772018-01-16 10:26:49 -0800309 void AddAudioVideoTracks() {
310 AddAudioTrack();
311 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700312 }
313
Steve Anton74255ff2018-01-24 18:32:57 -0800314 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
315 return AddTrack(CreateLocalAudioTrack());
316 }
deadbeef1dcb1642017-03-29 21:08:16 -0700317
Steve Anton74255ff2018-01-24 18:32:57 -0800318 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
319 return AddTrack(CreateLocalVideoTrack());
320 }
deadbeef1dcb1642017-03-29 21:08:16 -0700321
322 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
323 FakeConstraints constraints;
324 // Disable highpass filter so that we can get all the test audio frames.
325 constraints.AddMandatory(MediaConstraintsInterface::kHighpassFilter, false);
326 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
327 peer_connection_factory_->CreateAudioSource(&constraints);
328 // TODO(perkj): Test audio source when it is implemented. Currently audio
329 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700330 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700331 source);
332 }
333
334 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
deadbeefb1a15d72017-09-07 14:12:05 -0700335 return CreateLocalVideoTrackInternal(FakeConstraints(),
336 webrtc::kVideoRotation_0);
deadbeef1dcb1642017-03-29 21:08:16 -0700337 }
338
339 rtc::scoped_refptr<webrtc::VideoTrackInterface>
340 CreateLocalVideoTrackWithConstraints(const FakeConstraints& constraints) {
deadbeefb1a15d72017-09-07 14:12:05 -0700341 return CreateLocalVideoTrackInternal(constraints, webrtc::kVideoRotation_0);
deadbeef1dcb1642017-03-29 21:08:16 -0700342 }
343
344 rtc::scoped_refptr<webrtc::VideoTrackInterface>
345 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
deadbeefb1a15d72017-09-07 14:12:05 -0700346 return CreateLocalVideoTrackInternal(FakeConstraints(), rotation);
deadbeef1dcb1642017-03-29 21:08:16 -0700347 }
348
Steve Anton74255ff2018-01-24 18:32:57 -0800349 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
350 rtc::scoped_refptr<MediaStreamTrackInterface> track,
351 const std::vector<std::string>& stream_labels = {}) {
Steve Anton15324772018-01-16 10:26:49 -0800352 auto result = pc()->AddTrack(track, stream_labels);
353 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800354 return result.MoveValue();
355 }
356
357 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
358 cricket::MediaType media_type) {
359 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
360 for (auto receiver : pc()->GetReceivers()) {
361 if (receiver->media_type() == media_type) {
362 receivers.push_back(receiver);
363 }
364 }
365 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700366 }
367
368 bool SignalingStateStable() {
369 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
370 }
371
372 void CreateDataChannel() { CreateDataChannel(nullptr); }
373
374 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700375 CreateDataChannel(kDataChannelLabel, init);
376 }
377
378 void CreateDataChannel(const std::string& label,
379 const webrtc::DataChannelInit* init) {
380 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700381 ASSERT_TRUE(data_channel_.get() != nullptr);
382 data_observer_.reset(new MockDataChannelObserver(data_channel_));
383 }
384
385 DataChannelInterface* data_channel() { return data_channel_; }
386 const MockDataChannelObserver* data_observer() const {
387 return data_observer_.get();
388 }
389
390 int audio_frames_received() const {
391 return fake_audio_capture_module_->frames_received();
392 }
393
394 // Takes minimum of video frames received for each track.
395 //
396 // Can be used like:
397 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
398 //
399 // To ensure that all video tracks received at least a certain number of
400 // frames.
401 int min_video_frames_received_per_track() const {
402 int min_frames = INT_MAX;
403 if (video_decoder_factory_enabled_) {
404 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
405 fake_video_decoder_factory_->decoders();
406 if (decoders.empty()) {
407 return 0;
408 }
409 for (FakeWebRtcVideoDecoder* decoder : decoders) {
410 min_frames = std::min(min_frames, decoder->GetNumFramesReceived());
411 }
412 return min_frames;
413 } else {
414 if (fake_video_renderers_.empty()) {
415 return 0;
416 }
417
418 for (const auto& pair : fake_video_renderers_) {
419 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
420 }
421 return min_frames;
422 }
423 }
424
425 // In contrast to the above, sums the video frames received for all tracks.
426 // Can be used to verify that no video frames were received, or that the
427 // counts didn't increase.
428 int total_video_frames_received() const {
429 int total = 0;
430 if (video_decoder_factory_enabled_) {
431 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
432 fake_video_decoder_factory_->decoders();
433 for (const FakeWebRtcVideoDecoder* decoder : decoders) {
434 total += decoder->GetNumFramesReceived();
435 }
436 } else {
437 for (const auto& pair : fake_video_renderers_) {
438 total += pair.second->num_rendered_frames();
439 }
440 for (const auto& renderer : removed_fake_video_renderers_) {
441 total += renderer->num_rendered_frames();
442 }
443 }
444 return total;
445 }
446
447 // Returns a MockStatsObserver in a state after stats gathering finished,
448 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700449 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700450 webrtc::MediaStreamTrackInterface* track) {
451 rtc::scoped_refptr<MockStatsObserver> observer(
452 new rtc::RefCountedObject<MockStatsObserver>());
453 EXPECT_TRUE(peer_connection_->GetStats(
454 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
455 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
456 return observer;
457 }
458
459 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700460 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
461 return OldGetStatsForTrack(nullptr);
462 }
463
464 // Synchronously gets stats and returns them. If it times out, fails the test
465 // and returns null.
466 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
467 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
468 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
469 peer_connection_->GetStats(callback);
470 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
471 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700472 }
473
474 int rendered_width() {
475 EXPECT_FALSE(fake_video_renderers_.empty());
476 return fake_video_renderers_.empty()
477 ? 0
478 : fake_video_renderers_.begin()->second->width();
479 }
480
481 int rendered_height() {
482 EXPECT_FALSE(fake_video_renderers_.empty());
483 return fake_video_renderers_.empty()
484 ? 0
485 : fake_video_renderers_.begin()->second->height();
486 }
487
488 double rendered_aspect_ratio() {
489 if (rendered_height() == 0) {
490 return 0.0;
491 }
492 return static_cast<double>(rendered_width()) / rendered_height();
493 }
494
495 webrtc::VideoRotation rendered_rotation() {
496 EXPECT_FALSE(fake_video_renderers_.empty());
497 return fake_video_renderers_.empty()
498 ? webrtc::kVideoRotation_0
499 : fake_video_renderers_.begin()->second->rotation();
500 }
501
502 int local_rendered_width() {
503 return local_video_renderer_ ? local_video_renderer_->width() : 0;
504 }
505
506 int local_rendered_height() {
507 return local_video_renderer_ ? local_video_renderer_->height() : 0;
508 }
509
510 double local_rendered_aspect_ratio() {
511 if (local_rendered_height() == 0) {
512 return 0.0;
513 }
514 return static_cast<double>(local_rendered_width()) /
515 local_rendered_height();
516 }
517
518 size_t number_of_remote_streams() {
519 if (!pc()) {
520 return 0;
521 }
522 return pc()->remote_streams()->count();
523 }
524
525 StreamCollectionInterface* remote_streams() const {
526 if (!pc()) {
527 ADD_FAILURE();
528 return nullptr;
529 }
530 return pc()->remote_streams();
531 }
532
533 StreamCollectionInterface* local_streams() {
534 if (!pc()) {
535 ADD_FAILURE();
536 return nullptr;
537 }
538 return pc()->local_streams();
539 }
540
541 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
542 return pc()->signaling_state();
543 }
544
545 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
546 return pc()->ice_connection_state();
547 }
548
549 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
550 return pc()->ice_gathering_state();
551 }
552
553 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
554 // GetReceivers. They're updated automatically when a remote offer/answer
555 // from the fake signaling channel is applied, or when
556 // ResetRtpReceiverObservers below is called.
557 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
558 rtp_receiver_observers() {
559 return rtp_receiver_observers_;
560 }
561
562 void ResetRtpReceiverObservers() {
563 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100564 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
565 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700566 std::unique_ptr<MockRtpReceiverObserver> observer(
567 new MockRtpReceiverObserver(receiver->media_type()));
568 receiver->SetObserver(observer.get());
569 rtp_receiver_observers_.push_back(std::move(observer));
570 }
571 }
572
Steve Antonede9ca52017-10-16 13:04:27 -0700573 rtc::FakeNetworkManager* network() const {
574 return fake_network_manager_.get();
575 }
576 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
577
deadbeef1dcb1642017-03-29 21:08:16 -0700578 private:
579 explicit PeerConnectionWrapper(const std::string& debug_name)
580 : debug_name_(debug_name) {}
581
582 bool Init(
583 const MediaConstraintsInterface* constraints,
584 const PeerConnectionFactory::Options* options,
585 const PeerConnectionInterface::RTCConfiguration* config,
586 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
587 rtc::Thread* network_thread,
588 rtc::Thread* worker_thread) {
589 // There's an error in this test code if Init ends up being called twice.
590 RTC_DCHECK(!peer_connection_);
591 RTC_DCHECK(!peer_connection_factory_);
592
593 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700594 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700595
596 std::unique_ptr<cricket::PortAllocator> port_allocator(
597 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700598 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700599 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
600 if (!fake_audio_capture_module_) {
601 return false;
602 }
603 // Note that these factories don't end up getting used unless supported
604 // codecs are added to them.
605 fake_video_decoder_factory_ = new FakeWebRtcVideoDecoderFactory();
606 fake_video_encoder_factory_ = new FakeWebRtcVideoEncoderFactory();
607 rtc::Thread* const signaling_thread = rtc::Thread::Current();
608 peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(
609 network_thread, worker_thread, signaling_thread,
Karl Wiberg1b0eae32017-10-17 14:48:54 +0200610 fake_audio_capture_module_, webrtc::CreateBuiltinAudioEncoderFactory(),
611 webrtc::CreateBuiltinAudioDecoderFactory(), fake_video_encoder_factory_,
deadbeef1dcb1642017-03-29 21:08:16 -0700612 fake_video_decoder_factory_);
613 if (!peer_connection_factory_) {
614 return false;
615 }
616 if (options) {
617 peer_connection_factory_->SetOptions(*options);
618 }
619 peer_connection_ =
620 CreatePeerConnection(std::move(port_allocator), constraints, config,
621 std::move(cert_generator));
622 return peer_connection_.get() != nullptr;
623 }
624
625 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
626 std::unique_ptr<cricket::PortAllocator> port_allocator,
627 const MediaConstraintsInterface* constraints,
628 const PeerConnectionInterface::RTCConfiguration* config,
629 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator) {
630 PeerConnectionInterface::RTCConfiguration modified_config;
631 // If |config| is null, this will result in a default configuration being
632 // used.
633 if (config) {
634 modified_config = *config;
635 }
636 // Disable resolution adaptation; we don't want it interfering with the
637 // test results.
638 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
639 // ratios and not specific resolutions, is this even necessary?
640 modified_config.set_cpu_adaptation(false);
641
642 return peer_connection_factory_->CreatePeerConnection(
643 modified_config, constraints, std::move(port_allocator),
644 std::move(cert_generator), this);
645 }
646
647 void set_signaling_message_receiver(
648 SignalingMessageReceiver* signaling_message_receiver) {
649 signaling_message_receiver_ = signaling_message_receiver;
650 }
651
652 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
653
Steve Antonede9ca52017-10-16 13:04:27 -0700654 void set_signal_ice_candidates(bool signal) {
655 signal_ice_candidates_ = signal;
656 }
657
deadbeef1dcb1642017-03-29 21:08:16 -0700658 void EnableVideoDecoderFactory() {
659 video_decoder_factory_enabled_ = true;
660 fake_video_decoder_factory_->AddSupportedVideoCodecType(
661 webrtc::kVideoCodecVP8);
662 }
663
664 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
deadbeef1dcb1642017-03-29 21:08:16 -0700665 const FakeConstraints& constraints,
666 webrtc::VideoRotation rotation) {
667 // Set max frame rate to 10fps to reduce the risk of test flakiness.
668 // TODO(deadbeef): Do something more robust.
669 FakeConstraints source_constraints = constraints;
670 source_constraints.SetMandatoryMaxFrameRate(10);
671
672 cricket::FakeVideoCapturer* fake_capturer =
673 new webrtc::FakePeriodicVideoCapturer();
674 fake_capturer->SetRotation(rotation);
675 video_capturers_.push_back(fake_capturer);
676 rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source =
677 peer_connection_factory_->CreateVideoSource(fake_capturer,
678 &source_constraints);
679 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
deadbeefb1a15d72017-09-07 14:12:05 -0700680 peer_connection_factory_->CreateVideoTrack(rtc::CreateRandomUuid(),
681 source));
deadbeef1dcb1642017-03-29 21:08:16 -0700682 if (!local_video_renderer_) {
683 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
684 }
685 return track;
686 }
687
688 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100689 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800690 std::unique_ptr<SessionDescriptionInterface> desc =
691 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700692 if (received_sdp_munger_) {
693 received_sdp_munger_(desc->description());
694 }
695
696 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
697 // Setting a remote description may have changed the number of receivers,
698 // so reset the receiver observers.
699 ResetRtpReceiverObservers();
700 auto answer = CreateAnswer();
701 ASSERT_NE(nullptr, answer);
702 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
703 }
704
705 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100706 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800707 std::unique_ptr<SessionDescriptionInterface> desc =
708 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700709 if (received_sdp_munger_) {
710 received_sdp_munger_(desc->description());
711 }
712
713 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
714 // Set the RtpReceiverObserver after receivers are created.
715 ResetRtpReceiverObservers();
716 }
717
718 // Returns null on failure.
719 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
720 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
721 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
722 pc()->CreateOffer(observer, offer_answer_options_);
723 return WaitForDescriptionFromObserver(observer);
724 }
725
726 // Returns null on failure.
727 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
728 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
729 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
730 pc()->CreateAnswer(observer, offer_answer_options_);
731 return WaitForDescriptionFromObserver(observer);
732 }
733
734 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100735 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700736 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
737 if (!observer->result()) {
738 return nullptr;
739 }
740 auto description = observer->MoveDescription();
741 if (generated_sdp_munger_) {
742 generated_sdp_munger_(description->description());
743 }
744 return description;
745 }
746
747 // Setting the local description and sending the SDP message over the fake
748 // signaling channel are combined into the same method because the SDP
749 // message needs to be sent as soon as SetLocalDescription finishes, without
750 // waiting for the observer to be called. This ensures that ICE candidates
751 // don't outrace the description.
752 bool SetLocalDescriptionAndSendSdpMessage(
753 std::unique_ptr<SessionDescriptionInterface> desc) {
754 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
755 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100756 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800757 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700758 std::string sdp;
759 EXPECT_TRUE(desc->ToString(&sdp));
760 pc()->SetLocalDescription(observer, desc.release());
761 // As mentioned above, we need to send the message immediately after
762 // SetLocalDescription.
763 SendSdpMessage(type, sdp);
764 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
765 return true;
766 }
767
768 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
769 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
770 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100771 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700772 pc()->SetRemoteDescription(observer, desc.release());
773 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
774 return observer->result();
775 }
776
777 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
778 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800779 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700780 if (signaling_delay_ms_ == 0) {
781 RelaySdpMessageIfReceiverExists(type, msg);
782 } else {
783 invoker_.AsyncInvokeDelayed<void>(
784 RTC_FROM_HERE, rtc::Thread::Current(),
785 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
786 this, type, msg),
787 signaling_delay_ms_);
788 }
789 }
790
Steve Antona3a92c22017-12-07 10:27:41 -0800791 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700792 if (signaling_message_receiver_) {
793 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
794 }
795 }
796
797 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
798 // default).
799 void SendIceMessage(const std::string& sdp_mid,
800 int sdp_mline_index,
801 const std::string& msg) {
802 if (signaling_delay_ms_ == 0) {
803 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
804 } else {
805 invoker_.AsyncInvokeDelayed<void>(
806 RTC_FROM_HERE, rtc::Thread::Current(),
807 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
808 this, sdp_mid, sdp_mline_index, msg),
809 signaling_delay_ms_);
810 }
811 }
812
813 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
814 int sdp_mline_index,
815 const std::string& msg) {
816 if (signaling_message_receiver_) {
817 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
818 msg);
819 }
820 }
821
822 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800823 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
824 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700825 HandleIncomingOffer(msg);
826 } else {
827 HandleIncomingAnswer(msg);
828 }
829 }
830
831 void ReceiveIceMessage(const std::string& sdp_mid,
832 int sdp_mline_index,
833 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100834 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700835 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
836 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
837 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
838 }
839
840 // PeerConnectionObserver callbacks.
841 void OnSignalingChange(
842 webrtc::PeerConnectionInterface::SignalingState new_state) override {
843 EXPECT_EQ(pc()->signaling_state(), new_state);
844 }
Steve Anton15324772018-01-16 10:26:49 -0800845 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
846 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
847 streams) override {
848 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
849 rtc::scoped_refptr<VideoTrackInterface> video_track(
850 static_cast<VideoTrackInterface*>(receiver->track().get()));
851 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700852 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800853 fake_video_renderers_[video_track->id()] =
854 rtc::MakeUnique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700855 }
856 }
Steve Anton15324772018-01-16 10:26:49 -0800857 void OnRemoveTrack(
858 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
859 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
860 auto it = fake_video_renderers_.find(receiver->track()->id());
861 RTC_DCHECK(it != fake_video_renderers_.end());
862 fake_video_renderers_.erase(it);
863 }
864 }
deadbeef1dcb1642017-03-29 21:08:16 -0700865 void OnRenegotiationNeeded() override {}
866 void OnIceConnectionChange(
867 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
868 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700869 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700870 }
871 void OnIceGatheringChange(
872 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700873 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700874 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700875 }
876 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100877 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700878
879 std::string ice_sdp;
880 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700881 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700882 // Remote party may be deleted.
883 return;
884 }
885 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
886 }
887 void OnDataChannel(
888 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100889 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700890 data_channel_ = data_channel;
891 data_observer_.reset(new MockDataChannelObserver(data_channel));
892 }
893
deadbeef1dcb1642017-03-29 21:08:16 -0700894 std::string debug_name_;
895
896 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
897
898 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
899 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
900 peer_connection_factory_;
901
Steve Antonede9ca52017-10-16 13:04:27 -0700902 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700903 // Needed to keep track of number of frames sent.
904 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
905 // Needed to keep track of number of frames received.
906 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
907 fake_video_renderers_;
908 // Needed to ensure frames aren't received for removed tracks.
909 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
910 removed_fake_video_renderers_;
911 // Needed to keep track of number of frames received when external decoder
912 // used.
913 FakeWebRtcVideoDecoderFactory* fake_video_decoder_factory_ = nullptr;
914 FakeWebRtcVideoEncoderFactory* fake_video_encoder_factory_ = nullptr;
915 bool video_decoder_factory_enabled_ = false;
916
917 // For remote peer communication.
918 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
919 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -0700920 bool signal_ice_candidates_ = true;
deadbeef1dcb1642017-03-29 21:08:16 -0700921
922 // Store references to the video capturers we've created, so that we can stop
923 // them, if required.
924 std::vector<cricket::FakeVideoCapturer*> video_capturers_;
925 // |local_video_renderer_| attached to the first created local video track.
926 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
927
928 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
929 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
930 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
931
932 rtc::scoped_refptr<DataChannelInterface> data_channel_;
933 std::unique_ptr<MockDataChannelObserver> data_observer_;
934
935 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
936
Steve Antonede9ca52017-10-16 13:04:27 -0700937 std::vector<PeerConnectionInterface::IceConnectionState>
938 ice_connection_state_history_;
939 std::vector<PeerConnectionInterface::IceGatheringState>
940 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700941
942 rtc::AsyncInvoker invoker_;
943
944 friend class PeerConnectionIntegrationTest;
945};
946
Elad Alon99c3fe52017-10-13 16:29:40 +0200947class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
948 public:
949 virtual ~MockRtcEventLogOutput() = default;
950 MOCK_CONST_METHOD0(IsActive, bool());
951 MOCK_METHOD1(Write, bool(const std::string&));
952};
953
deadbeef1dcb1642017-03-29 21:08:16 -0700954// Tests two PeerConnections connecting to each other end-to-end, using a
955// virtual network, fake A/V capture and fake encoder/decoders. The
956// PeerConnections share the threads/socket servers, but use separate versions
957// of everything else (including "PeerConnectionFactory"s).
958class PeerConnectionIntegrationTest : public testing::Test {
959 public:
960 PeerConnectionIntegrationTest()
deadbeef98e186c2017-05-16 18:00:06 -0700961 : ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -0700962 fss_(new rtc::FirewallSocketServer(ss_.get())),
963 network_thread_(new rtc::Thread(fss_.get())),
deadbeef1dcb1642017-03-29 21:08:16 -0700964 worker_thread_(rtc::Thread::Create()) {
965 RTC_CHECK(network_thread_->Start());
966 RTC_CHECK(worker_thread_->Start());
967 }
968
969 ~PeerConnectionIntegrationTest() {
970 if (caller_) {
971 caller_->set_signaling_message_receiver(nullptr);
972 }
973 if (callee_) {
974 callee_->set_signaling_message_receiver(nullptr);
975 }
976 }
977
978 bool SignalingStateStable() {
979 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
980 }
981
deadbeef71452802017-05-07 17:21:01 -0700982 bool DtlsConnected() {
983 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
984 // are connected. This is an important distinction. Once we have separate
985 // ICE and DTLS state, this check needs to use the DTLS state.
986 return (callee()->ice_connection_state() ==
987 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
988 callee()->ice_connection_state() ==
989 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
990 (caller()->ice_connection_state() ==
991 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
992 caller()->ice_connection_state() ==
993 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
994 }
995
deadbeef1dcb1642017-03-29 21:08:16 -0700996 bool CreatePeerConnectionWrappers() {
997 return CreatePeerConnectionWrappersWithConfig(
998 PeerConnectionInterface::RTCConfiguration(),
999 PeerConnectionInterface::RTCConfiguration());
1000 }
1001
1002 bool CreatePeerConnectionWrappersWithConstraints(
1003 MediaConstraintsInterface* caller_constraints,
1004 MediaConstraintsInterface* callee_constraints) {
1005 caller_.reset(PeerConnectionWrapper::CreateWithConstraints(
1006 "Caller", caller_constraints, network_thread_.get(),
1007 worker_thread_.get()));
1008 callee_.reset(PeerConnectionWrapper::CreateWithConstraints(
1009 "Callee", callee_constraints, network_thread_.get(),
1010 worker_thread_.get()));
1011 return caller_ && callee_;
1012 }
1013
1014 bool CreatePeerConnectionWrappersWithConfig(
1015 const PeerConnectionInterface::RTCConfiguration& caller_config,
1016 const PeerConnectionInterface::RTCConfiguration& callee_config) {
1017 caller_.reset(PeerConnectionWrapper::CreateWithConfig(
1018 "Caller", caller_config, network_thread_.get(), worker_thread_.get()));
1019 callee_.reset(PeerConnectionWrapper::CreateWithConfig(
1020 "Callee", callee_config, network_thread_.get(), worker_thread_.get()));
1021 return caller_ && callee_;
1022 }
1023
1024 bool CreatePeerConnectionWrappersWithOptions(
1025 const PeerConnectionFactory::Options& caller_options,
1026 const PeerConnectionFactory::Options& callee_options) {
1027 caller_.reset(PeerConnectionWrapper::CreateWithOptions(
1028 "Caller", caller_options, network_thread_.get(), worker_thread_.get()));
1029 callee_.reset(PeerConnectionWrapper::CreateWithOptions(
1030 "Callee", callee_options, network_thread_.get(), worker_thread_.get()));
1031 return caller_ && callee_;
1032 }
1033
1034 PeerConnectionWrapper* CreatePeerConnectionWrapperWithAlternateKey() {
1035 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1036 new FakeRTCCertificateGenerator());
1037 cert_generator->use_alternate_key();
1038
1039 // Make sure the new client is using a different certificate.
1040 return PeerConnectionWrapper::CreateWithDtlsIdentityStore(
1041 "New Peer", std::move(cert_generator), network_thread_.get(),
1042 worker_thread_.get());
1043 }
1044
1045 // Once called, SDP blobs and ICE candidates will be automatically signaled
1046 // between PeerConnections.
1047 void ConnectFakeSignaling() {
1048 caller_->set_signaling_message_receiver(callee_.get());
1049 callee_->set_signaling_message_receiver(caller_.get());
1050 }
1051
Steve Antonede9ca52017-10-16 13:04:27 -07001052 // Once called, SDP blobs will be automatically signaled between
1053 // PeerConnections. Note that ICE candidates will not be signaled unless they
1054 // are in the exchanged SDP blobs.
1055 void ConnectFakeSignalingForSdpOnly() {
1056 ConnectFakeSignaling();
1057 SetSignalIceCandidates(false);
1058 }
1059
deadbeef1dcb1642017-03-29 21:08:16 -07001060 void SetSignalingDelayMs(int delay_ms) {
1061 caller_->set_signaling_delay_ms(delay_ms);
1062 callee_->set_signaling_delay_ms(delay_ms);
1063 }
1064
Steve Antonede9ca52017-10-16 13:04:27 -07001065 void SetSignalIceCandidates(bool signal) {
1066 caller_->set_signal_ice_candidates(signal);
1067 callee_->set_signal_ice_candidates(signal);
1068 }
1069
deadbeef1dcb1642017-03-29 21:08:16 -07001070 void EnableVideoDecoderFactory() {
1071 caller_->EnableVideoDecoderFactory();
1072 callee_->EnableVideoDecoderFactory();
1073 }
1074
1075 // Messages may get lost on the unreliable DataChannel, so we send multiple
1076 // times to avoid test flakiness.
1077 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1078 const std::string& data,
1079 int retries) {
1080 for (int i = 0; i < retries; ++i) {
1081 dc->Send(DataBuffer(data));
1082 }
1083 }
1084
1085 rtc::Thread* network_thread() { return network_thread_.get(); }
1086
1087 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1088
1089 PeerConnectionWrapper* caller() { return caller_.get(); }
1090
1091 // Set the |caller_| to the |wrapper| passed in and return the
1092 // original |caller_|.
1093 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1094 PeerConnectionWrapper* wrapper) {
1095 PeerConnectionWrapper* old = caller_.release();
1096 caller_.reset(wrapper);
1097 return old;
1098 }
1099
1100 PeerConnectionWrapper* callee() { return callee_.get(); }
1101
1102 // Set the |callee_| to the |wrapper| passed in and return the
1103 // original |callee_|.
1104 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1105 PeerConnectionWrapper* wrapper) {
1106 PeerConnectionWrapper* old = callee_.release();
1107 callee_.reset(wrapper);
1108 return old;
1109 }
1110
Steve Antonede9ca52017-10-16 13:04:27 -07001111 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1112
deadbeef1dcb1642017-03-29 21:08:16 -07001113 // Expects the provided number of new frames to be received within |wait_ms|.
1114 // "New frames" meaning that it waits for the current frame counts to
1115 // *increase* by the provided values. For video, uses
1116 // RecievedVideoFramesForEachTrack for the case of multiple video tracks
1117 // being received.
1118 void ExpectNewFramesReceivedWithWait(
1119 int expected_caller_received_audio_frames,
1120 int expected_caller_received_video_frames,
1121 int expected_callee_received_audio_frames,
1122 int expected_callee_received_video_frames,
1123 int wait_ms) {
1124 // Add current frame counts to the provided values, in order to wait for
1125 // the frame count to increase.
1126 expected_caller_received_audio_frames += caller()->audio_frames_received();
1127 expected_caller_received_video_frames +=
1128 caller()->min_video_frames_received_per_track();
1129 expected_callee_received_audio_frames += callee()->audio_frames_received();
1130 expected_callee_received_video_frames +=
1131 callee()->min_video_frames_received_per_track();
1132
1133 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
1134 expected_caller_received_audio_frames &&
1135 caller()->min_video_frames_received_per_track() >=
1136 expected_caller_received_video_frames &&
1137 callee()->audio_frames_received() >=
1138 expected_callee_received_audio_frames &&
1139 callee()->min_video_frames_received_per_track() >=
1140 expected_callee_received_video_frames,
1141 wait_ms);
1142
1143 // After the combined wait, do an "expect" for each individual count, to
1144 // print out a more detailed message upon failure.
1145 EXPECT_GE(caller()->audio_frames_received(),
1146 expected_caller_received_audio_frames);
1147 EXPECT_GE(caller()->min_video_frames_received_per_track(),
1148 expected_caller_received_video_frames);
1149 EXPECT_GE(callee()->audio_frames_received(),
1150 expected_callee_received_audio_frames);
1151 EXPECT_GE(callee()->min_video_frames_received_per_track(),
1152 expected_callee_received_video_frames);
1153 }
1154
Tommi8e545ee2018-02-08 16:25:20 +00001155 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1156 bool remote_gcm_enabled,
1157 int expected_cipher_suite) {
1158 PeerConnectionFactory::Options caller_options;
1159 caller_options.crypto_options.enable_gcm_crypto_suites = local_gcm_enabled;
1160 PeerConnectionFactory::Options callee_options;
1161 callee_options.crypto_options.enable_gcm_crypto_suites = remote_gcm_enabled;
deadbeef1dcb1642017-03-29 21:08:16 -07001162 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1163 callee_options));
1164 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1165 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1166 caller()->pc()->RegisterUMAObserver(caller_observer);
1167 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001168 caller()->AddAudioVideoTracks();
1169 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001170 caller()->CreateAndSetAndSignalOffer();
1171 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1172 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001173 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001174 EXPECT_EQ(
1175 1, caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1176 expected_cipher_suite));
1177 caller()->pc()->RegisterUMAObserver(nullptr);
1178 }
1179
1180 private:
1181 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001182 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001183 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001184 // |network_thread_| and |worker_thread_| are used by both
1185 // |caller_| and |callee_| so they must be destroyed
1186 // later.
1187 std::unique_ptr<rtc::Thread> network_thread_;
1188 std::unique_ptr<rtc::Thread> worker_thread_;
1189 std::unique_ptr<PeerConnectionWrapper> caller_;
1190 std::unique_ptr<PeerConnectionWrapper> callee_;
1191};
1192
1193// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1194// includes testing that the callback is invoked if an observer is connected
1195// after the first packet has already been received.
1196TEST_F(PeerConnectionIntegrationTest,
1197 RtpReceiverObserverOnFirstPacketReceived) {
1198 ASSERT_TRUE(CreatePeerConnectionWrappers());
1199 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001200 caller()->AddAudioVideoTracks();
1201 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001202 // Start offer/answer exchange and wait for it to complete.
1203 caller()->CreateAndSetAndSignalOffer();
1204 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1205 // Should be one receiver each for audio/video.
1206 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1207 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1208 // Wait for all "first packet received" callbacks to be fired.
1209 EXPECT_TRUE_WAIT(
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 kMaxWaitForFramesMs);
1216 EXPECT_TRUE_WAIT(
1217 std::all_of(callee()->rtp_receiver_observers().begin(),
1218 callee()->rtp_receiver_observers().end(),
1219 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1220 return o->first_packet_received();
1221 }),
1222 kMaxWaitForFramesMs);
1223 // If new observers are set after the first packet was already received, the
1224 // callback should still be invoked.
1225 caller()->ResetRtpReceiverObservers();
1226 callee()->ResetRtpReceiverObservers();
1227 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1228 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1229 EXPECT_TRUE(
1230 std::all_of(caller()->rtp_receiver_observers().begin(),
1231 caller()->rtp_receiver_observers().end(),
1232 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1233 return o->first_packet_received();
1234 }));
1235 EXPECT_TRUE(
1236 std::all_of(callee()->rtp_receiver_observers().begin(),
1237 callee()->rtp_receiver_observers().end(),
1238 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1239 return o->first_packet_received();
1240 }));
1241}
1242
1243class DummyDtmfObserver : public DtmfSenderObserverInterface {
1244 public:
1245 DummyDtmfObserver() : completed_(false) {}
1246
1247 // Implements DtmfSenderObserverInterface.
1248 void OnToneChange(const std::string& tone) override {
1249 tones_.push_back(tone);
1250 if (tone.empty()) {
1251 completed_ = true;
1252 }
1253 }
1254
1255 const std::vector<std::string>& tones() const { return tones_; }
1256 bool completed() const { return completed_; }
1257
1258 private:
1259 bool completed_;
1260 std::vector<std::string> tones_;
1261};
1262
1263// Assumes |sender| already has an audio track added and the offer/answer
1264// exchange is done.
1265void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1266 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001267 // We should be able to get a DTMF sender from the local sender.
1268 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1269 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1270 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001271 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001272 dtmf_sender->RegisterObserver(&observer);
1273
1274 // Test the DtmfSender object just created.
1275 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1276 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1277
1278 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1279 std::vector<std::string> tones = {"1", "a", ""};
1280 EXPECT_EQ(tones, observer.tones());
1281 dtmf_sender->UnregisterObserver();
1282 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1283}
1284
1285// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1286// direction).
1287TEST_F(PeerConnectionIntegrationTest, DtmfSenderObserver) {
1288 ASSERT_TRUE(CreatePeerConnectionWrappers());
1289 ConnectFakeSignaling();
1290 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001291 caller()->AddAudioTrack();
1292 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001293 caller()->CreateAndSetAndSignalOffer();
1294 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001295 // DTLS must finish before the DTMF sender can be used reliably.
1296 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001297 TestDtmfFromSenderToReceiver(caller(), callee());
1298 TestDtmfFromSenderToReceiver(callee(), caller());
1299}
1300
1301// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1302// between two connections, using DTLS-SRTP.
1303TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
1304 ASSERT_TRUE(CreatePeerConnectionWrappers());
1305 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001306 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1307 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1308 caller()->pc()->RegisterUMAObserver(caller_observer);
1309
deadbeef1dcb1642017-03-29 21:08:16 -07001310 // Do normal offer/answer and wait for some frames to be received in each
1311 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001312 caller()->AddAudioVideoTracks();
1313 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001314 caller()->CreateAndSetAndSignalOffer();
1315 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1316 ExpectNewFramesReceivedWithWait(
1317 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1318 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1319 kMaxWaitForFramesMs);
Harald Alvestrand194939b2018-01-24 16:04:13 +01001320 EXPECT_LE(
1321 1, caller_observer->GetEnumCounter(webrtc::kEnumCounterKeyProtocol,
1322 webrtc::kEnumCounterKeyProtocolDtls));
1323 EXPECT_EQ(
1324 0, caller_observer->GetEnumCounter(webrtc::kEnumCounterKeyProtocol,
1325 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001326}
1327
1328// Uses SDES instead of DTLS for key agreement.
1329TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
1330 PeerConnectionInterface::RTCConfiguration sdes_config;
1331 sdes_config.enable_dtls_srtp.emplace(false);
1332 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1333 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001334 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1335 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1336 caller()->pc()->RegisterUMAObserver(caller_observer);
deadbeef1dcb1642017-03-29 21:08:16 -07001337
1338 // Do normal offer/answer and wait for some frames to be received in each
1339 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001340 caller()->AddAudioVideoTracks();
1341 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001342 caller()->CreateAndSetAndSignalOffer();
1343 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1344 ExpectNewFramesReceivedWithWait(
1345 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1346 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1347 kMaxWaitForFramesMs);
Harald Alvestrand194939b2018-01-24 16:04:13 +01001348 EXPECT_LE(
1349 1, caller_observer->GetEnumCounter(webrtc::kEnumCounterKeyProtocol,
1350 webrtc::kEnumCounterKeyProtocolSdes));
1351 EXPECT_EQ(
1352 0, caller_observer->GetEnumCounter(webrtc::kEnumCounterKeyProtocol,
1353 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001354}
1355
Steve Anton8c0f7a72017-10-03 10:03:10 -07001356// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1357// certificate once the DTLS handshake has finished.
1358TEST_F(PeerConnectionIntegrationTest,
1359 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1360 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1361 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1362 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1363 return pc->GetRemoteAudioSSLCertificate();
1364 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001365 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1366 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1367 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1368 return pc->GetRemoteAudioSSLCertChain();
1369 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001370
1371 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1372 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1373
1374 // Configure each side with a known certificate so they can be compared later.
1375 PeerConnectionInterface::RTCConfiguration caller_config;
1376 caller_config.enable_dtls_srtp.emplace(true);
1377 caller_config.certificates.push_back(caller_cert);
1378 PeerConnectionInterface::RTCConfiguration callee_config;
1379 callee_config.enable_dtls_srtp.emplace(true);
1380 callee_config.certificates.push_back(callee_cert);
1381 ASSERT_TRUE(
1382 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1383 ConnectFakeSignaling();
1384
1385 // When first initialized, there should not be a remote SSL certificate (and
1386 // calling this method should not crash).
1387 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1388 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001389 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1390 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001391
Steve Anton15324772018-01-16 10:26:49 -08001392 caller()->AddAudioTrack();
1393 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001394 caller()->CreateAndSetAndSignalOffer();
1395 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1396 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1397
1398 // Once DTLS has been connected, each side should return the other's SSL
1399 // certificate when calling GetRemoteAudioSSLCertificate.
1400
1401 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1402 ASSERT_TRUE(caller_remote_cert);
1403 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1404 caller_remote_cert->ToPEMString());
1405
1406 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1407 ASSERT_TRUE(callee_remote_cert);
1408 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1409 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001410
1411 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1412 ASSERT_TRUE(caller_remote_cert_chain);
1413 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1414 auto remote_cert = &caller_remote_cert_chain->Get(0);
1415 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1416 remote_cert->ToPEMString());
1417
1418 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1419 ASSERT_TRUE(callee_remote_cert_chain);
1420 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1421 remote_cert = &callee_remote_cert_chain->Get(0);
1422 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1423 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001424}
1425
deadbeef1dcb1642017-03-29 21:08:16 -07001426// This test sets up a call between two parties (using DTLS) and tests that we
1427// can get a video aspect ratio of 16:9.
1428TEST_F(PeerConnectionIntegrationTest, SendAndReceive16To9AspectRatio) {
1429 ASSERT_TRUE(CreatePeerConnectionWrappers());
1430 ConnectFakeSignaling();
1431
1432 // Add video tracks with 16:9 constraint.
1433 FakeConstraints constraints;
1434 double requested_ratio = 16.0 / 9;
1435 constraints.SetMandatoryMinAspectRatio(requested_ratio);
Steve Anton15324772018-01-16 10:26:49 -08001436 caller()->AddTrack(
1437 caller()->CreateLocalVideoTrackWithConstraints(constraints));
1438 callee()->AddTrack(
1439 callee()->CreateLocalVideoTrackWithConstraints(constraints));
deadbeef1dcb1642017-03-29 21:08:16 -07001440
1441 // Do normal offer/answer and wait for at least one frame to be received in
1442 // each direction.
1443 caller()->CreateAndSetAndSignalOffer();
1444 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1445 callee()->min_video_frames_received_per_track() > 0,
1446 kMaxWaitForFramesMs);
1447
1448 // Check rendered aspect ratio.
1449 EXPECT_EQ(requested_ratio, caller()->local_rendered_aspect_ratio());
1450 EXPECT_EQ(requested_ratio, caller()->rendered_aspect_ratio());
1451 EXPECT_EQ(requested_ratio, callee()->local_rendered_aspect_ratio());
1452 EXPECT_EQ(requested_ratio, callee()->rendered_aspect_ratio());
1453}
1454
1455// This test sets up a call between two parties with a source resolution of
1456// 1280x720 and verifies that a 16:9 aspect ratio is received.
1457TEST_F(PeerConnectionIntegrationTest,
1458 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1459 ASSERT_TRUE(CreatePeerConnectionWrappers());
1460 ConnectFakeSignaling();
1461
1462 // Similar to above test, but uses MandatoryMin[Width/Height] constraint
1463 // instead of aspect ratio constraint.
1464 FakeConstraints constraints;
1465 constraints.SetMandatoryMinWidth(1280);
1466 constraints.SetMandatoryMinHeight(720);
Steve Anton15324772018-01-16 10:26:49 -08001467 caller()->AddTrack(
1468 caller()->CreateLocalVideoTrackWithConstraints(constraints));
1469 callee()->AddTrack(
1470 callee()->CreateLocalVideoTrackWithConstraints(constraints));
deadbeef1dcb1642017-03-29 21:08:16 -07001471
1472 // Do normal offer/answer and wait for at least one frame to be received in
1473 // each direction.
1474 caller()->CreateAndSetAndSignalOffer();
1475 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1476 callee()->min_video_frames_received_per_track() > 0,
1477 kMaxWaitForFramesMs);
1478
1479 // Check rendered aspect ratio.
1480 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1481 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1482 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1483 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1484}
1485
1486// This test sets up an one-way call, with media only from caller to
1487// callee.
1488TEST_F(PeerConnectionIntegrationTest, OneWayMediaCall) {
1489 ASSERT_TRUE(CreatePeerConnectionWrappers());
1490 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001491 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001492 caller()->CreateAndSetAndSignalOffer();
1493 int caller_received_frames = 0;
1494 ExpectNewFramesReceivedWithWait(
1495 caller_received_frames, caller_received_frames,
1496 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1497 kMaxWaitForFramesMs);
1498}
1499
1500// This test sets up a audio call initially, with the callee rejecting video
1501// initially. Then later the callee decides to upgrade to audio/video, and
1502// initiates a new offer/answer exchange.
1503TEST_F(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
1504 ASSERT_TRUE(CreatePeerConnectionWrappers());
1505 ConnectFakeSignaling();
1506 // Initially, offer an audio/video stream from the caller, but refuse to
1507 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001508 caller()->AddAudioVideoTracks();
1509 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001510 PeerConnectionInterface::RTCOfferAnswerOptions options;
1511 options.offer_to_receive_video = 0;
1512 callee()->SetOfferAnswerOptions(options);
1513 // Do offer/answer and make sure audio is still received end-to-end.
1514 caller()->CreateAndSetAndSignalOffer();
1515 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1516 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1517 kDefaultExpectedAudioFrameCount, 0,
1518 kMaxWaitForFramesMs);
1519 // Sanity check that the callee's description has a rejected video section.
1520 ASSERT_NE(nullptr, callee()->pc()->local_description());
1521 const ContentInfo* callee_video_content =
1522 GetFirstVideoContent(callee()->pc()->local_description()->description());
1523 ASSERT_NE(nullptr, callee_video_content);
1524 EXPECT_TRUE(callee_video_content->rejected);
1525 // Now negotiate with video and ensure negotiation succeeds, with video
1526 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001527 callee()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001528 options.offer_to_receive_video = 1;
1529 callee()->SetOfferAnswerOptions(options);
1530 callee()->CreateAndSetAndSignalOffer();
1531 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1532 // Expect additional audio frames to be received after the upgrade.
1533 ExpectNewFramesReceivedWithWait(
1534 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1535 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1536 kMaxWaitForFramesMs);
1537}
1538
deadbeef4389b4d2017-09-07 09:07:36 -07001539// Simpler than the above test; just add an audio track to an established
1540// video-only connection.
1541TEST_F(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
1542 ASSERT_TRUE(CreatePeerConnectionWrappers());
1543 ConnectFakeSignaling();
1544 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08001545 caller()->AddVideoTrack();
1546 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001547 caller()->CreateAndSetAndSignalOffer();
1548 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1549 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08001550 caller()->AddAudioTrack();
1551 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001552 caller()->CreateAndSetAndSignalOffer();
1553 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1554 // Ensure both audio and video frames are received end-to-end.
1555 ExpectNewFramesReceivedWithWait(
1556 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1557 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1558 kMaxWaitForFramesMs);
1559}
1560
deadbeef1dcb1642017-03-29 21:08:16 -07001561// This test sets up a call that's transferred to a new caller with a different
1562// DTLS fingerprint.
1563TEST_F(PeerConnectionIntegrationTest, CallTransferredForCallee) {
1564 ASSERT_TRUE(CreatePeerConnectionWrappers());
1565 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001566 caller()->AddAudioVideoTracks();
1567 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001568 caller()->CreateAndSetAndSignalOffer();
1569 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1570
1571 // Keep the original peer around which will still send packets to the
1572 // receiving client. These SRTP packets will be dropped.
1573 std::unique_ptr<PeerConnectionWrapper> original_peer(
1574 SetCallerPcWrapperAndReturnCurrent(
1575 CreatePeerConnectionWrapperWithAlternateKey()));
1576 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1577 // directly above.
1578 original_peer->pc()->Close();
1579
1580 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001581 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001582 caller()->CreateAndSetAndSignalOffer();
1583 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1584 // Wait for some additional frames to be transmitted end-to-end.
1585 ExpectNewFramesReceivedWithWait(
1586 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1587 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1588 kMaxWaitForFramesMs);
1589}
1590
1591// This test sets up a call that's transferred to a new callee with a different
1592// DTLS fingerprint.
1593TEST_F(PeerConnectionIntegrationTest, CallTransferredForCaller) {
1594 ASSERT_TRUE(CreatePeerConnectionWrappers());
1595 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001596 caller()->AddAudioVideoTracks();
1597 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001598 caller()->CreateAndSetAndSignalOffer();
1599 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1600
1601 // Keep the original peer around which will still send packets to the
1602 // receiving client. These SRTP packets will be dropped.
1603 std::unique_ptr<PeerConnectionWrapper> original_peer(
1604 SetCalleePcWrapperAndReturnCurrent(
1605 CreatePeerConnectionWrapperWithAlternateKey()));
1606 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1607 // directly above.
1608 original_peer->pc()->Close();
1609
1610 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001611 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001612 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1613 caller()->CreateAndSetAndSignalOffer();
1614 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1615 // Wait for some additional frames to be transmitted end-to-end.
1616 ExpectNewFramesReceivedWithWait(
1617 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1618 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1619 kMaxWaitForFramesMs);
1620}
1621
1622// This test sets up a non-bundled call and negotiates bundling at the same
1623// time as starting an ICE restart. When bundling is in effect in the restart,
1624// the DTLS-SRTP context should be successfully reset.
1625TEST_F(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
1626 ASSERT_TRUE(CreatePeerConnectionWrappers());
1627 ConnectFakeSignaling();
1628
Steve Anton15324772018-01-16 10:26:49 -08001629 caller()->AddAudioVideoTracks();
1630 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001631 // Remove the bundle group from the SDP received by the callee.
1632 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1633 desc->RemoveGroupByName("BUNDLE");
1634 });
1635 caller()->CreateAndSetAndSignalOffer();
1636 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1637 ExpectNewFramesReceivedWithWait(
1638 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1639 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1640 kMaxWaitForFramesMs);
1641
1642 // Now stop removing the BUNDLE group, and trigger an ICE restart.
1643 callee()->SetReceivedSdpMunger(nullptr);
1644 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1645 caller()->CreateAndSetAndSignalOffer();
1646 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1647
1648 // Expect additional frames to be received after the ICE restart.
1649 ExpectNewFramesReceivedWithWait(
1650 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1651 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1652 kMaxWaitForFramesMs);
1653}
1654
1655// Test CVO (Coordination of Video Orientation). If a video source is rotated
1656// and both peers support the CVO RTP header extension, the actual video frames
1657// don't need to be encoded in different resolutions, since the rotation is
1658// communicated through the RTP header extension.
1659TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
1660 ASSERT_TRUE(CreatePeerConnectionWrappers());
1661 ConnectFakeSignaling();
1662 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08001663 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001664 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08001665 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001666 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1667
1668 // Wait for video frames to be received by both sides.
1669 caller()->CreateAndSetAndSignalOffer();
1670 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1671 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1672 callee()->min_video_frames_received_per_track() > 0,
1673 kMaxWaitForFramesMs);
1674
1675 // Ensure that the aspect ratio is unmodified.
1676 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1677 // not just assumed.
1678 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
1679 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
1680 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
1681 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
1682 // Ensure that the CVO bits were surfaced to the renderer.
1683 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
1684 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
1685}
1686
1687// Test that when the CVO extension isn't supported, video is rotated the
1688// old-fashioned way, by encoding rotated frames.
1689TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
1690 ASSERT_TRUE(CreatePeerConnectionWrappers());
1691 ConnectFakeSignaling();
1692 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08001693 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001694 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08001695 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001696 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1697
1698 // Remove the CVO extension from the offered SDP.
1699 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1700 cricket::VideoContentDescription* video =
1701 GetFirstVideoContentDescription(desc);
1702 video->ClearRtpHeaderExtensions();
1703 });
1704 // Wait for video frames to be received by both sides.
1705 caller()->CreateAndSetAndSignalOffer();
1706 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1707 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1708 callee()->min_video_frames_received_per_track() > 0,
1709 kMaxWaitForFramesMs);
1710
1711 // Expect that the aspect ratio is inversed to account for the 90/270 degree
1712 // rotation.
1713 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1714 // not just assumed.
1715 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
1716 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
1717 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
1718 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
1719 // Expect that each endpoint is unaware of the rotation of the other endpoint.
1720 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
1721 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
1722}
1723
1724// TODO(deadbeef): The tests below rely on RTCOfferAnswerOptions to reject an
1725// m= section. When we implement Unified Plan SDP, the right way to do this
1726// would be by stopping an RtpTransceiver.
1727
1728// Test that if the answerer rejects the audio m= section, no audio is sent or
1729// received, but video still can be.
1730TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
1731 ASSERT_TRUE(CreatePeerConnectionWrappers());
1732 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001733 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001734 // Only add video track for callee, and set offer_to_receive_audio to 0, so
1735 // it will reject the audio m= section completely.
1736 PeerConnectionInterface::RTCOfferAnswerOptions options;
1737 options.offer_to_receive_audio = 0;
1738 callee()->SetOfferAnswerOptions(options);
Steve Anton15324772018-01-16 10:26:49 -08001739 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07001740 // Do offer/answer and wait for successful end-to-end video frames.
1741 caller()->CreateAndSetAndSignalOffer();
1742 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1743 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount, 0,
1744 kDefaultExpectedVideoFrameCount,
1745 kMaxWaitForFramesMs);
1746 // Shouldn't have received audio frames at any point.
1747 EXPECT_EQ(0, caller()->audio_frames_received());
1748 EXPECT_EQ(0, callee()->audio_frames_received());
1749 // Sanity check that the callee's description has a rejected audio section.
1750 ASSERT_NE(nullptr, callee()->pc()->local_description());
1751 const ContentInfo* callee_audio_content =
1752 GetFirstAudioContent(callee()->pc()->local_description()->description());
1753 ASSERT_NE(nullptr, callee_audio_content);
1754 EXPECT_TRUE(callee_audio_content->rejected);
1755}
1756
1757// Test that if the answerer rejects the video m= section, no video is sent or
1758// received, but audio still can be.
1759TEST_F(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
1760 ASSERT_TRUE(CreatePeerConnectionWrappers());
1761 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001762 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001763 // Only add audio track for callee, and set offer_to_receive_video to 0, so
1764 // it will reject the video m= section completely.
1765 PeerConnectionInterface::RTCOfferAnswerOptions options;
1766 options.offer_to_receive_video = 0;
1767 callee()->SetOfferAnswerOptions(options);
Steve Anton15324772018-01-16 10:26:49 -08001768 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07001769 // Do offer/answer and wait for successful end-to-end audio frames.
1770 caller()->CreateAndSetAndSignalOffer();
1771 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1772 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1773 kDefaultExpectedAudioFrameCount, 0,
1774 kMaxWaitForFramesMs);
1775 // Shouldn't have received video frames at any point.
1776 EXPECT_EQ(0, caller()->total_video_frames_received());
1777 EXPECT_EQ(0, callee()->total_video_frames_received());
1778 // Sanity check that the callee's description has a rejected video section.
1779 ASSERT_NE(nullptr, callee()->pc()->local_description());
1780 const ContentInfo* callee_video_content =
1781 GetFirstVideoContent(callee()->pc()->local_description()->description());
1782 ASSERT_NE(nullptr, callee_video_content);
1783 EXPECT_TRUE(callee_video_content->rejected);
1784}
1785
1786// Test that if the answerer rejects both audio and video m= sections, nothing
1787// bad happens.
1788// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
1789// test anything but the fact that negotiation succeeds, which doesn't mean
1790// much.
1791TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
1792 ASSERT_TRUE(CreatePeerConnectionWrappers());
1793 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001794 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001795 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
1796 // will reject both audio and video m= sections.
1797 PeerConnectionInterface::RTCOfferAnswerOptions options;
1798 options.offer_to_receive_audio = 0;
1799 options.offer_to_receive_video = 0;
1800 callee()->SetOfferAnswerOptions(options);
1801 // Do offer/answer and wait for stable signaling state.
1802 caller()->CreateAndSetAndSignalOffer();
1803 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1804 // Sanity check that the callee's description has rejected m= sections.
1805 ASSERT_NE(nullptr, callee()->pc()->local_description());
1806 const ContentInfo* callee_audio_content =
1807 GetFirstAudioContent(callee()->pc()->local_description()->description());
1808 ASSERT_NE(nullptr, callee_audio_content);
1809 EXPECT_TRUE(callee_audio_content->rejected);
1810 const ContentInfo* callee_video_content =
1811 GetFirstVideoContent(callee()->pc()->local_description()->description());
1812 ASSERT_NE(nullptr, callee_video_content);
1813 EXPECT_TRUE(callee_video_content->rejected);
1814}
1815
1816// This test sets up an audio and video call between two parties. After the
1817// call runs for a while, the caller sends an updated offer with video being
1818// rejected. Once the re-negotiation is done, the video flow should stop and
1819// the audio flow should continue.
1820TEST_F(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
1821 ASSERT_TRUE(CreatePeerConnectionWrappers());
1822 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001823 caller()->AddAudioVideoTracks();
1824 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001825 caller()->CreateAndSetAndSignalOffer();
1826 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1827 ExpectNewFramesReceivedWithWait(
1828 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1829 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1830 kMaxWaitForFramesMs);
1831
1832 // Renegotiate, rejecting the video m= section.
1833 // TODO(deadbeef): When an RtpTransceiver API is available, use that to
1834 // reject the video m= section.
1835 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
1836 for (cricket::ContentInfo& content : description->contents()) {
1837 if (cricket::IsVideoContent(&content)) {
1838 content.rejected = true;
1839 }
1840 }
1841 });
1842 caller()->CreateAndSetAndSignalOffer();
1843 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
1844
1845 // Sanity check that the caller's description has a rejected video section.
1846 ASSERT_NE(nullptr, caller()->pc()->local_description());
1847 const ContentInfo* caller_video_content =
1848 GetFirstVideoContent(caller()->pc()->local_description()->description());
1849 ASSERT_NE(nullptr, caller_video_content);
1850 EXPECT_TRUE(caller_video_content->rejected);
1851
1852 int caller_video_received = caller()->total_video_frames_received();
1853 int callee_video_received = callee()->total_video_frames_received();
1854
1855 // Wait for some additional audio frames to be received.
1856 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1857 kDefaultExpectedAudioFrameCount, 0,
1858 kMaxWaitForFramesMs);
1859
1860 // During this time, we shouldn't have received any additional video frames
1861 // for the rejected video tracks.
1862 EXPECT_EQ(caller_video_received, caller()->total_video_frames_received());
1863 EXPECT_EQ(callee_video_received, callee()->total_video_frames_received());
1864}
1865
1866// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
1867// is needed to support legacy endpoints.
1868// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
1869// add a test for an end-to-end test without MID signaling either (basically,
1870// the minimum acceptable SDP).
1871TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
1872 ASSERT_TRUE(CreatePeerConnectionWrappers());
1873 ConnectFakeSignaling();
1874 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08001875 caller()->AddAudioVideoTracks();
1876 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07001877 // Remove SSRCs and MSIDs from the received offer SDP.
1878 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07001879 caller()->CreateAndSetAndSignalOffer();
1880 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1881 ExpectNewFramesReceivedWithWait(
1882 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1883 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1884 kMaxWaitForFramesMs);
1885}
1886
1887// Test that if two video tracks are sent (from caller to callee, in this test),
1888// they're transmitted correctly end-to-end.
1889TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
1890 ASSERT_TRUE(CreatePeerConnectionWrappers());
1891 ConnectFakeSignaling();
1892 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08001893 caller()->AddAudioVideoTracks();
1894 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001895 caller()->CreateAndSetAndSignalOffer();
1896 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08001897 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001898 int expected_callee_received_frames = kDefaultExpectedVideoFrameCount;
1899 ExpectNewFramesReceivedWithWait(0, 0, 0, expected_callee_received_frames,
1900 kMaxWaitForFramesMs);
1901}
1902
1903static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
1904 bool first = true;
1905 for (cricket::ContentInfo& content : desc->contents()) {
1906 if (first) {
1907 first = false;
1908 continue;
1909 }
1910 content.bundle_only = true;
1911 }
1912 first = true;
1913 for (cricket::TransportInfo& transport : desc->transport_infos()) {
1914 if (first) {
1915 first = false;
1916 continue;
1917 }
1918 transport.description.ice_ufrag.clear();
1919 transport.description.ice_pwd.clear();
1920 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
1921 transport.description.identity_fingerprint.reset(nullptr);
1922 }
1923}
1924
1925// Test that if applying a true "max bundle" offer, which uses ports of 0,
1926// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
1927// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
1928// successfully and media flows.
1929// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
1930// TODO(deadbeef): Won't need this test once we start generating actual
1931// standards-compliant SDP.
1932TEST_F(PeerConnectionIntegrationTest,
1933 EndToEndCallWithSpecCompliantMaxBundleOffer) {
1934 ASSERT_TRUE(CreatePeerConnectionWrappers());
1935 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001936 caller()->AddAudioVideoTracks();
1937 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001938 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
1939 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
1940 // but the first m= section.
1941 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
1942 caller()->CreateAndSetAndSignalOffer();
1943 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1944 ExpectNewFramesReceivedWithWait(
1945 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1946 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1947 kMaxWaitForFramesMs);
1948}
1949
1950// Test that we can receive the audio output level from a remote audio track.
1951// TODO(deadbeef): Use a fake audio source and verify that the output level is
1952// exactly what the source on the other side was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001953TEST_F(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001954 ASSERT_TRUE(CreatePeerConnectionWrappers());
1955 ConnectFakeSignaling();
1956 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08001957 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001958 caller()->CreateAndSetAndSignalOffer();
1959 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1960
1961 // Get the audio output level stats. Note that the level is not available
1962 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07001963 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001964 kMaxWaitForFramesMs);
1965}
1966
1967// Test that an audio input level is reported.
1968// TODO(deadbeef): Use a fake audio source and verify that the input level is
1969// exactly what the source was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001970TEST_F(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001971 ASSERT_TRUE(CreatePeerConnectionWrappers());
1972 ConnectFakeSignaling();
1973 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08001974 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001975 caller()->CreateAndSetAndSignalOffer();
1976 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1977
1978 // Get the audio input level stats. The level should be available very
1979 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07001980 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001981 kMaxWaitForStatsMs);
1982}
1983
1984// Test that we can get incoming byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001985TEST_F(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001986 ASSERT_TRUE(CreatePeerConnectionWrappers());
1987 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001988 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001989 // Do offer/answer, wait for the callee to receive some frames.
1990 caller()->CreateAndSetAndSignalOffer();
1991 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1992 int expected_caller_received_frames = 0;
1993 ExpectNewFramesReceivedWithWait(
1994 expected_caller_received_frames, expected_caller_received_frames,
1995 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1996 kMaxWaitForFramesMs);
1997
1998 // Get a handle to the remote tracks created, so they can be used as GetStats
1999 // filters.
Steve Anton15324772018-01-16 10:26:49 -08002000 for (auto receiver : callee()->pc()->GetReceivers()) {
2001 // We received frames, so we definitely should have nonzero "received bytes"
2002 // stats at this point.
2003 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2004 0);
2005 }
deadbeef1dcb1642017-03-29 21:08:16 -07002006}
2007
2008// Test that we can get outgoing byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07002009TEST_F(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002010 ASSERT_TRUE(CreatePeerConnectionWrappers());
2011 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002012 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002013 auto audio_track = caller()->CreateLocalAudioTrack();
2014 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002015 caller()->AddTrack(audio_track);
2016 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002017 // Do offer/answer, wait for the callee to receive some frames.
2018 caller()->CreateAndSetAndSignalOffer();
2019 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2020 int expected_caller_received_frames = 0;
2021 ExpectNewFramesReceivedWithWait(
2022 expected_caller_received_frames, expected_caller_received_frames,
2023 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2024 kMaxWaitForFramesMs);
2025
2026 // The callee received frames, so we definitely should have nonzero "sent
2027 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002028 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2029 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2030}
2031
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002032// Test that we can get capture start ntp time.
2033TEST_F(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
2034 ASSERT_TRUE(CreatePeerConnectionWrappers());
2035 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002036 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002037
Steve Anton15324772018-01-16 10:26:49 -08002038 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002039
2040 // Do offer/answer, wait for the callee to receive some frames.
2041 caller()->CreateAndSetAndSignalOffer();
2042 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2043
2044 // Get the remote audio track created on the receiver, so they can be used as
2045 // GetStats filters.
2046 StreamCollectionInterface* remote_streams = callee()->remote_streams();
2047 ASSERT_EQ(1u, remote_streams->count());
2048 ASSERT_EQ(1u, remote_streams->at(0)->GetAudioTracks().size());
2049 MediaStreamTrackInterface* remote_audio_track =
2050 remote_streams->at(0)->GetAudioTracks()[0];
2051
2052 // Get the audio output level stats. Note that the level is not available
2053 // until an RTCP packet has been received.
2054 EXPECT_TRUE_WAIT(callee()->OldGetStatsForTrack(remote_audio_track)->
2055 CaptureStartNtpTime() > 0, 2 * kMaxWaitForFramesMs);
2056}
2057
deadbeefd8ad7882017-04-18 16:01:17 -07002058// Test that we can get stats (using the new stats implemnetation) for
2059// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2060// SDP.
2061TEST_F(PeerConnectionIntegrationTest,
2062 GetStatsForUnsignaledStreamWithNewStatsApi) {
2063 ASSERT_TRUE(CreatePeerConnectionWrappers());
2064 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002065 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002066 // Remove SSRCs and MSIDs from the received offer SDP.
2067 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2068 caller()->CreateAndSetAndSignalOffer();
2069 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2070 // Wait for one audio frame to be received by the callee.
2071 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
2072
2073 // We received a frame, so we should have nonzero "bytes received" stats for
2074 // the unsignaled stream, if stats are working for it.
2075 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2076 callee()->NewGetStats();
2077 ASSERT_NE(nullptr, report);
2078 auto inbound_stream_stats =
2079 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2080 ASSERT_EQ(1U, inbound_stream_stats.size());
2081 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2082 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002083 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2084}
2085
2086// Test that we can successfully get the media related stats (audio level
2087// etc.) for the unsignaled stream.
2088TEST_F(PeerConnectionIntegrationTest,
2089 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2090 ASSERT_TRUE(CreatePeerConnectionWrappers());
2091 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002092 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002093 // Remove SSRCs and MSIDs from the received offer SDP.
2094 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2095 caller()->CreateAndSetAndSignalOffer();
2096 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2097 // Wait for one audio frame to be received by the callee.
2098 ExpectNewFramesReceivedWithWait(0, 0, 1, 1, kMaxWaitForFramesMs);
2099
2100 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2101 callee()->NewGetStats();
2102 ASSERT_NE(nullptr, report);
2103
2104 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2105 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2106 ASSERT_GE(audio_index, 0);
2107 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002108}
2109
deadbeef4e2deab2017-09-20 13:56:21 -07002110// Helper for test below.
2111void ModifySsrcs(cricket::SessionDescription* desc) {
2112 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002113 for (cricket::StreamParams& stream :
2114 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002115 for (uint32_t& ssrc : stream.ssrcs) {
2116 ssrc = rtc::CreateRandomId();
2117 }
2118 }
2119 }
2120}
2121
2122// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2123// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2124// This should result in two "RTCInboundRTPStreamStats", but only one
2125// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2126// being reset to 0 once the SSRC change occurs.
2127//
2128// Regression test for this bug:
2129// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2130//
2131// The bug causes the track stats to only represent one of the two streams:
2132// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2133// that the track stat counters would reset to 0 when the new stream is
2134// received, and a 50% chance that they'll stop updating (while
2135// "concealed_samples" continues increasing, due to silence being generated for
2136// the inactive stream).
2137TEST_F(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002138 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002139 ASSERT_TRUE(CreatePeerConnectionWrappers());
2140 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002141 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002142 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2143 // that doesn't signal SSRCs (from the callee's perspective).
2144 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2145 caller()->CreateAndSetAndSignalOffer();
2146 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2147 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
2148 ExpectNewFramesReceivedWithWait(0, 0, 25, 0, kMaxWaitForFramesMs);
2149
2150 // Some audio frames were received, so we should have nonzero "samples
2151 // received" for the track.
2152 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2153 callee()->NewGetStats();
2154 ASSERT_NE(nullptr, report);
2155 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2156 ASSERT_EQ(1U, track_stats.size());
2157 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2158 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2159 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2160
2161 // Create a new offer and munge it to cause the caller to use a new SSRC.
2162 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2163 caller()->CreateAndSetAndSignalOffer();
2164 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2165 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2166 // SSRC.
2167 ExpectNewFramesReceivedWithWait(0, 0, 25, 0, kMaxWaitForFramesMs);
2168
2169 report = callee()->NewGetStats();
2170 ASSERT_NE(nullptr, report);
2171 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2172 ASSERT_EQ(1U, track_stats.size());
2173 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2174 // The "total samples received" stat should only be greater than it was
2175 // before.
2176 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2177 // Right now, the new SSRC will cause the counters to reset to 0.
2178 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2179
2180 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002181 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002182 // good sign that we're seeing stats from the old stream that's no longer
2183 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002184 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002185 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2186 EXPECT_LT(*track_stats[0]->concealed_samples,
2187 *track_stats[0]->total_samples_received *
2188 kAcceptableConcealedSamplesPercentage);
2189
2190 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2191 // sanity check that the SSRC really changed.
2192 // TODO(deadbeef): This isn't working right now, because we're not returning
2193 // *any* stats for the inactive stream. Uncomment when the bug is completely
2194 // fixed.
2195 // auto inbound_stream_stats =
2196 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2197 // ASSERT_EQ(2U, inbound_stream_stats.size());
2198}
2199
deadbeef1dcb1642017-03-29 21:08:16 -07002200// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
2201TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
2202 PeerConnectionFactory::Options dtls_10_options;
2203 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2204 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2205 dtls_10_options));
2206 ConnectFakeSignaling();
2207 // Do normal offer/answer and wait for some frames to be received in each
2208 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002209 caller()->AddAudioVideoTracks();
2210 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002211 caller()->CreateAndSetAndSignalOffer();
2212 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2213 ExpectNewFramesReceivedWithWait(
2214 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2215 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2216 kMaxWaitForFramesMs);
2217}
2218
2219// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
2220TEST_F(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
2221 PeerConnectionFactory::Options dtls_10_options;
2222 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2223 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2224 dtls_10_options));
2225 ConnectFakeSignaling();
2226 // Register UMA observer before signaling begins.
2227 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
2228 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2229 caller()->pc()->RegisterUMAObserver(caller_observer);
Steve Anton15324772018-01-16 10:26:49 -08002230 caller()->AddAudioVideoTracks();
2231 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002232 caller()->CreateAndSetAndSignalOffer();
2233 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2234 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002235 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002236 kDefaultTimeout);
2237 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002238 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002239 EXPECT_EQ(1,
2240 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2241 kDefaultSrtpCryptoSuite));
2242}
2243
2244// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
2245TEST_F(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
2246 PeerConnectionFactory::Options dtls_12_options;
2247 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2248 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2249 dtls_12_options));
2250 ConnectFakeSignaling();
2251 // Register UMA observer before signaling begins.
2252 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
2253 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2254 caller()->pc()->RegisterUMAObserver(caller_observer);
Steve Anton15324772018-01-16 10:26:49 -08002255 caller()->AddAudioVideoTracks();
2256 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002257 caller()->CreateAndSetAndSignalOffer();
2258 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2259 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002260 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002261 kDefaultTimeout);
2262 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002263 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002264 EXPECT_EQ(1,
2265 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2266 kDefaultSrtpCryptoSuite));
2267}
2268
2269// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2270// callee only supports 1.0.
2271TEST_F(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
2272 PeerConnectionFactory::Options caller_options;
2273 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2274 PeerConnectionFactory::Options callee_options;
2275 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2276 ASSERT_TRUE(
2277 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2278 ConnectFakeSignaling();
2279 // Do normal offer/answer and wait for some frames to be received in each
2280 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002281 caller()->AddAudioVideoTracks();
2282 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002283 caller()->CreateAndSetAndSignalOffer();
2284 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2285 ExpectNewFramesReceivedWithWait(
2286 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2287 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2288 kMaxWaitForFramesMs);
2289}
2290
2291// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2292// callee supports 1.2.
2293TEST_F(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
2294 PeerConnectionFactory::Options caller_options;
2295 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2296 PeerConnectionFactory::Options callee_options;
2297 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2298 ASSERT_TRUE(
2299 CreatePeerConnectionWrappersWithOptions(caller_options, callee_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();
deadbeef1dcb1642017-03-29 21:08:16 -07002305 caller()->CreateAndSetAndSignalOffer();
2306 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2307 ExpectNewFramesReceivedWithWait(
2308 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2309 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2310 kMaxWaitForFramesMs);
2311}
2312
2313// Test that a non-GCM cipher is used if both sides only support non-GCM.
2314TEST_F(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
2315 bool local_gcm_enabled = false;
2316 bool remote_gcm_enabled = false;
2317 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2318 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2319 expected_cipher_suite);
2320}
2321
2322// Test that a GCM cipher is used if both ends support it.
2323TEST_F(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
2324 bool local_gcm_enabled = true;
2325 bool remote_gcm_enabled = true;
2326 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2327 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2328 expected_cipher_suite);
2329}
2330
2331// Test that GCM isn't used if only the offerer supports it.
2332TEST_F(PeerConnectionIntegrationTest,
2333 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2334 bool local_gcm_enabled = true;
2335 bool remote_gcm_enabled = false;
2336 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2337 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2338 expected_cipher_suite);
2339}
2340
2341// Test that GCM isn't used if only the answerer supports it.
2342TEST_F(PeerConnectionIntegrationTest,
2343 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2344 bool local_gcm_enabled = false;
2345 bool remote_gcm_enabled = true;
2346 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2347 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2348 expected_cipher_suite);
2349}
2350
deadbeef7914b8c2017-04-21 03:23:33 -07002351// Verify that media can be transmitted end-to-end when GCM crypto suites are
2352// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
2353// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
2354// works with it.
2355TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
2356 PeerConnectionFactory::Options gcm_options;
2357 gcm_options.crypto_options.enable_gcm_crypto_suites = true;
2358 ASSERT_TRUE(
2359 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
2360 ConnectFakeSignaling();
2361 // Do normal offer/answer and wait for some frames to be received in each
2362 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002363 caller()->AddAudioVideoTracks();
2364 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002365 caller()->CreateAndSetAndSignalOffer();
2366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2367 ExpectNewFramesReceivedWithWait(
2368 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2369 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2370 kMaxWaitForFramesMs);
2371}
2372
deadbeef1dcb1642017-03-29 21:08:16 -07002373// This test sets up a call between two parties with audio, video and an RTP
2374// data channel.
2375TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
2376 FakeConstraints setup_constraints;
2377 setup_constraints.SetAllowRtpDataChannels();
2378 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2379 &setup_constraints));
2380 ConnectFakeSignaling();
2381 // Expect that data channel created on caller side will show up for callee as
2382 // well.
2383 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002384 caller()->AddAudioVideoTracks();
2385 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002386 caller()->CreateAndSetAndSignalOffer();
2387 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2388 // Ensure the existence of the RTP data channel didn't impede audio/video.
2389 ExpectNewFramesReceivedWithWait(
2390 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2391 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2392 kMaxWaitForFramesMs);
2393 ASSERT_NE(nullptr, caller()->data_channel());
2394 ASSERT_NE(nullptr, callee()->data_channel());
2395 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2396 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2397
2398 // Ensure data can be sent in both directions.
2399 std::string data = "hello world";
2400 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2401 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2402 kDefaultTimeout);
2403 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2404 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2405 kDefaultTimeout);
2406}
2407
2408// Ensure that an RTP data channel is signaled as closed for the caller when
2409// the callee rejects it in a subsequent offer.
2410TEST_F(PeerConnectionIntegrationTest,
2411 RtpDataChannelSignaledClosedInCalleeOffer) {
2412 // Same procedure as above test.
2413 FakeConstraints setup_constraints;
2414 setup_constraints.SetAllowRtpDataChannels();
2415 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2416 &setup_constraints));
2417 ConnectFakeSignaling();
2418 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002419 caller()->AddAudioVideoTracks();
2420 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002421 caller()->CreateAndSetAndSignalOffer();
2422 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2423 ASSERT_NE(nullptr, caller()->data_channel());
2424 ASSERT_NE(nullptr, callee()->data_channel());
2425 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2426 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2427
2428 // Close the data channel on the callee, and do an updated offer/answer.
2429 callee()->data_channel()->Close();
2430 callee()->CreateAndSetAndSignalOffer();
2431 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2432 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2433 EXPECT_FALSE(callee()->data_observer()->IsOpen());
2434}
2435
2436// Tests that data is buffered in an RTP data channel until an observer is
2437// registered for it.
2438//
2439// NOTE: RTP data channels can receive data before the underlying
2440// transport has detected that a channel is writable and thus data can be
2441// received before the data channel state changes to open. That is hard to test
2442// but the same buffering is expected to be used in that case.
2443TEST_F(PeerConnectionIntegrationTest,
2444 DataBufferedUntilRtpDataChannelObserverRegistered) {
2445 // Use fake clock and simulated network delay so that we predictably can wait
2446 // until an SCTP message has been delivered without "sleep()"ing.
2447 rtc::ScopedFakeClock fake_clock;
2448 // Some things use a time of "0" as a special value, so we need to start out
2449 // the fake clock at a nonzero time.
2450 // TODO(deadbeef): Fix this.
2451 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2452 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
2453 virtual_socket_server()->UpdateDelayDistribution();
2454
2455 FakeConstraints constraints;
2456 constraints.SetAllowRtpDataChannels();
2457 ASSERT_TRUE(
2458 CreatePeerConnectionWrappersWithConstraints(&constraints, &constraints));
2459 ConnectFakeSignaling();
2460 caller()->CreateDataChannel();
2461 caller()->CreateAndSetAndSignalOffer();
2462 ASSERT_TRUE(caller()->data_channel() != nullptr);
2463 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
2464 kDefaultTimeout, fake_clock);
2465 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
2466 kDefaultTimeout, fake_clock);
2467 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
2468 callee()->data_channel()->state(), kDefaultTimeout,
2469 fake_clock);
2470
2471 // Unregister the observer which is normally automatically registered.
2472 callee()->data_channel()->UnregisterObserver();
2473 // Send data and advance fake clock until it should have been received.
2474 std::string data = "hello world";
2475 caller()->data_channel()->Send(DataBuffer(data));
2476 SIMULATED_WAIT(false, 50, fake_clock);
2477
2478 // Attach data channel and expect data to be received immediately. Note that
2479 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
2480 // further, but data can be received even if the callback is asynchronous.
2481 MockDataChannelObserver new_observer(callee()->data_channel());
2482 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
2483 fake_clock);
2484}
2485
2486// This test sets up a call between two parties with audio, video and but only
2487// the caller client supports RTP data channels.
2488TEST_F(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
2489 FakeConstraints setup_constraints_1;
2490 setup_constraints_1.SetAllowRtpDataChannels();
2491 // Must disable DTLS to make negotiation succeed.
2492 setup_constraints_1.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2493 false);
2494 FakeConstraints setup_constraints_2;
2495 setup_constraints_2.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2496 false);
2497 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(
2498 &setup_constraints_1, &setup_constraints_2));
2499 ConnectFakeSignaling();
2500 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002501 caller()->AddAudioVideoTracks();
2502 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002503 caller()->CreateAndSetAndSignalOffer();
2504 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2505 // The caller should still have a data channel, but it should be closed, and
2506 // one should ever have been created for the callee.
2507 EXPECT_TRUE(caller()->data_channel() != nullptr);
2508 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2509 EXPECT_EQ(nullptr, callee()->data_channel());
2510}
2511
2512// This test sets up a call between two parties with audio, and video. When
2513// audio and video is setup and flowing, an RTP data channel is negotiated.
2514TEST_F(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
2515 FakeConstraints setup_constraints;
2516 setup_constraints.SetAllowRtpDataChannels();
2517 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2518 &setup_constraints));
2519 ConnectFakeSignaling();
2520 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08002521 caller()->AddAudioVideoTracks();
2522 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002523 caller()->CreateAndSetAndSignalOffer();
2524 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2525 // Create data channel and do new offer and answer.
2526 caller()->CreateDataChannel();
2527 caller()->CreateAndSetAndSignalOffer();
2528 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2529 ASSERT_NE(nullptr, caller()->data_channel());
2530 ASSERT_NE(nullptr, callee()->data_channel());
2531 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2532 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2533 // Ensure data can be sent in both directions.
2534 std::string data = "hello world";
2535 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2536 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2537 kDefaultTimeout);
2538 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2539 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2540 kDefaultTimeout);
2541}
2542
2543#ifdef HAVE_SCTP
2544
2545// This test sets up a call between two parties with audio, video and an SCTP
2546// data channel.
2547TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
2548 ASSERT_TRUE(CreatePeerConnectionWrappers());
2549 ConnectFakeSignaling();
2550 // Expect that data channel created on caller side will show up for callee as
2551 // well.
2552 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002553 caller()->AddAudioVideoTracks();
2554 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002555 caller()->CreateAndSetAndSignalOffer();
2556 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2557 // Ensure the existence of the SCTP data channel didn't impede audio/video.
2558 ExpectNewFramesReceivedWithWait(
2559 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2560 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2561 kMaxWaitForFramesMs);
2562 // Caller data channel should already exist (it created one). Callee data
2563 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2564 ASSERT_NE(nullptr, caller()->data_channel());
2565 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2566 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2567 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2568
2569 // Ensure data can be sent in both directions.
2570 std::string data = "hello world";
2571 caller()->data_channel()->Send(DataBuffer(data));
2572 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2573 kDefaultTimeout);
2574 callee()->data_channel()->Send(DataBuffer(data));
2575 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2576 kDefaultTimeout);
2577}
2578
2579// Ensure that when the callee closes an SCTP data channel, the closing
2580// procedure results in the data channel being closed for the caller as well.
2581TEST_F(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
2582 // Same procedure as above test.
2583 ASSERT_TRUE(CreatePeerConnectionWrappers());
2584 ConnectFakeSignaling();
2585 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002586 caller()->AddAudioVideoTracks();
2587 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002588 caller()->CreateAndSetAndSignalOffer();
2589 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2590 ASSERT_NE(nullptr, caller()->data_channel());
2591 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2592 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2593 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2594
2595 // Close the data channel on the callee side, and wait for it to reach the
2596 // "closed" state on both sides.
2597 callee()->data_channel()->Close();
2598 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
2599 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
2600}
2601
Steve Antonda6c0952017-10-23 11:41:54 -07002602TEST_F(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
2603 ASSERT_TRUE(CreatePeerConnectionWrappers());
2604 ConnectFakeSignaling();
2605 webrtc::DataChannelInit init;
2606 init.id = 53;
2607 init.maxRetransmits = 52;
2608 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08002609 caller()->AddAudioVideoTracks();
2610 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07002611 caller()->CreateAndSetAndSignalOffer();
2612 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07002613 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2614 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07002615 EXPECT_EQ(init.id, callee()->data_channel()->id());
2616 EXPECT_EQ("data-channel", callee()->data_channel()->label());
2617 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
2618 EXPECT_FALSE(callee()->data_channel()->negotiated());
2619}
2620
deadbeef1dcb1642017-03-29 21:08:16 -07002621// Test usrsctp's ability to process unordered data stream, where data actually
2622// arrives out of order using simulated delays. Previously there have been some
2623// bugs in this area.
2624TEST_F(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
2625 // Introduce random network delays.
2626 // Otherwise it's not a true "unordered" test.
2627 virtual_socket_server()->set_delay_mean(20);
2628 virtual_socket_server()->set_delay_stddev(5);
2629 virtual_socket_server()->UpdateDelayDistribution();
2630 // Normal procedure, but with unordered data channel config.
2631 ASSERT_TRUE(CreatePeerConnectionWrappers());
2632 ConnectFakeSignaling();
2633 webrtc::DataChannelInit init;
2634 init.ordered = false;
2635 caller()->CreateDataChannel(&init);
2636 caller()->CreateAndSetAndSignalOffer();
2637 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2638 ASSERT_NE(nullptr, caller()->data_channel());
2639 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2640 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2641 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2642
2643 static constexpr int kNumMessages = 100;
2644 // Deliberately chosen to be larger than the MTU so messages get fragmented.
2645 static constexpr size_t kMaxMessageSize = 4096;
2646 // Create and send random messages.
2647 std::vector<std::string> sent_messages;
2648 for (int i = 0; i < kNumMessages; ++i) {
2649 size_t length =
2650 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
2651 std::string message;
2652 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
2653 caller()->data_channel()->Send(DataBuffer(message));
2654 callee()->data_channel()->Send(DataBuffer(message));
2655 sent_messages.push_back(message);
2656 }
2657
2658 // Wait for all messages to be received.
2659 EXPECT_EQ_WAIT(kNumMessages,
2660 caller()->data_observer()->received_message_count(),
2661 kDefaultTimeout);
2662 EXPECT_EQ_WAIT(kNumMessages,
2663 callee()->data_observer()->received_message_count(),
2664 kDefaultTimeout);
2665
2666 // Sort and compare to make sure none of the messages were corrupted.
2667 std::vector<std::string> caller_received_messages =
2668 caller()->data_observer()->messages();
2669 std::vector<std::string> callee_received_messages =
2670 callee()->data_observer()->messages();
2671 std::sort(sent_messages.begin(), sent_messages.end());
2672 std::sort(caller_received_messages.begin(), caller_received_messages.end());
2673 std::sort(callee_received_messages.begin(), callee_received_messages.end());
2674 EXPECT_EQ(sent_messages, caller_received_messages);
2675 EXPECT_EQ(sent_messages, callee_received_messages);
2676}
2677
2678// This test sets up a call between two parties with audio, and video. When
2679// audio and video are setup and flowing, an SCTP data channel is negotiated.
2680TEST_F(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
2681 ASSERT_TRUE(CreatePeerConnectionWrappers());
2682 ConnectFakeSignaling();
2683 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08002684 caller()->AddAudioVideoTracks();
2685 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002686 caller()->CreateAndSetAndSignalOffer();
2687 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2688 // Create data channel and do new offer and answer.
2689 caller()->CreateDataChannel();
2690 caller()->CreateAndSetAndSignalOffer();
2691 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2692 // Caller data channel should already exist (it created one). Callee data
2693 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2694 ASSERT_NE(nullptr, caller()->data_channel());
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 // Ensure data can be sent in both directions.
2699 std::string data = "hello world";
2700 caller()->data_channel()->Send(DataBuffer(data));
2701 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2702 kDefaultTimeout);
2703 callee()->data_channel()->Send(DataBuffer(data));
2704 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2705 kDefaultTimeout);
2706}
2707
deadbeef7914b8c2017-04-21 03:23:33 -07002708// Set up a connection initially just using SCTP data channels, later upgrading
2709// to audio/video, ensuring frames are received end-to-end. Effectively the
2710// inverse of the test above.
2711// This was broken in M57; see https://crbug.com/711243
2712TEST_F(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
2713 ASSERT_TRUE(CreatePeerConnectionWrappers());
2714 ConnectFakeSignaling();
2715 // Do initial offer/answer with just data channel.
2716 caller()->CreateDataChannel();
2717 caller()->CreateAndSetAndSignalOffer();
2718 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2719 // Wait until data can be sent over the data channel.
2720 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2721 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2722 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2723
2724 // Do subsequent offer/answer with two-way audio and video. Audio and video
2725 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08002726 caller()->AddAudioVideoTracks();
2727 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002728 caller()->CreateAndSetAndSignalOffer();
2729 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2730 ExpectNewFramesReceivedWithWait(
2731 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2732 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2733 kMaxWaitForFramesMs);
2734}
2735
deadbeef8b7e9ad2017-05-25 09:38:55 -07002736static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07002737 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08002738 GetFirstDataContentDescription(desc);
2739 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07002740 dcd_offer->set_use_sctpmap(false);
2741 dcd_offer->set_protocol("UDP/DTLS/SCTP");
2742}
2743
2744// Test that the data channel works when a spec-compliant SCTP m= section is
2745// offered (using "a=sctp-port" instead of "a=sctpmap", and using
2746// "UDP/DTLS/SCTP" as the protocol).
2747TEST_F(PeerConnectionIntegrationTest,
2748 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
2749 ASSERT_TRUE(CreatePeerConnectionWrappers());
2750 ConnectFakeSignaling();
2751 caller()->CreateDataChannel();
2752 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
2753 caller()->CreateAndSetAndSignalOffer();
2754 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2755 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2756 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2757 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2758
2759 // Ensure data can be sent in both directions.
2760 std::string data = "hello world";
2761 caller()->data_channel()->Send(DataBuffer(data));
2762 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2763 kDefaultTimeout);
2764 callee()->data_channel()->Send(DataBuffer(data));
2765 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2766 kDefaultTimeout);
2767}
2768
deadbeef1dcb1642017-03-29 21:08:16 -07002769#endif // HAVE_SCTP
2770
2771// Test that the ICE connection and gathering states eventually reach
2772// "complete".
2773TEST_F(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
2774 ASSERT_TRUE(CreatePeerConnectionWrappers());
2775 ConnectFakeSignaling();
2776 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002777 caller()->AddAudioVideoTracks();
2778 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002779 caller()->CreateAndSetAndSignalOffer();
2780 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2781 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2782 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
2783 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2784 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
2785 // After the best candidate pair is selected and all candidates are signaled,
2786 // the ICE connection state should reach "complete".
2787 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
2788 // answerer/"callee" by default) only reaches "connected". When this is
2789 // fixed, this test should be updated.
2790 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2791 caller()->ice_connection_state(), kDefaultTimeout);
2792 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2793 callee()->ice_connection_state(), kDefaultTimeout);
2794}
2795
Steve Antonede9ca52017-10-16 13:04:27 -07002796// Test that firewalling the ICE connection causes the clients to identify the
2797// disconnected state and then removing the firewall causes them to reconnect.
2798class PeerConnectionIntegrationIceStatesTest
2799 : public PeerConnectionIntegrationTest,
2800 public ::testing::WithParamInterface<std::tuple<std::string, uint32_t>> {
2801 protected:
2802 PeerConnectionIntegrationIceStatesTest() {
2803 port_allocator_flags_ = std::get<1>(GetParam());
2804 }
2805
2806 void StartStunServer(const SocketAddress& server_address) {
2807 stun_server_.reset(
2808 cricket::TestStunServer::Create(network_thread(), server_address));
2809 }
2810
2811 bool TestIPv6() {
2812 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
2813 }
2814
2815 void SetPortAllocatorFlags() {
2816 caller()->port_allocator()->set_flags(port_allocator_flags_);
2817 callee()->port_allocator()->set_flags(port_allocator_flags_);
2818 }
2819
2820 std::vector<SocketAddress> CallerAddresses() {
2821 std::vector<SocketAddress> addresses;
2822 addresses.push_back(SocketAddress("1.1.1.1", 0));
2823 if (TestIPv6()) {
2824 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
2825 }
2826 return addresses;
2827 }
2828
2829 std::vector<SocketAddress> CalleeAddresses() {
2830 std::vector<SocketAddress> addresses;
2831 addresses.push_back(SocketAddress("2.2.2.2", 0));
2832 if (TestIPv6()) {
2833 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
2834 }
2835 return addresses;
2836 }
2837
2838 void SetUpNetworkInterfaces() {
2839 // Remove the default interfaces added by the test infrastructure.
2840 caller()->network()->RemoveInterface(kDefaultLocalAddress);
2841 callee()->network()->RemoveInterface(kDefaultLocalAddress);
2842
2843 // Add network addresses for test.
2844 for (const auto& caller_address : CallerAddresses()) {
2845 caller()->network()->AddInterface(caller_address);
2846 }
2847 for (const auto& callee_address : CalleeAddresses()) {
2848 callee()->network()->AddInterface(callee_address);
2849 }
2850 }
2851
2852 private:
2853 uint32_t port_allocator_flags_;
2854 std::unique_ptr<cricket::TestStunServer> stun_server_;
2855};
2856
2857// Tests that the PeerConnection goes through all the ICE gathering/connection
2858// states over the duration of the call. This includes Disconnected and Failed
2859// states, induced by putting a firewall between the peers and waiting for them
2860// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08002861TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
2862 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
2863 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
2864 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07002865
2866 const SocketAddress kStunServerAddress =
2867 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
2868 StartStunServer(kStunServerAddress);
2869
2870 PeerConnectionInterface::RTCConfiguration config;
2871 PeerConnectionInterface::IceServer ice_stun_server;
2872 ice_stun_server.urls.push_back(
2873 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
2874 kStunServerAddress.PortAsString());
2875 config.servers.push_back(ice_stun_server);
2876
2877 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
2878 ConnectFakeSignaling();
2879 SetPortAllocatorFlags();
2880 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08002881 caller()->AddAudioVideoTracks();
2882 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07002883
2884 // Initial state before anything happens.
2885 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
2886 caller()->ice_gathering_state());
2887 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
2888 caller()->ice_connection_state());
2889
2890 // Start the call by creating the offer, setting it as the local description,
2891 // then sending it to the peer who will respond with an answer. This happens
2892 // asynchronously so that we can watch the states as it runs in the
2893 // background.
2894 caller()->CreateAndSetAndSignalOffer();
2895
Steve Anton83119dd2017-11-10 16:19:52 -08002896 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
2897 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002898
2899 // Verify that the observer was notified of the intermediate transitions.
2900 EXPECT_THAT(caller()->ice_connection_state_history(),
2901 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
2902 PeerConnectionInterface::kIceConnectionConnected,
2903 PeerConnectionInterface::kIceConnectionCompleted));
2904 EXPECT_THAT(caller()->ice_gathering_state_history(),
2905 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
2906 PeerConnectionInterface::kIceGatheringComplete));
2907
2908 // Block connections to/from the caller and wait for ICE to become
2909 // disconnected.
2910 for (const auto& caller_address : CallerAddresses()) {
2911 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
2912 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002913 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08002914 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
2915 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002916
2917 // Let ICE re-establish by removing the firewall rules.
2918 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01002919 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08002920 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
2921 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002922
2923 // According to RFC7675, if there is no response within 30 seconds then the
2924 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08002925 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07002926 constexpr int kConsentTimeout = 30000;
2927 for (const auto& caller_address : CallerAddresses()) {
2928 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
2929 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002930 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08002931 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
2932 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002933}
2934
2935// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
2936// and that the statistics in the metric observers are updated correctly.
2937TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
2938 ASSERT_TRUE(CreatePeerConnectionWrappers());
2939 ConnectFakeSignaling();
2940 SetPortAllocatorFlags();
2941 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08002942 caller()->AddAudioVideoTracks();
2943 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07002944
2945 rtc::scoped_refptr<webrtc::FakeMetricsObserver> metrics_observer(
2946 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>());
2947 caller()->pc()->RegisterUMAObserver(metrics_observer.get());
2948
2949 caller()->CreateAndSetAndSignalOffer();
2950
2951 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2952
2953 const int num_best_ipv4 = metrics_observer->GetEnumCounter(
2954 webrtc::kEnumCounterAddressFamily, webrtc::kBestConnections_IPv4);
2955 const int num_best_ipv6 = metrics_observer->GetEnumCounter(
2956 webrtc::kEnumCounterAddressFamily, webrtc::kBestConnections_IPv6);
2957 if (TestIPv6()) {
2958 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
2959 // connection.
2960 EXPECT_EQ(0u, num_best_ipv4);
2961 EXPECT_EQ(1u, num_best_ipv6);
2962 } else {
2963 EXPECT_EQ(1u, num_best_ipv4);
2964 EXPECT_EQ(0u, num_best_ipv6);
2965 }
2966
2967 EXPECT_EQ(0u, metrics_observer->GetEnumCounter(
2968 webrtc::kEnumCounterIceCandidatePairTypeUdp,
2969 webrtc::kIceCandidatePairHostHost));
2970 EXPECT_EQ(1u, metrics_observer->GetEnumCounter(
2971 webrtc::kEnumCounterIceCandidatePairTypeUdp,
2972 webrtc::kIceCandidatePairHostPublicHostPublic));
2973}
2974
2975constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
2976 cricket::PORTALLOCATOR_DISABLE_STUN |
2977 cricket::PORTALLOCATOR_DISABLE_RELAY;
2978constexpr uint32_t kFlagsIPv6NoStun =
2979 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
2980 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
2981constexpr uint32_t kFlagsIPv4Stun =
2982 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
2983
2984INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
2985 PeerConnectionIntegrationIceStatesTest,
2986 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
2987 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
2988 std::make_pair("IPv4 with STUN",
2989 kFlagsIPv4Stun)));
2990
deadbeef1dcb1642017-03-29 21:08:16 -07002991// This test sets up a call between two parties with audio and video.
2992// During the call, the caller restarts ICE and the test verifies that
2993// new ICE candidates are generated and audio and video still can flow, and the
2994// ICE state reaches completed again.
2995TEST_F(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
2996 ASSERT_TRUE(CreatePeerConnectionWrappers());
2997 ConnectFakeSignaling();
2998 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08002999 caller()->AddAudioVideoTracks();
3000 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003001 caller()->CreateAndSetAndSignalOffer();
3002 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3003 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3004 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3005 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3006 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3007
3008 // To verify that the ICE restart actually occurs, get
3009 // ufrag/password/candidates before and after restart.
3010 // Create an SDP string of the first audio candidate for both clients.
3011 const webrtc::IceCandidateCollection* audio_candidates_caller =
3012 caller()->pc()->local_description()->candidates(0);
3013 const webrtc::IceCandidateCollection* audio_candidates_callee =
3014 callee()->pc()->local_description()->candidates(0);
3015 ASSERT_GT(audio_candidates_caller->count(), 0u);
3016 ASSERT_GT(audio_candidates_callee->count(), 0u);
3017 std::string caller_candidate_pre_restart;
3018 ASSERT_TRUE(
3019 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
3020 std::string callee_candidate_pre_restart;
3021 ASSERT_TRUE(
3022 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
3023 const cricket::SessionDescription* desc =
3024 caller()->pc()->local_description()->description();
3025 std::string caller_ufrag_pre_restart =
3026 desc->transport_infos()[0].description.ice_ufrag;
3027 desc = callee()->pc()->local_description()->description();
3028 std::string callee_ufrag_pre_restart =
3029 desc->transport_infos()[0].description.ice_ufrag;
3030
3031 // Have the caller initiate an ICE restart.
3032 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
3033 caller()->CreateAndSetAndSignalOffer();
3034 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3035 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3036 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3037 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3038 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3039
3040 // Grab the ufrags/candidates again.
3041 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
3042 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
3043 ASSERT_GT(audio_candidates_caller->count(), 0u);
3044 ASSERT_GT(audio_candidates_callee->count(), 0u);
3045 std::string caller_candidate_post_restart;
3046 ASSERT_TRUE(
3047 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
3048 std::string callee_candidate_post_restart;
3049 ASSERT_TRUE(
3050 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
3051 desc = caller()->pc()->local_description()->description();
3052 std::string caller_ufrag_post_restart =
3053 desc->transport_infos()[0].description.ice_ufrag;
3054 desc = callee()->pc()->local_description()->description();
3055 std::string callee_ufrag_post_restart =
3056 desc->transport_infos()[0].description.ice_ufrag;
3057 // Sanity check that an ICE restart was actually negotiated in SDP.
3058 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
3059 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
3060 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
3061 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
3062
3063 // Ensure that additional frames are received after the ICE restart.
3064 ExpectNewFramesReceivedWithWait(
3065 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3066 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3067 kMaxWaitForFramesMs);
3068}
3069
3070// Verify that audio/video can be received end-to-end when ICE renomination is
3071// enabled.
3072TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
3073 PeerConnectionInterface::RTCConfiguration config;
3074 config.enable_ice_renomination = true;
3075 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3076 ConnectFakeSignaling();
3077 // Do normal offer/answer and wait for some frames to be received in each
3078 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003079 caller()->AddAudioVideoTracks();
3080 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003081 caller()->CreateAndSetAndSignalOffer();
3082 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3083 // Sanity check that ICE renomination was actually negotiated.
3084 const cricket::SessionDescription* desc =
3085 caller()->pc()->local_description()->description();
3086 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003087 ASSERT_NE(
3088 info.description.transport_options.end(),
3089 std::find(info.description.transport_options.begin(),
3090 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003091 }
3092 desc = callee()->pc()->local_description()->description();
3093 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003094 ASSERT_NE(
3095 info.description.transport_options.end(),
3096 std::find(info.description.transport_options.begin(),
3097 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003098 }
3099 ExpectNewFramesReceivedWithWait(
3100 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3101 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3102 kMaxWaitForFramesMs);
3103}
3104
Steve Anton6f25b092017-10-23 09:39:20 -07003105// With a max bundle policy and RTCP muxing, adding a new media description to
3106// the connection should not affect ICE at all because the new media will use
3107// the existing connection.
3108TEST_F(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003109 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07003110 PeerConnectionInterface::RTCConfiguration config;
3111 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3112 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3113 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
3114 config, PeerConnectionInterface::RTCConfiguration()));
3115 ConnectFakeSignaling();
3116
Steve Anton15324772018-01-16 10:26:49 -08003117 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003118 caller()->CreateAndSetAndSignalOffer();
3119 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07003120 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3121 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07003122
3123 caller()->clear_ice_connection_state_history();
3124
Steve Anton15324772018-01-16 10:26:49 -08003125 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003126 caller()->CreateAndSetAndSignalOffer();
3127 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3128
3129 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
3130}
3131
deadbeef1dcb1642017-03-29 21:08:16 -07003132// This test sets up a call between two parties with audio and video. It then
3133// renegotiates setting the video m-line to "port 0", then later renegotiates
3134// again, enabling video.
3135TEST_F(PeerConnectionIntegrationTest,
3136 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
3137 ASSERT_TRUE(CreatePeerConnectionWrappers());
3138 ConnectFakeSignaling();
3139
3140 // Do initial negotiation, only sending media from the caller. Will result in
3141 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08003142 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003143 caller()->CreateAndSetAndSignalOffer();
3144 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3145
3146 // Negotiate again, disabling the video "m=" section (the callee will set the
3147 // port to 0 due to offer_to_receive_video = 0).
3148 PeerConnectionInterface::RTCOfferAnswerOptions options;
3149 options.offer_to_receive_video = 0;
3150 callee()->SetOfferAnswerOptions(options);
3151 caller()->CreateAndSetAndSignalOffer();
3152 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3153 // Sanity check that video "m=" section was actually rejected.
3154 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
3155 callee()->pc()->local_description()->description());
3156 ASSERT_NE(nullptr, answer_video_content);
3157 ASSERT_TRUE(answer_video_content->rejected);
3158
3159 // Enable video and do negotiation again, making sure video is received
3160 // end-to-end, also adding media stream to callee.
3161 options.offer_to_receive_video = 1;
3162 callee()->SetOfferAnswerOptions(options);
Steve Anton15324772018-01-16 10:26:49 -08003163 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003164 caller()->CreateAndSetAndSignalOffer();
3165 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3166 // Verify the caller receives frames from the newly added stream, and the
3167 // callee receives additional frames from the re-enabled video m= section.
3168 ExpectNewFramesReceivedWithWait(
3169 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3170 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3171 kMaxWaitForFramesMs);
3172}
3173
3174// This test sets up a Jsep call between two parties with external
3175// VideoDecoderFactory.
3176// TODO(holmer): Disabled due to sometimes crashing on buildbots.
3177// See issue webrtc/2378.
3178TEST_F(PeerConnectionIntegrationTest,
3179 DISABLED_EndToEndCallWithVideoDecoderFactory) {
3180 ASSERT_TRUE(CreatePeerConnectionWrappers());
3181 EnableVideoDecoderFactory();
3182 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003183 caller()->AddAudioVideoTracks();
3184 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003185 caller()->CreateAndSetAndSignalOffer();
3186 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3187 ExpectNewFramesReceivedWithWait(
3188 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3189 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3190 kMaxWaitForFramesMs);
3191}
3192
3193// This tests that if we negotiate after calling CreateSender but before we
3194// have a track, then set a track later, frames from the newly-set track are
3195// received end-to-end.
3196// TODO(deadbeef): Change this test to use AddTransceiver, once that's
3197// implemented.
3198TEST_F(PeerConnectionIntegrationTest,
3199 MediaFlowsAfterEarlyWarmupWithCreateSender) {
3200 ASSERT_TRUE(CreatePeerConnectionWrappers());
3201 ConnectFakeSignaling();
3202 auto caller_audio_sender =
3203 caller()->pc()->CreateSender("audio", "caller_stream");
3204 auto caller_video_sender =
3205 caller()->pc()->CreateSender("video", "caller_stream");
3206 auto callee_audio_sender =
3207 callee()->pc()->CreateSender("audio", "callee_stream");
3208 auto callee_video_sender =
3209 callee()->pc()->CreateSender("video", "callee_stream");
3210 caller()->CreateAndSetAndSignalOffer();
3211 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3212 // Wait for ICE to complete, without any tracks being set.
3213 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3214 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3215 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3216 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3217 // Now set the tracks, and expect frames to immediately start flowing.
3218 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3219 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3220 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3221 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
3222 ExpectNewFramesReceivedWithWait(
3223 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3224 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3225 kMaxWaitForFramesMs);
3226}
3227
3228// This test verifies that a remote video track can be added via AddStream,
3229// and sent end-to-end. For this particular test, it's simply echoed back
3230// from the caller to the callee, rather than being forwarded to a third
3231// PeerConnection.
3232TEST_F(PeerConnectionIntegrationTest, CanSendRemoteVideoTrack) {
3233 ASSERT_TRUE(CreatePeerConnectionWrappers());
3234 ConnectFakeSignaling();
3235 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08003236 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07003237 caller()->CreateAndSetAndSignalOffer();
3238 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3239 ASSERT_EQ(1, callee()->remote_streams()->count());
3240
3241 // Echo the stream back, and do a new offer/anwer (initiated by callee this
3242 // time).
3243 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
3244 callee()->CreateAndSetAndSignalOffer();
3245 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3246
3247 int expected_caller_received_video_frames = kDefaultExpectedVideoFrameCount;
3248 ExpectNewFramesReceivedWithWait(0, expected_caller_received_video_frames, 0,
3249 0, kMaxWaitForFramesMs);
3250}
3251
3252// Test that we achieve the expected end-to-end connection time, using a
3253// fake clock and simulated latency on the media and signaling paths.
3254// We use a TURN<->TURN connection because this is usually the quickest to
3255// set up initially, especially when we're confident the connection will work
3256// and can start sending media before we get a STUN response.
3257//
3258// With various optimizations enabled, here are the network delays we expect to
3259// be on the critical path:
3260// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
3261// signaling answer (with DTLS fingerprint).
3262// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
3263// using TURN<->TURN pair, and DTLS exchange is 4 packets,
3264// the first of which should have arrived before the answer.
3265TEST_F(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
3266 rtc::ScopedFakeClock fake_clock;
3267 // Some things use a time of "0" as a special value, so we need to start out
3268 // the fake clock at a nonzero time.
3269 // TODO(deadbeef): Fix this.
3270 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
3271
3272 static constexpr int media_hop_delay_ms = 50;
3273 static constexpr int signaling_trip_delay_ms = 500;
3274 // For explanation of these values, see comment above.
3275 static constexpr int required_media_hops = 9;
3276 static constexpr int required_signaling_trips = 2;
3277 // For internal delays (such as posting an event asychronously).
3278 static constexpr int allowed_internal_delay_ms = 20;
3279 static constexpr int total_connection_time_ms =
3280 media_hop_delay_ms * required_media_hops +
3281 signaling_trip_delay_ms * required_signaling_trips +
3282 allowed_internal_delay_ms;
3283
3284 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3285 3478};
3286 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3287 0};
3288 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3289 3478};
3290 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3291 0};
3292 cricket::TestTurnServer turn_server_1(network_thread(),
3293 turn_server_1_internal_address,
3294 turn_server_1_external_address);
3295 cricket::TestTurnServer turn_server_2(network_thread(),
3296 turn_server_2_internal_address,
3297 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02003298
deadbeef1dcb1642017-03-29 21:08:16 -07003299 // Bypass permission check on received packets so media can be sent before
3300 // the candidate is signaled.
3301 turn_server_1.set_enable_permission_checks(false);
3302 turn_server_2.set_enable_permission_checks(false);
3303
3304 PeerConnectionInterface::RTCConfiguration client_1_config;
3305 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3306 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3307 ice_server_1.username = "test";
3308 ice_server_1.password = "test";
3309 client_1_config.servers.push_back(ice_server_1);
3310 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3311 client_1_config.presume_writable_when_fully_relayed = true;
3312
3313 PeerConnectionInterface::RTCConfiguration client_2_config;
3314 webrtc::PeerConnectionInterface::IceServer ice_server_2;
3315 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
3316 ice_server_2.username = "test";
3317 ice_server_2.password = "test";
3318 client_2_config.servers.push_back(ice_server_2);
3319 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
3320 client_2_config.presume_writable_when_fully_relayed = true;
3321
3322 ASSERT_TRUE(
3323 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
3324 // Set up the simulated delays.
3325 SetSignalingDelayMs(signaling_trip_delay_ms);
3326 ConnectFakeSignaling();
3327 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
3328 virtual_socket_server()->UpdateDelayDistribution();
3329
3330 // Set "offer to receive audio/video" without adding any tracks, so we just
3331 // set up ICE/DTLS with no media.
3332 PeerConnectionInterface::RTCOfferAnswerOptions options;
3333 options.offer_to_receive_audio = 1;
3334 options.offer_to_receive_video = 1;
3335 caller()->SetOfferAnswerOptions(options);
3336 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07003337 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
3338 fake_clock);
deadbeef1dcb1642017-03-29 21:08:16 -07003339 // Need to free the clients here since they're using things we created on
3340 // the stack.
3341 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
3342 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
3343}
3344
Jonas Orelandbdcee282017-10-10 14:01:40 +02003345// Verify that a TurnCustomizer passed in through RTCConfiguration
3346// is actually used by the underlying TURN candidate pair.
3347// Note that turnport_unittest.cc contains more detailed, lower-level tests.
3348TEST_F(PeerConnectionIntegrationTest, \
3349 TurnCustomizerUsedForTurnConnections) {
3350 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3351 3478};
3352 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3353 0};
3354 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3355 3478};
3356 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3357 0};
3358 cricket::TestTurnServer turn_server_1(network_thread(),
3359 turn_server_1_internal_address,
3360 turn_server_1_external_address);
3361 cricket::TestTurnServer turn_server_2(network_thread(),
3362 turn_server_2_internal_address,
3363 turn_server_2_external_address);
3364
3365 PeerConnectionInterface::RTCConfiguration client_1_config;
3366 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3367 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3368 ice_server_1.username = "test";
3369 ice_server_1.password = "test";
3370 client_1_config.servers.push_back(ice_server_1);
3371 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3372 auto customizer1 = rtc::MakeUnique<cricket::TestTurnCustomizer>();
3373 client_1_config.turn_customizer = customizer1.get();
3374
3375 PeerConnectionInterface::RTCConfiguration client_2_config;
3376 webrtc::PeerConnectionInterface::IceServer ice_server_2;
3377 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
3378 ice_server_2.username = "test";
3379 ice_server_2.password = "test";
3380 client_2_config.servers.push_back(ice_server_2);
3381 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
3382 auto customizer2 = rtc::MakeUnique<cricket::TestTurnCustomizer>();
3383 client_2_config.turn_customizer = customizer2.get();
3384
3385 ASSERT_TRUE(
3386 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
3387 ConnectFakeSignaling();
3388
3389 // Set "offer to receive audio/video" without adding any tracks, so we just
3390 // set up ICE/DTLS with no media.
3391 PeerConnectionInterface::RTCOfferAnswerOptions options;
3392 options.offer_to_receive_audio = 1;
3393 options.offer_to_receive_video = 1;
3394 caller()->SetOfferAnswerOptions(options);
3395 caller()->CreateAndSetAndSignalOffer();
3396 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
3397
3398 EXPECT_GT(customizer1->allow_channel_data_cnt_, 0u);
3399 EXPECT_GT(customizer1->modify_cnt_, 0u);
3400
3401 EXPECT_GT(customizer2->allow_channel_data_cnt_, 0u);
3402 EXPECT_GT(customizer2->modify_cnt_, 0u);
3403
3404 // Need to free the clients here since they're using things we created on
3405 // the stack.
3406 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
3407 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
3408}
3409
deadbeefc964d0b2017-04-03 10:03:35 -07003410// Test that audio and video flow end-to-end when codec names don't use the
3411// expected casing, given that they're supposed to be case insensitive. To test
3412// this, all but one codec is removed from each media description, and its
3413// casing is changed.
3414//
3415// In the past, this has regressed and caused crashes/black video, due to the
3416// fact that code at some layers was doing case-insensitive comparisons and
3417// code at other layers was not.
3418TEST_F(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
3419 ASSERT_TRUE(CreatePeerConnectionWrappers());
3420 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003421 caller()->AddAudioVideoTracks();
3422 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07003423
3424 // Remove all but one audio/video codec (opus and VP8), and change the
3425 // casing of the caller's generated offer.
3426 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
3427 cricket::AudioContentDescription* audio =
3428 GetFirstAudioContentDescription(description);
3429 ASSERT_NE(nullptr, audio);
3430 auto audio_codecs = audio->codecs();
3431 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
3432 [](const cricket::AudioCodec& codec) {
3433 return codec.name != "opus";
3434 }),
3435 audio_codecs.end());
3436 ASSERT_EQ(1u, audio_codecs.size());
3437 audio_codecs[0].name = "OpUs";
3438 audio->set_codecs(audio_codecs);
3439
3440 cricket::VideoContentDescription* video =
3441 GetFirstVideoContentDescription(description);
3442 ASSERT_NE(nullptr, video);
3443 auto video_codecs = video->codecs();
3444 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
3445 [](const cricket::VideoCodec& codec) {
3446 return codec.name != "VP8";
3447 }),
3448 video_codecs.end());
3449 ASSERT_EQ(1u, video_codecs.size());
3450 video_codecs[0].name = "vP8";
3451 video->set_codecs(video_codecs);
3452 });
3453
3454 caller()->CreateAndSetAndSignalOffer();
3455 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3456
3457 // Verify frames are still received end-to-end.
3458 ExpectNewFramesReceivedWithWait(
3459 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3460 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3461 kMaxWaitForFramesMs);
3462}
3463
hbos8d609f62017-04-10 07:39:05 -07003464TEST_F(PeerConnectionIntegrationTest, GetSources) {
3465 ASSERT_TRUE(CreatePeerConnectionWrappers());
3466 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003467 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07003468 caller()->CreateAndSetAndSignalOffer();
3469 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07003470 // Wait for one audio frame to be received by the callee.
hbos8d609f62017-04-10 07:39:05 -07003471 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
3472 ASSERT_GT(callee()->pc()->GetReceivers().size(), 0u);
3473 auto receiver = callee()->pc()->GetReceivers()[0];
3474 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
3475
3476 auto contributing_sources = receiver->GetSources();
3477 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
3478 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
3479 contributing_sources[0].source_id());
3480}
3481
deadbeef2f425aa2017-04-14 10:41:32 -07003482// Test that if a track is removed and added again with a different stream ID,
3483// the new stream ID is successfully communicated in SDP and media continues to
3484// flow end-to-end.
3485TEST_F(PeerConnectionIntegrationTest, RemoveAndAddTrackWithNewStreamId) {
3486 ASSERT_TRUE(CreatePeerConnectionWrappers());
3487 ConnectFakeSignaling();
3488
3489 rtc::scoped_refptr<MediaStreamInterface> stream_1 =
3490 caller()->pc_factory()->CreateLocalMediaStream("stream_1");
3491 rtc::scoped_refptr<MediaStreamInterface> stream_2 =
3492 caller()->pc_factory()->CreateLocalMediaStream("stream_2");
3493
3494 // Add track using stream 1, do offer/answer.
3495 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
3496 caller()->CreateLocalAudioTrack();
3497 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
3498 caller()->pc()->AddTrack(track, {stream_1.get()});
3499 caller()->CreateAndSetAndSignalOffer();
3500 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3501 // Wait for one audio frame to be received by the callee.
3502 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
3503
3504 // Remove the sender, and create a new one with the new stream.
3505 caller()->pc()->RemoveTrack(sender);
3506 sender = caller()->pc()->AddTrack(track, {stream_2.get()});
3507 caller()->CreateAndSetAndSignalOffer();
3508 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3509 // Wait for additional audio frames to be received by the callee.
3510 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount, 0,
3511 kMaxWaitForFramesMs);
3512}
3513
Elad Alon99c3fe52017-10-13 16:29:40 +02003514TEST_F(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
3515 ASSERT_TRUE(CreatePeerConnectionWrappers());
3516 ConnectFakeSignaling();
3517
3518 auto output = rtc::MakeUnique<testing::NiceMock<MockRtcEventLogOutput>>();
3519 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
3520 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
3521 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01003522 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
3523 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02003524
Steve Anton15324772018-01-16 10:26:49 -08003525 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02003526 caller()->CreateAndSetAndSignalOffer();
3527 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3528}
3529
Steve Antonede9ca52017-10-16 13:04:27 -07003530// Test that if candidates are only signaled by applying full session
3531// descriptions (instead of using AddIceCandidate), the peers can connect to
3532// each other and exchange media.
3533TEST_F(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
3534 ASSERT_TRUE(CreatePeerConnectionWrappers());
3535 // Each side will signal the session descriptions but not candidates.
3536 ConnectFakeSignalingForSdpOnly();
3537
3538 // Add audio video track and exchange the initial offer/answer with media
3539 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08003540 caller()->AddAudioVideoTracks();
3541 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003542 caller()->CreateAndSetAndSignalOffer();
3543
3544 // Wait for all candidates to be gathered on both the caller and callee.
3545 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
3546 caller()->ice_gathering_state(), kDefaultTimeout);
3547 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
3548 callee()->ice_gathering_state(), kDefaultTimeout);
3549
3550 // The candidates will now be included in the session description, so
3551 // signaling them will start the ICE connection.
3552 caller()->CreateAndSetAndSignalOffer();
3553 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3554
3555 // Ensure that media flows in both directions.
3556 ExpectNewFramesReceivedWithWait(
3557 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3558 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3559 kMaxWaitForFramesMs);
3560}
3561
henrika5f6bf242017-11-01 11:06:56 +01003562// Test that SetAudioPlayout can be used to disable audio playout from the
3563// start, then later enable it. This may be useful, for example, if the caller
3564// needs to play a local ringtone until some event occurs, after which it
3565// switches to playing the received audio.
3566TEST_F(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
3567 ASSERT_TRUE(CreatePeerConnectionWrappers());
3568 ConnectFakeSignaling();
3569
3570 // Set up audio-only call where audio playout is disabled on caller's side.
3571 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08003572 caller()->AddAudioTrack();
3573 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01003574 caller()->CreateAndSetAndSignalOffer();
3575 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3576
3577 // Pump messages for a second.
3578 WAIT(false, 1000);
3579 // Since audio playout is disabled, the caller shouldn't have received
3580 // anything (at the playout level, at least).
3581 EXPECT_EQ(0, caller()->audio_frames_received());
3582 // As a sanity check, make sure the callee (for which playout isn't disabled)
3583 // did still see frames on its audio level.
3584 ASSERT_GT(callee()->audio_frames_received(), 0);
3585
3586 // Enable playout again, and ensure audio starts flowing.
3587 caller()->pc()->SetAudioPlayout(true);
3588 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
3589 kDefaultExpectedAudioFrameCount, 0,
3590 kMaxWaitForFramesMs);
3591}
3592
3593double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
3594 auto report = pc->NewGetStats();
3595 auto track_stats_list =
3596 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3597 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
3598 for (const auto* track_stats : track_stats_list) {
3599 if (track_stats->remote_source.is_defined() &&
3600 *track_stats->remote_source) {
3601 remote_track_stats = track_stats;
3602 break;
3603 }
3604 }
3605
3606 if (!remote_track_stats->total_audio_energy.is_defined()) {
3607 return 0.0;
3608 }
3609 return *remote_track_stats->total_audio_energy;
3610}
3611
3612// Test that if audio playout is disabled via the SetAudioPlayout() method, then
3613// incoming audio is still processed and statistics are generated.
3614TEST_F(PeerConnectionIntegrationTest,
3615 DisableAudioPlayoutStillGeneratesAudioStats) {
3616 ASSERT_TRUE(CreatePeerConnectionWrappers());
3617 ConnectFakeSignaling();
3618
3619 // Set up audio-only call where playout is disabled but audio-processing is
3620 // still active.
Steve Anton15324772018-01-16 10:26:49 -08003621 caller()->AddAudioTrack();
3622 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01003623 caller()->pc()->SetAudioPlayout(false);
3624
3625 caller()->CreateAndSetAndSignalOffer();
3626 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3627
3628 // Wait for the callee to receive audio stats.
3629 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
3630}
3631
henrika4f167df2017-11-01 14:45:55 +01003632// Test that SetAudioRecording can be used to disable audio recording from the
3633// start, then later enable it. This may be useful, for example, if the caller
3634// wants to ensure that no audio resources are active before a certain state
3635// is reached.
3636TEST_F(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
3637 ASSERT_TRUE(CreatePeerConnectionWrappers());
3638 ConnectFakeSignaling();
3639
3640 // Set up audio-only call where audio recording is disabled on caller's side.
3641 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08003642 caller()->AddAudioTrack();
3643 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01003644 caller()->CreateAndSetAndSignalOffer();
3645 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3646
3647 // Pump messages for a second.
3648 WAIT(false, 1000);
3649 // Since caller has disabled audio recording, the callee shouldn't have
3650 // received anything.
3651 EXPECT_EQ(0, callee()->audio_frames_received());
3652 // As a sanity check, make sure the caller did still see frames on its
3653 // audio level since audio recording is enabled on the calle side.
3654 ASSERT_GT(caller()->audio_frames_received(), 0);
3655
3656 // Enable audio recording again, and ensure audio starts flowing.
3657 caller()->pc()->SetAudioRecording(true);
3658 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
3659 kDefaultExpectedAudioFrameCount, 0,
3660 kMaxWaitForFramesMs);
3661}
3662
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08003663// Test that after closing PeerConnections, they stop sending any packets (ICE,
3664// DTLS, RTP...).
3665TEST_F(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
3666 // Set up audio/video/data, wait for some frames to be received.
3667 ASSERT_TRUE(CreatePeerConnectionWrappers());
3668 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003669 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08003670#ifdef HAVE_SCTP
3671 caller()->CreateDataChannel();
3672#endif
3673 caller()->CreateAndSetAndSignalOffer();
3674 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3675 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount,
3676 kDefaultExpectedAudioFrameCount,
3677 kMaxWaitForFramesMs);
3678 // Close PeerConnections.
3679 caller()->pc()->Close();
3680 callee()->pc()->Close();
3681 // Pump messages for a second, and ensure no new packets end up sent.
3682 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
3683 WAIT(false, 1000);
3684 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
3685 EXPECT_EQ(sent_packets_a, sent_packets_b);
3686}
3687
Steve Antond3679212018-01-17 17:41:02 -08003688// Test that a basic 1 audio and 1 video track call works when Unified Plan
3689// semantics configured for both sides.
3690TEST_F(PeerConnectionIntegrationTest, UnifiedPlanMediaFlows) {
3691 PeerConnectionInterface::RTCConfiguration config;
3692 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
3693 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3694 ConnectFakeSignaling();
3695 caller()->AddAudioVideoTracks();
3696 callee()->AddAudioVideoTracks();
3697 caller()->CreateAndSetAndSignalOffer();
3698 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3699 ExpectNewFramesReceivedWithWait(
3700 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3701 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3702 kMaxWaitForFramesMs);
3703}
3704
Steve Anton74255ff2018-01-24 18:32:57 -08003705// Tests that verify interoperability between Plan B and Unified Plan
3706// PeerConnections.
3707class PeerConnectionIntegrationInteropTest
3708 : public PeerConnectionIntegrationTest,
3709 public ::testing::WithParamInterface<
3710 std::tuple<SdpSemantics, SdpSemantics>> {
3711 protected:
3712 PeerConnectionIntegrationInteropTest()
3713 : caller_semantics_(std::get<0>(GetParam())),
3714 callee_semantics_(std::get<1>(GetParam())) {}
3715
3716 bool CreatePeerConnectionWrappersWithSemantics() {
3717 RTCConfiguration caller_config;
3718 caller_config.sdp_semantics = caller_semantics_;
3719 RTCConfiguration callee_config;
3720 callee_config.sdp_semantics = callee_semantics_;
3721 return CreatePeerConnectionWrappersWithConfig(caller_config, callee_config);
3722 }
3723
3724 const SdpSemantics caller_semantics_;
3725 const SdpSemantics callee_semantics_;
3726};
3727
3728TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
3729 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3730 ConnectFakeSignaling();
3731
3732 caller()->CreateAndSetAndSignalOffer();
3733 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3734}
3735
3736TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
3737 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3738 ConnectFakeSignaling();
3739 auto audio_sender = caller()->AddAudioTrack();
3740
3741 caller()->CreateAndSetAndSignalOffer();
3742 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3743
3744 // Verify that one audio receiver has been created on the remote and that it
3745 // has the same track ID as the sending track.
3746 auto receivers = callee()->pc()->GetReceivers();
3747 ASSERT_EQ(1u, receivers.size());
3748 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
3749 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
3750
3751 // Expect to receive only audio frames on the callee.
3752 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount, 0,
3753 kMaxWaitForFramesMs);
3754}
3755
3756TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
3757 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3758 ConnectFakeSignaling();
3759 auto video_sender = caller()->AddVideoTrack();
3760 auto audio_sender = caller()->AddAudioTrack();
3761
3762 caller()->CreateAndSetAndSignalOffer();
3763 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3764
3765 // Verify that one audio and one video receiver have been created on the
3766 // remote and that they have the same track IDs as the sending tracks.
3767 auto audio_receivers =
3768 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
3769 ASSERT_EQ(1u, audio_receivers.size());
3770 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
3771 auto video_receivers =
3772 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
3773 ASSERT_EQ(1u, video_receivers.size());
3774 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
3775
3776 // Expect to receive audio and video frames only on the callee.
3777 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount,
3778 kDefaultExpectedVideoFrameCount,
3779 kMaxWaitForFramesMs);
3780}
3781
3782TEST_P(PeerConnectionIntegrationInteropTest,
3783 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
3784 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3785 ConnectFakeSignaling();
3786 caller()->AddAudioVideoTracks();
3787 callee()->AddAudioVideoTracks();
3788
3789 caller()->CreateAndSetAndSignalOffer();
3790 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3791
3792 ExpectNewFramesReceivedWithWait(
3793 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3794 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3795 kMaxWaitForFramesMs);
3796}
3797
3798TEST_P(PeerConnectionIntegrationInteropTest,
3799 ReverseRolesOneAudioLocalToOneVideoRemote) {
3800 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3801 ConnectFakeSignaling();
3802 caller()->AddAudioTrack();
3803 callee()->AddVideoTrack();
3804
3805 caller()->CreateAndSetAndSignalOffer();
3806 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3807
3808 // Verify that only the audio track has been negotiated.
3809 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
3810 // Might also check that the callee's NegotiationNeeded flag is set.
3811
3812 // Reverse roles.
3813 callee()->CreateAndSetAndSignalOffer();
3814 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3815
3816 // Expect to receive audio frames on the callee and video frames on the
3817 // caller.
3818 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount,
3819 kDefaultExpectedAudioFrameCount, 0,
3820 kMaxWaitForFramesMs);
3821}
3822
3823// Test that if one side offers two video tracks then the other side will only
3824// see the first one and ignore the second.
3825TEST_P(PeerConnectionIntegrationInteropTest, TwoVideoLocalToNoMediaRemote) {
3826 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3827 ConnectFakeSignaling();
3828 auto first_sender = caller()->AddVideoTrack();
3829 caller()->AddVideoTrack();
3830
3831 caller()->CreateAndSetAndSignalOffer();
3832 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3833
3834 // Verify that there is only one receiver and it corresponds to the first
3835 // added track.
3836 auto receivers = callee()->pc()->GetReceivers();
3837 ASSERT_EQ(1u, receivers.size());
3838 EXPECT_TRUE(receivers[0]->track()->enabled());
3839 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
3840
3841 // Expect to receive video frames from the one track.
3842 ExpectNewFramesReceivedWithWait(0, 0,
3843 0, kDefaultExpectedVideoFrameCount,
3844 kMaxWaitForFramesMs);
3845}
3846
3847// Test that in the multi-track case each endpoint only looks at the first track
3848// and ignores the second one.
3849TEST_P(PeerConnectionIntegrationInteropTest, TwoVideoLocalToTwoVideoRemote) {
3850 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3851 ConnectFakeSignaling();
3852 caller()->AddVideoTrack();
3853 caller()->AddVideoTrack();
3854 callee()->AddVideoTrack();
3855 callee()->AddVideoTrack();
3856
3857 caller()->CreateAndSetAndSignalOffer();
3858 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3859
3860 PeerConnectionWrapper* plan_b =
3861 (caller_semantics_ == SdpSemantics::kPlanB ? caller() : callee());
3862 PeerConnectionWrapper* unified_plan =
3863 (caller_semantics_ == SdpSemantics::kUnifiedPlan ? caller() : callee());
3864
3865 // Should have two senders each, one for each track.
3866 EXPECT_EQ(2u, plan_b->pc()->GetSenders().size());
3867 EXPECT_EQ(2u, unified_plan->pc()->GetSenders().size());
3868
3869 // Plan B will have one receiver since it only looks at the first video
3870 // section. The receiver should have the same track ID as the sender's first
3871 // track.
3872 ASSERT_EQ(1u, plan_b->pc()->GetReceivers().size());
3873 EXPECT_EQ(unified_plan->pc()->GetSenders()[0]->track()->id(),
3874 plan_b->pc()->GetReceivers()[0]->track()->id());
3875
3876 // Unified Plan will have two receivers since they were created with the
3877 // transceivers when the tracks were added.
3878 ASSERT_EQ(2u, unified_plan->pc()->GetReceivers().size());
3879
3880 if (unified_plan == caller()) {
3881 // If the Unified Plan endpoint was the caller, then the Plan B endpoint
3882 // would have rejected the second video media section so we would expect the
3883 // transceiver to be stopped.
3884 EXPECT_FALSE(unified_plan->pc()->GetTransceivers()[0]->stopped());
3885 EXPECT_TRUE(unified_plan->pc()->GetTransceivers()[1]->stopped());
3886 } else {
3887 // If the Unified Plan endpoint was the callee, then the Plan B endpoint
3888 // would have offered only one video section so we would expect the first
3889 // transceiver to map to the first track and the second transceiver to be
3890 // missing a mid.
3891 EXPECT_TRUE(unified_plan->pc()->GetTransceivers()[0]->mid());
3892 EXPECT_FALSE(unified_plan->pc()->GetTransceivers()[1]->mid());
3893 }
3894
3895 // Should be exchanging video frames for the first tracks on each endpoint.
3896 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount, 0,
3897 kDefaultExpectedVideoFrameCount,
3898 kMaxWaitForFramesMs);
3899}
3900
3901INSTANTIATE_TEST_CASE_P(
3902 PeerConnectionIntegrationTest,
3903 PeerConnectionIntegrationInteropTest,
3904 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
3905 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
3906
deadbeef1dcb1642017-03-29 21:08:16 -07003907} // namespace
3908
3909#endif // if !defined(THREAD_SANITIZER)