blob: 2768358d82b36b6437e21409a15d2a8acd4ea849 [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.
110static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_32;
111static 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
1155 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;
1162 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 };
1365
1366 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1367 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1368
1369 // Configure each side with a known certificate so they can be compared later.
1370 PeerConnectionInterface::RTCConfiguration caller_config;
1371 caller_config.enable_dtls_srtp.emplace(true);
1372 caller_config.certificates.push_back(caller_cert);
1373 PeerConnectionInterface::RTCConfiguration callee_config;
1374 callee_config.enable_dtls_srtp.emplace(true);
1375 callee_config.certificates.push_back(callee_cert);
1376 ASSERT_TRUE(
1377 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1378 ConnectFakeSignaling();
1379
1380 // When first initialized, there should not be a remote SSL certificate (and
1381 // calling this method should not crash).
1382 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1383 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
1384
Steve Anton15324772018-01-16 10:26:49 -08001385 caller()->AddAudioTrack();
1386 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001387 caller()->CreateAndSetAndSignalOffer();
1388 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1389 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1390
1391 // Once DTLS has been connected, each side should return the other's SSL
1392 // certificate when calling GetRemoteAudioSSLCertificate.
1393
1394 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1395 ASSERT_TRUE(caller_remote_cert);
1396 EXPECT_EQ(callee_cert->ssl_certificate().ToPEMString(),
1397 caller_remote_cert->ToPEMString());
1398
1399 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1400 ASSERT_TRUE(callee_remote_cert);
1401 EXPECT_EQ(caller_cert->ssl_certificate().ToPEMString(),
1402 callee_remote_cert->ToPEMString());
1403}
1404
deadbeef1dcb1642017-03-29 21:08:16 -07001405// This test sets up a call between two parties (using DTLS) and tests that we
1406// can get a video aspect ratio of 16:9.
1407TEST_F(PeerConnectionIntegrationTest, SendAndReceive16To9AspectRatio) {
1408 ASSERT_TRUE(CreatePeerConnectionWrappers());
1409 ConnectFakeSignaling();
1410
1411 // Add video tracks with 16:9 constraint.
1412 FakeConstraints constraints;
1413 double requested_ratio = 16.0 / 9;
1414 constraints.SetMandatoryMinAspectRatio(requested_ratio);
Steve Anton15324772018-01-16 10:26:49 -08001415 caller()->AddTrack(
1416 caller()->CreateLocalVideoTrackWithConstraints(constraints));
1417 callee()->AddTrack(
1418 callee()->CreateLocalVideoTrackWithConstraints(constraints));
deadbeef1dcb1642017-03-29 21:08:16 -07001419
1420 // Do normal offer/answer and wait for at least one frame to be received in
1421 // each direction.
1422 caller()->CreateAndSetAndSignalOffer();
1423 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1424 callee()->min_video_frames_received_per_track() > 0,
1425 kMaxWaitForFramesMs);
1426
1427 // Check rendered aspect ratio.
1428 EXPECT_EQ(requested_ratio, caller()->local_rendered_aspect_ratio());
1429 EXPECT_EQ(requested_ratio, caller()->rendered_aspect_ratio());
1430 EXPECT_EQ(requested_ratio, callee()->local_rendered_aspect_ratio());
1431 EXPECT_EQ(requested_ratio, callee()->rendered_aspect_ratio());
1432}
1433
1434// This test sets up a call between two parties with a source resolution of
1435// 1280x720 and verifies that a 16:9 aspect ratio is received.
1436TEST_F(PeerConnectionIntegrationTest,
1437 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1438 ASSERT_TRUE(CreatePeerConnectionWrappers());
1439 ConnectFakeSignaling();
1440
1441 // Similar to above test, but uses MandatoryMin[Width/Height] constraint
1442 // instead of aspect ratio constraint.
1443 FakeConstraints constraints;
1444 constraints.SetMandatoryMinWidth(1280);
1445 constraints.SetMandatoryMinHeight(720);
Steve Anton15324772018-01-16 10:26:49 -08001446 caller()->AddTrack(
1447 caller()->CreateLocalVideoTrackWithConstraints(constraints));
1448 callee()->AddTrack(
1449 callee()->CreateLocalVideoTrackWithConstraints(constraints));
deadbeef1dcb1642017-03-29 21:08:16 -07001450
1451 // Do normal offer/answer and wait for at least one frame to be received in
1452 // each direction.
1453 caller()->CreateAndSetAndSignalOffer();
1454 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1455 callee()->min_video_frames_received_per_track() > 0,
1456 kMaxWaitForFramesMs);
1457
1458 // Check rendered aspect ratio.
1459 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1460 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1461 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1462 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1463}
1464
1465// This test sets up an one-way call, with media only from caller to
1466// callee.
1467TEST_F(PeerConnectionIntegrationTest, OneWayMediaCall) {
1468 ASSERT_TRUE(CreatePeerConnectionWrappers());
1469 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001470 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001471 caller()->CreateAndSetAndSignalOffer();
1472 int caller_received_frames = 0;
1473 ExpectNewFramesReceivedWithWait(
1474 caller_received_frames, caller_received_frames,
1475 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1476 kMaxWaitForFramesMs);
1477}
1478
1479// This test sets up a audio call initially, with the callee rejecting video
1480// initially. Then later the callee decides to upgrade to audio/video, and
1481// initiates a new offer/answer exchange.
1482TEST_F(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
1483 ASSERT_TRUE(CreatePeerConnectionWrappers());
1484 ConnectFakeSignaling();
1485 // Initially, offer an audio/video stream from the caller, but refuse to
1486 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001487 caller()->AddAudioVideoTracks();
1488 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001489 PeerConnectionInterface::RTCOfferAnswerOptions options;
1490 options.offer_to_receive_video = 0;
1491 callee()->SetOfferAnswerOptions(options);
1492 // Do offer/answer and make sure audio is still received end-to-end.
1493 caller()->CreateAndSetAndSignalOffer();
1494 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1495 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1496 kDefaultExpectedAudioFrameCount, 0,
1497 kMaxWaitForFramesMs);
1498 // Sanity check that the callee's description has a rejected video section.
1499 ASSERT_NE(nullptr, callee()->pc()->local_description());
1500 const ContentInfo* callee_video_content =
1501 GetFirstVideoContent(callee()->pc()->local_description()->description());
1502 ASSERT_NE(nullptr, callee_video_content);
1503 EXPECT_TRUE(callee_video_content->rejected);
1504 // Now negotiate with video and ensure negotiation succeeds, with video
1505 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001506 callee()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001507 options.offer_to_receive_video = 1;
1508 callee()->SetOfferAnswerOptions(options);
1509 callee()->CreateAndSetAndSignalOffer();
1510 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1511 // Expect additional audio frames to be received after the upgrade.
1512 ExpectNewFramesReceivedWithWait(
1513 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1514 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1515 kMaxWaitForFramesMs);
1516}
1517
deadbeef4389b4d2017-09-07 09:07:36 -07001518// Simpler than the above test; just add an audio track to an established
1519// video-only connection.
1520TEST_F(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
1521 ASSERT_TRUE(CreatePeerConnectionWrappers());
1522 ConnectFakeSignaling();
1523 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08001524 caller()->AddVideoTrack();
1525 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001526 caller()->CreateAndSetAndSignalOffer();
1527 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1528 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08001529 caller()->AddAudioTrack();
1530 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001531 caller()->CreateAndSetAndSignalOffer();
1532 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1533 // Ensure both audio and video frames are received end-to-end.
1534 ExpectNewFramesReceivedWithWait(
1535 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1536 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1537 kMaxWaitForFramesMs);
1538}
1539
deadbeef1dcb1642017-03-29 21:08:16 -07001540// This test sets up a call that's transferred to a new caller with a different
1541// DTLS fingerprint.
1542TEST_F(PeerConnectionIntegrationTest, CallTransferredForCallee) {
1543 ASSERT_TRUE(CreatePeerConnectionWrappers());
1544 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001545 caller()->AddAudioVideoTracks();
1546 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001547 caller()->CreateAndSetAndSignalOffer();
1548 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1549
1550 // Keep the original peer around which will still send packets to the
1551 // receiving client. These SRTP packets will be dropped.
1552 std::unique_ptr<PeerConnectionWrapper> original_peer(
1553 SetCallerPcWrapperAndReturnCurrent(
1554 CreatePeerConnectionWrapperWithAlternateKey()));
1555 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1556 // directly above.
1557 original_peer->pc()->Close();
1558
1559 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001560 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001561 caller()->CreateAndSetAndSignalOffer();
1562 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1563 // Wait for some additional frames to be transmitted end-to-end.
1564 ExpectNewFramesReceivedWithWait(
1565 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1566 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1567 kMaxWaitForFramesMs);
1568}
1569
1570// This test sets up a call that's transferred to a new callee with a different
1571// DTLS fingerprint.
1572TEST_F(PeerConnectionIntegrationTest, CallTransferredForCaller) {
1573 ASSERT_TRUE(CreatePeerConnectionWrappers());
1574 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001575 caller()->AddAudioVideoTracks();
1576 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001577 caller()->CreateAndSetAndSignalOffer();
1578 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1579
1580 // Keep the original peer around which will still send packets to the
1581 // receiving client. These SRTP packets will be dropped.
1582 std::unique_ptr<PeerConnectionWrapper> original_peer(
1583 SetCalleePcWrapperAndReturnCurrent(
1584 CreatePeerConnectionWrapperWithAlternateKey()));
1585 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1586 // directly above.
1587 original_peer->pc()->Close();
1588
1589 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001590 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001591 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1592 caller()->CreateAndSetAndSignalOffer();
1593 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1594 // Wait for some additional frames to be transmitted end-to-end.
1595 ExpectNewFramesReceivedWithWait(
1596 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1597 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1598 kMaxWaitForFramesMs);
1599}
1600
1601// This test sets up a non-bundled call and negotiates bundling at the same
1602// time as starting an ICE restart. When bundling is in effect in the restart,
1603// the DTLS-SRTP context should be successfully reset.
1604TEST_F(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
1605 ASSERT_TRUE(CreatePeerConnectionWrappers());
1606 ConnectFakeSignaling();
1607
Steve Anton15324772018-01-16 10:26:49 -08001608 caller()->AddAudioVideoTracks();
1609 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001610 // Remove the bundle group from the SDP received by the callee.
1611 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1612 desc->RemoveGroupByName("BUNDLE");
1613 });
1614 caller()->CreateAndSetAndSignalOffer();
1615 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1616 ExpectNewFramesReceivedWithWait(
1617 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1618 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1619 kMaxWaitForFramesMs);
1620
1621 // Now stop removing the BUNDLE group, and trigger an ICE restart.
1622 callee()->SetReceivedSdpMunger(nullptr);
1623 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1624 caller()->CreateAndSetAndSignalOffer();
1625 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1626
1627 // Expect additional frames to be received after the ICE restart.
1628 ExpectNewFramesReceivedWithWait(
1629 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1630 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1631 kMaxWaitForFramesMs);
1632}
1633
1634// Test CVO (Coordination of Video Orientation). If a video source is rotated
1635// and both peers support the CVO RTP header extension, the actual video frames
1636// don't need to be encoded in different resolutions, since the rotation is
1637// communicated through the RTP header extension.
1638TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
1639 ASSERT_TRUE(CreatePeerConnectionWrappers());
1640 ConnectFakeSignaling();
1641 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08001642 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001643 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08001644 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001645 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1646
1647 // Wait for video frames to be received by both sides.
1648 caller()->CreateAndSetAndSignalOffer();
1649 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1650 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1651 callee()->min_video_frames_received_per_track() > 0,
1652 kMaxWaitForFramesMs);
1653
1654 // Ensure that the aspect ratio is unmodified.
1655 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1656 // not just assumed.
1657 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
1658 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
1659 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
1660 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
1661 // Ensure that the CVO bits were surfaced to the renderer.
1662 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
1663 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
1664}
1665
1666// Test that when the CVO extension isn't supported, video is rotated the
1667// old-fashioned way, by encoding rotated frames.
1668TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
1669 ASSERT_TRUE(CreatePeerConnectionWrappers());
1670 ConnectFakeSignaling();
1671 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08001672 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001673 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08001674 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07001675 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1676
1677 // Remove the CVO extension from the offered SDP.
1678 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1679 cricket::VideoContentDescription* video =
1680 GetFirstVideoContentDescription(desc);
1681 video->ClearRtpHeaderExtensions();
1682 });
1683 // Wait for video frames to be received by both sides.
1684 caller()->CreateAndSetAndSignalOffer();
1685 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1686 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1687 callee()->min_video_frames_received_per_track() > 0,
1688 kMaxWaitForFramesMs);
1689
1690 // Expect that the aspect ratio is inversed to account for the 90/270 degree
1691 // rotation.
1692 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1693 // not just assumed.
1694 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
1695 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
1696 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
1697 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
1698 // Expect that each endpoint is unaware of the rotation of the other endpoint.
1699 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
1700 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
1701}
1702
1703// TODO(deadbeef): The tests below rely on RTCOfferAnswerOptions to reject an
1704// m= section. When we implement Unified Plan SDP, the right way to do this
1705// would be by stopping an RtpTransceiver.
1706
1707// Test that if the answerer rejects the audio m= section, no audio is sent or
1708// received, but video still can be.
1709TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
1710 ASSERT_TRUE(CreatePeerConnectionWrappers());
1711 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001712 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001713 // Only add video track for callee, and set offer_to_receive_audio to 0, so
1714 // it will reject the audio m= section completely.
1715 PeerConnectionInterface::RTCOfferAnswerOptions options;
1716 options.offer_to_receive_audio = 0;
1717 callee()->SetOfferAnswerOptions(options);
Steve Anton15324772018-01-16 10:26:49 -08001718 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07001719 // Do offer/answer and wait for successful end-to-end video frames.
1720 caller()->CreateAndSetAndSignalOffer();
1721 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1722 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount, 0,
1723 kDefaultExpectedVideoFrameCount,
1724 kMaxWaitForFramesMs);
1725 // Shouldn't have received audio frames at any point.
1726 EXPECT_EQ(0, caller()->audio_frames_received());
1727 EXPECT_EQ(0, callee()->audio_frames_received());
1728 // Sanity check that the callee's description has a rejected audio section.
1729 ASSERT_NE(nullptr, callee()->pc()->local_description());
1730 const ContentInfo* callee_audio_content =
1731 GetFirstAudioContent(callee()->pc()->local_description()->description());
1732 ASSERT_NE(nullptr, callee_audio_content);
1733 EXPECT_TRUE(callee_audio_content->rejected);
1734}
1735
1736// Test that if the answerer rejects the video m= section, no video is sent or
1737// received, but audio still can be.
1738TEST_F(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
1739 ASSERT_TRUE(CreatePeerConnectionWrappers());
1740 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001741 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001742 // Only add audio track for callee, and set offer_to_receive_video to 0, so
1743 // it will reject the video m= section completely.
1744 PeerConnectionInterface::RTCOfferAnswerOptions options;
1745 options.offer_to_receive_video = 0;
1746 callee()->SetOfferAnswerOptions(options);
Steve Anton15324772018-01-16 10:26:49 -08001747 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07001748 // Do offer/answer and wait for successful end-to-end audio frames.
1749 caller()->CreateAndSetAndSignalOffer();
1750 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1751 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1752 kDefaultExpectedAudioFrameCount, 0,
1753 kMaxWaitForFramesMs);
1754 // Shouldn't have received video frames at any point.
1755 EXPECT_EQ(0, caller()->total_video_frames_received());
1756 EXPECT_EQ(0, callee()->total_video_frames_received());
1757 // Sanity check that the callee's description has a rejected video section.
1758 ASSERT_NE(nullptr, callee()->pc()->local_description());
1759 const ContentInfo* callee_video_content =
1760 GetFirstVideoContent(callee()->pc()->local_description()->description());
1761 ASSERT_NE(nullptr, callee_video_content);
1762 EXPECT_TRUE(callee_video_content->rejected);
1763}
1764
1765// Test that if the answerer rejects both audio and video m= sections, nothing
1766// bad happens.
1767// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
1768// test anything but the fact that negotiation succeeds, which doesn't mean
1769// much.
1770TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
1771 ASSERT_TRUE(CreatePeerConnectionWrappers());
1772 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001773 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001774 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
1775 // will reject both audio and video m= sections.
1776 PeerConnectionInterface::RTCOfferAnswerOptions options;
1777 options.offer_to_receive_audio = 0;
1778 options.offer_to_receive_video = 0;
1779 callee()->SetOfferAnswerOptions(options);
1780 // Do offer/answer and wait for stable signaling state.
1781 caller()->CreateAndSetAndSignalOffer();
1782 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1783 // Sanity check that the callee's description has rejected m= sections.
1784 ASSERT_NE(nullptr, callee()->pc()->local_description());
1785 const ContentInfo* callee_audio_content =
1786 GetFirstAudioContent(callee()->pc()->local_description()->description());
1787 ASSERT_NE(nullptr, callee_audio_content);
1788 EXPECT_TRUE(callee_audio_content->rejected);
1789 const ContentInfo* callee_video_content =
1790 GetFirstVideoContent(callee()->pc()->local_description()->description());
1791 ASSERT_NE(nullptr, callee_video_content);
1792 EXPECT_TRUE(callee_video_content->rejected);
1793}
1794
1795// This test sets up an audio and video call between two parties. After the
1796// call runs for a while, the caller sends an updated offer with video being
1797// rejected. Once the re-negotiation is done, the video flow should stop and
1798// the audio flow should continue.
1799TEST_F(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
1800 ASSERT_TRUE(CreatePeerConnectionWrappers());
1801 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001802 caller()->AddAudioVideoTracks();
1803 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001804 caller()->CreateAndSetAndSignalOffer();
1805 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1806 ExpectNewFramesReceivedWithWait(
1807 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1808 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1809 kMaxWaitForFramesMs);
1810
1811 // Renegotiate, rejecting the video m= section.
1812 // TODO(deadbeef): When an RtpTransceiver API is available, use that to
1813 // reject the video m= section.
1814 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
1815 for (cricket::ContentInfo& content : description->contents()) {
1816 if (cricket::IsVideoContent(&content)) {
1817 content.rejected = true;
1818 }
1819 }
1820 });
1821 caller()->CreateAndSetAndSignalOffer();
1822 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
1823
1824 // Sanity check that the caller's description has a rejected video section.
1825 ASSERT_NE(nullptr, caller()->pc()->local_description());
1826 const ContentInfo* caller_video_content =
1827 GetFirstVideoContent(caller()->pc()->local_description()->description());
1828 ASSERT_NE(nullptr, caller_video_content);
1829 EXPECT_TRUE(caller_video_content->rejected);
1830
1831 int caller_video_received = caller()->total_video_frames_received();
1832 int callee_video_received = callee()->total_video_frames_received();
1833
1834 // Wait for some additional audio frames to be received.
1835 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1836 kDefaultExpectedAudioFrameCount, 0,
1837 kMaxWaitForFramesMs);
1838
1839 // During this time, we shouldn't have received any additional video frames
1840 // for the rejected video tracks.
1841 EXPECT_EQ(caller_video_received, caller()->total_video_frames_received());
1842 EXPECT_EQ(callee_video_received, callee()->total_video_frames_received());
1843}
1844
1845// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
1846// is needed to support legacy endpoints.
1847// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
1848// add a test for an end-to-end test without MID signaling either (basically,
1849// the minimum acceptable SDP).
1850TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
1851 ASSERT_TRUE(CreatePeerConnectionWrappers());
1852 ConnectFakeSignaling();
1853 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08001854 caller()->AddAudioVideoTracks();
1855 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07001856 // Remove SSRCs and MSIDs from the received offer SDP.
1857 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07001858 caller()->CreateAndSetAndSignalOffer();
1859 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1860 ExpectNewFramesReceivedWithWait(
1861 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1862 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1863 kMaxWaitForFramesMs);
1864}
1865
1866// Test that if two video tracks are sent (from caller to callee, in this test),
1867// they're transmitted correctly end-to-end.
1868TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
1869 ASSERT_TRUE(CreatePeerConnectionWrappers());
1870 ConnectFakeSignaling();
1871 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08001872 caller()->AddAudioVideoTracks();
1873 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001874 caller()->CreateAndSetAndSignalOffer();
1875 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08001876 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001877 int expected_callee_received_frames = kDefaultExpectedVideoFrameCount;
1878 ExpectNewFramesReceivedWithWait(0, 0, 0, expected_callee_received_frames,
1879 kMaxWaitForFramesMs);
1880}
1881
1882static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
1883 bool first = true;
1884 for (cricket::ContentInfo& content : desc->contents()) {
1885 if (first) {
1886 first = false;
1887 continue;
1888 }
1889 content.bundle_only = true;
1890 }
1891 first = true;
1892 for (cricket::TransportInfo& transport : desc->transport_infos()) {
1893 if (first) {
1894 first = false;
1895 continue;
1896 }
1897 transport.description.ice_ufrag.clear();
1898 transport.description.ice_pwd.clear();
1899 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
1900 transport.description.identity_fingerprint.reset(nullptr);
1901 }
1902}
1903
1904// Test that if applying a true "max bundle" offer, which uses ports of 0,
1905// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
1906// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
1907// successfully and media flows.
1908// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
1909// TODO(deadbeef): Won't need this test once we start generating actual
1910// standards-compliant SDP.
1911TEST_F(PeerConnectionIntegrationTest,
1912 EndToEndCallWithSpecCompliantMaxBundleOffer) {
1913 ASSERT_TRUE(CreatePeerConnectionWrappers());
1914 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001915 caller()->AddAudioVideoTracks();
1916 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001917 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
1918 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
1919 // but the first m= section.
1920 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
1921 caller()->CreateAndSetAndSignalOffer();
1922 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1923 ExpectNewFramesReceivedWithWait(
1924 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1925 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1926 kMaxWaitForFramesMs);
1927}
1928
1929// Test that we can receive the audio output level from a remote audio track.
1930// TODO(deadbeef): Use a fake audio source and verify that the output level is
1931// exactly what the source on the other side was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001932TEST_F(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001933 ASSERT_TRUE(CreatePeerConnectionWrappers());
1934 ConnectFakeSignaling();
1935 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08001936 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001937 caller()->CreateAndSetAndSignalOffer();
1938 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1939
1940 // Get the audio output level stats. Note that the level is not available
1941 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07001942 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001943 kMaxWaitForFramesMs);
1944}
1945
1946// Test that an audio input level is reported.
1947// TODO(deadbeef): Use a fake audio source and verify that the input level is
1948// exactly what the source was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001949TEST_F(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001950 ASSERT_TRUE(CreatePeerConnectionWrappers());
1951 ConnectFakeSignaling();
1952 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08001953 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001954 caller()->CreateAndSetAndSignalOffer();
1955 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1956
1957 // Get the audio input level stats. The level should be available very
1958 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07001959 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001960 kMaxWaitForStatsMs);
1961}
1962
1963// Test that we can get incoming byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001964TEST_F(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001965 ASSERT_TRUE(CreatePeerConnectionWrappers());
1966 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001967 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001968 // Do offer/answer, wait for the callee to receive some frames.
1969 caller()->CreateAndSetAndSignalOffer();
1970 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1971 int expected_caller_received_frames = 0;
1972 ExpectNewFramesReceivedWithWait(
1973 expected_caller_received_frames, expected_caller_received_frames,
1974 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1975 kMaxWaitForFramesMs);
1976
1977 // Get a handle to the remote tracks created, so they can be used as GetStats
1978 // filters.
Steve Anton15324772018-01-16 10:26:49 -08001979 for (auto receiver : callee()->pc()->GetReceivers()) {
1980 // We received frames, so we definitely should have nonzero "received bytes"
1981 // stats at this point.
1982 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
1983 0);
1984 }
deadbeef1dcb1642017-03-29 21:08:16 -07001985}
1986
1987// Test that we can get outgoing byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001988TEST_F(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001989 ASSERT_TRUE(CreatePeerConnectionWrappers());
1990 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001991 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001992 auto audio_track = caller()->CreateLocalAudioTrack();
1993 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08001994 caller()->AddTrack(audio_track);
1995 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07001996 // Do offer/answer, wait for the callee to receive some frames.
1997 caller()->CreateAndSetAndSignalOffer();
1998 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1999 int expected_caller_received_frames = 0;
2000 ExpectNewFramesReceivedWithWait(
2001 expected_caller_received_frames, expected_caller_received_frames,
2002 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2003 kMaxWaitForFramesMs);
2004
2005 // The callee received frames, so we definitely should have nonzero "sent
2006 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002007 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2008 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2009}
2010
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002011// Test that we can get capture start ntp time.
2012TEST_F(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
2013 ASSERT_TRUE(CreatePeerConnectionWrappers());
2014 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002015 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002016
Steve Anton15324772018-01-16 10:26:49 -08002017 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002018
2019 // Do offer/answer, wait for the callee to receive some frames.
2020 caller()->CreateAndSetAndSignalOffer();
2021 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2022
2023 // Get the remote audio track created on the receiver, so they can be used as
2024 // GetStats filters.
2025 StreamCollectionInterface* remote_streams = callee()->remote_streams();
2026 ASSERT_EQ(1u, remote_streams->count());
2027 ASSERT_EQ(1u, remote_streams->at(0)->GetAudioTracks().size());
2028 MediaStreamTrackInterface* remote_audio_track =
2029 remote_streams->at(0)->GetAudioTracks()[0];
2030
2031 // Get the audio output level stats. Note that the level is not available
2032 // until an RTCP packet has been received.
2033 EXPECT_TRUE_WAIT(callee()->OldGetStatsForTrack(remote_audio_track)->
2034 CaptureStartNtpTime() > 0, 2 * kMaxWaitForFramesMs);
2035}
2036
deadbeefd8ad7882017-04-18 16:01:17 -07002037// Test that we can get stats (using the new stats implemnetation) for
2038// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2039// SDP.
2040TEST_F(PeerConnectionIntegrationTest,
2041 GetStatsForUnsignaledStreamWithNewStatsApi) {
2042 ASSERT_TRUE(CreatePeerConnectionWrappers());
2043 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002044 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002045 // Remove SSRCs and MSIDs from the received offer SDP.
2046 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2047 caller()->CreateAndSetAndSignalOffer();
2048 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2049 // Wait for one audio frame to be received by the callee.
2050 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
2051
2052 // We received a frame, so we should have nonzero "bytes received" stats for
2053 // the unsignaled stream, if stats are working for it.
2054 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2055 callee()->NewGetStats();
2056 ASSERT_NE(nullptr, report);
2057 auto inbound_stream_stats =
2058 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2059 ASSERT_EQ(1U, inbound_stream_stats.size());
2060 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2061 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002062 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2063}
2064
2065// Test that we can successfully get the media related stats (audio level
2066// etc.) for the unsignaled stream.
2067TEST_F(PeerConnectionIntegrationTest,
2068 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2069 ASSERT_TRUE(CreatePeerConnectionWrappers());
2070 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002071 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002072 // Remove SSRCs and MSIDs from the received offer SDP.
2073 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2074 caller()->CreateAndSetAndSignalOffer();
2075 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2076 // Wait for one audio frame to be received by the callee.
2077 ExpectNewFramesReceivedWithWait(0, 0, 1, 1, kMaxWaitForFramesMs);
2078
2079 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2080 callee()->NewGetStats();
2081 ASSERT_NE(nullptr, report);
2082
2083 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2084 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2085 ASSERT_GE(audio_index, 0);
2086 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002087}
2088
deadbeef4e2deab2017-09-20 13:56:21 -07002089// Helper for test below.
2090void ModifySsrcs(cricket::SessionDescription* desc) {
2091 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -08002092 for (cricket::StreamParams& stream :
2093 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002094 for (uint32_t& ssrc : stream.ssrcs) {
2095 ssrc = rtc::CreateRandomId();
2096 }
2097 }
2098 }
2099}
2100
2101// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2102// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2103// This should result in two "RTCInboundRTPStreamStats", but only one
2104// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2105// being reset to 0 once the SSRC change occurs.
2106//
2107// Regression test for this bug:
2108// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2109//
2110// The bug causes the track stats to only represent one of the two streams:
2111// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2112// that the track stat counters would reset to 0 when the new stream is
2113// received, and a 50% chance that they'll stop updating (while
2114// "concealed_samples" continues increasing, due to silence being generated for
2115// the inactive stream).
2116TEST_F(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002117 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002118 ASSERT_TRUE(CreatePeerConnectionWrappers());
2119 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002120 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002121 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2122 // that doesn't signal SSRCs (from the callee's perspective).
2123 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2124 caller()->CreateAndSetAndSignalOffer();
2125 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2126 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
2127 ExpectNewFramesReceivedWithWait(0, 0, 25, 0, kMaxWaitForFramesMs);
2128
2129 // Some audio frames were received, so we should have nonzero "samples
2130 // received" for the track.
2131 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2132 callee()->NewGetStats();
2133 ASSERT_NE(nullptr, report);
2134 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2135 ASSERT_EQ(1U, track_stats.size());
2136 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2137 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2138 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2139
2140 // Create a new offer and munge it to cause the caller to use a new SSRC.
2141 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2142 caller()->CreateAndSetAndSignalOffer();
2143 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2144 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2145 // SSRC.
2146 ExpectNewFramesReceivedWithWait(0, 0, 25, 0, kMaxWaitForFramesMs);
2147
2148 report = callee()->NewGetStats();
2149 ASSERT_NE(nullptr, report);
2150 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2151 ASSERT_EQ(1U, track_stats.size());
2152 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2153 // The "total samples received" stat should only be greater than it was
2154 // before.
2155 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2156 // Right now, the new SSRC will cause the counters to reset to 0.
2157 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2158
2159 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002160 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002161 // good sign that we're seeing stats from the old stream that's no longer
2162 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002163 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002164 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2165 EXPECT_LT(*track_stats[0]->concealed_samples,
2166 *track_stats[0]->total_samples_received *
2167 kAcceptableConcealedSamplesPercentage);
2168
2169 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2170 // sanity check that the SSRC really changed.
2171 // TODO(deadbeef): This isn't working right now, because we're not returning
2172 // *any* stats for the inactive stream. Uncomment when the bug is completely
2173 // fixed.
2174 // auto inbound_stream_stats =
2175 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2176 // ASSERT_EQ(2U, inbound_stream_stats.size());
2177}
2178
deadbeef1dcb1642017-03-29 21:08:16 -07002179// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
2180TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
2181 PeerConnectionFactory::Options dtls_10_options;
2182 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2183 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2184 dtls_10_options));
2185 ConnectFakeSignaling();
2186 // Do normal offer/answer and wait for some frames to be received in each
2187 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002188 caller()->AddAudioVideoTracks();
2189 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002190 caller()->CreateAndSetAndSignalOffer();
2191 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2192 ExpectNewFramesReceivedWithWait(
2193 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2194 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2195 kMaxWaitForFramesMs);
2196}
2197
2198// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
2199TEST_F(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
2200 PeerConnectionFactory::Options dtls_10_options;
2201 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2202 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2203 dtls_10_options));
2204 ConnectFakeSignaling();
2205 // Register UMA observer before signaling begins.
2206 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
2207 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2208 caller()->pc()->RegisterUMAObserver(caller_observer);
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 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002214 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002215 kDefaultTimeout);
2216 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002217 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002218 EXPECT_EQ(1,
2219 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2220 kDefaultSrtpCryptoSuite));
2221}
2222
2223// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
2224TEST_F(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
2225 PeerConnectionFactory::Options dtls_12_options;
2226 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2227 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2228 dtls_12_options));
2229 ConnectFakeSignaling();
2230 // Register UMA observer before signaling begins.
2231 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
2232 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
2233 caller()->pc()->RegisterUMAObserver(caller_observer);
Steve Anton15324772018-01-16 10:26:49 -08002234 caller()->AddAudioVideoTracks();
2235 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002236 caller()->CreateAndSetAndSignalOffer();
2237 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2238 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002239 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002240 kDefaultTimeout);
2241 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002242 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002243 EXPECT_EQ(1,
2244 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
2245 kDefaultSrtpCryptoSuite));
2246}
2247
2248// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2249// callee only supports 1.0.
2250TEST_F(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
2251 PeerConnectionFactory::Options caller_options;
2252 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2253 PeerConnectionFactory::Options callee_options;
2254 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2255 ASSERT_TRUE(
2256 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2257 ConnectFakeSignaling();
2258 // Do normal offer/answer and wait for some frames to be received in each
2259 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002260 caller()->AddAudioVideoTracks();
2261 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002262 caller()->CreateAndSetAndSignalOffer();
2263 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2264 ExpectNewFramesReceivedWithWait(
2265 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2266 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2267 kMaxWaitForFramesMs);
2268}
2269
2270// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2271// callee supports 1.2.
2272TEST_F(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
2273 PeerConnectionFactory::Options caller_options;
2274 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2275 PeerConnectionFactory::Options callee_options;
2276 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2277 ASSERT_TRUE(
2278 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2279 ConnectFakeSignaling();
2280 // Do normal offer/answer and wait for some frames to be received in each
2281 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002282 caller()->AddAudioVideoTracks();
2283 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002284 caller()->CreateAndSetAndSignalOffer();
2285 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2286 ExpectNewFramesReceivedWithWait(
2287 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2288 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2289 kMaxWaitForFramesMs);
2290}
2291
2292// Test that a non-GCM cipher is used if both sides only support non-GCM.
2293TEST_F(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
2294 bool local_gcm_enabled = false;
2295 bool remote_gcm_enabled = false;
2296 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2297 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2298 expected_cipher_suite);
2299}
2300
2301// Test that a GCM cipher is used if both ends support it.
2302TEST_F(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
2303 bool local_gcm_enabled = true;
2304 bool remote_gcm_enabled = true;
2305 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2306 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2307 expected_cipher_suite);
2308}
2309
2310// Test that GCM isn't used if only the offerer supports it.
2311TEST_F(PeerConnectionIntegrationTest,
2312 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2313 bool local_gcm_enabled = true;
2314 bool remote_gcm_enabled = false;
2315 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2316 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2317 expected_cipher_suite);
2318}
2319
2320// Test that GCM isn't used if only the answerer supports it.
2321TEST_F(PeerConnectionIntegrationTest,
2322 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2323 bool local_gcm_enabled = false;
2324 bool remote_gcm_enabled = true;
2325 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2326 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2327 expected_cipher_suite);
2328}
2329
deadbeef7914b8c2017-04-21 03:23:33 -07002330// Verify that media can be transmitted end-to-end when GCM crypto suites are
2331// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
2332// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
2333// works with it.
2334TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
2335 PeerConnectionFactory::Options gcm_options;
2336 gcm_options.crypto_options.enable_gcm_crypto_suites = true;
2337 ASSERT_TRUE(
2338 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
2339 ConnectFakeSignaling();
2340 // Do normal offer/answer and wait for some frames to be received in each
2341 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002342 caller()->AddAudioVideoTracks();
2343 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002344 caller()->CreateAndSetAndSignalOffer();
2345 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2346 ExpectNewFramesReceivedWithWait(
2347 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2348 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2349 kMaxWaitForFramesMs);
2350}
2351
deadbeef1dcb1642017-03-29 21:08:16 -07002352// This test sets up a call between two parties with audio, video and an RTP
2353// data channel.
2354TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
2355 FakeConstraints setup_constraints;
2356 setup_constraints.SetAllowRtpDataChannels();
2357 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2358 &setup_constraints));
2359 ConnectFakeSignaling();
2360 // Expect that data channel created on caller side will show up for callee as
2361 // well.
2362 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002363 caller()->AddAudioVideoTracks();
2364 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002365 caller()->CreateAndSetAndSignalOffer();
2366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2367 // Ensure the existence of the RTP data channel didn't impede audio/video.
2368 ExpectNewFramesReceivedWithWait(
2369 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2370 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2371 kMaxWaitForFramesMs);
2372 ASSERT_NE(nullptr, caller()->data_channel());
2373 ASSERT_NE(nullptr, callee()->data_channel());
2374 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2375 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2376
2377 // Ensure data can be sent in both directions.
2378 std::string data = "hello world";
2379 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2380 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2381 kDefaultTimeout);
2382 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2383 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2384 kDefaultTimeout);
2385}
2386
2387// Ensure that an RTP data channel is signaled as closed for the caller when
2388// the callee rejects it in a subsequent offer.
2389TEST_F(PeerConnectionIntegrationTest,
2390 RtpDataChannelSignaledClosedInCalleeOffer) {
2391 // Same procedure as above test.
2392 FakeConstraints setup_constraints;
2393 setup_constraints.SetAllowRtpDataChannels();
2394 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2395 &setup_constraints));
2396 ConnectFakeSignaling();
2397 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002398 caller()->AddAudioVideoTracks();
2399 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002400 caller()->CreateAndSetAndSignalOffer();
2401 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2402 ASSERT_NE(nullptr, caller()->data_channel());
2403 ASSERT_NE(nullptr, callee()->data_channel());
2404 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2405 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2406
2407 // Close the data channel on the callee, and do an updated offer/answer.
2408 callee()->data_channel()->Close();
2409 callee()->CreateAndSetAndSignalOffer();
2410 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2411 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2412 EXPECT_FALSE(callee()->data_observer()->IsOpen());
2413}
2414
2415// Tests that data is buffered in an RTP data channel until an observer is
2416// registered for it.
2417//
2418// NOTE: RTP data channels can receive data before the underlying
2419// transport has detected that a channel is writable and thus data can be
2420// received before the data channel state changes to open. That is hard to test
2421// but the same buffering is expected to be used in that case.
2422TEST_F(PeerConnectionIntegrationTest,
2423 DataBufferedUntilRtpDataChannelObserverRegistered) {
2424 // Use fake clock and simulated network delay so that we predictably can wait
2425 // until an SCTP message has been delivered without "sleep()"ing.
2426 rtc::ScopedFakeClock fake_clock;
2427 // Some things use a time of "0" as a special value, so we need to start out
2428 // the fake clock at a nonzero time.
2429 // TODO(deadbeef): Fix this.
2430 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2431 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
2432 virtual_socket_server()->UpdateDelayDistribution();
2433
2434 FakeConstraints constraints;
2435 constraints.SetAllowRtpDataChannels();
2436 ASSERT_TRUE(
2437 CreatePeerConnectionWrappersWithConstraints(&constraints, &constraints));
2438 ConnectFakeSignaling();
2439 caller()->CreateDataChannel();
2440 caller()->CreateAndSetAndSignalOffer();
2441 ASSERT_TRUE(caller()->data_channel() != nullptr);
2442 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
2443 kDefaultTimeout, fake_clock);
2444 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
2445 kDefaultTimeout, fake_clock);
2446 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
2447 callee()->data_channel()->state(), kDefaultTimeout,
2448 fake_clock);
2449
2450 // Unregister the observer which is normally automatically registered.
2451 callee()->data_channel()->UnregisterObserver();
2452 // Send data and advance fake clock until it should have been received.
2453 std::string data = "hello world";
2454 caller()->data_channel()->Send(DataBuffer(data));
2455 SIMULATED_WAIT(false, 50, fake_clock);
2456
2457 // Attach data channel and expect data to be received immediately. Note that
2458 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
2459 // further, but data can be received even if the callback is asynchronous.
2460 MockDataChannelObserver new_observer(callee()->data_channel());
2461 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
2462 fake_clock);
2463}
2464
2465// This test sets up a call between two parties with audio, video and but only
2466// the caller client supports RTP data channels.
2467TEST_F(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
2468 FakeConstraints setup_constraints_1;
2469 setup_constraints_1.SetAllowRtpDataChannels();
2470 // Must disable DTLS to make negotiation succeed.
2471 setup_constraints_1.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2472 false);
2473 FakeConstraints setup_constraints_2;
2474 setup_constraints_2.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2475 false);
2476 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(
2477 &setup_constraints_1, &setup_constraints_2));
2478 ConnectFakeSignaling();
2479 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002480 caller()->AddAudioVideoTracks();
2481 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002482 caller()->CreateAndSetAndSignalOffer();
2483 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2484 // The caller should still have a data channel, but it should be closed, and
2485 // one should ever have been created for the callee.
2486 EXPECT_TRUE(caller()->data_channel() != nullptr);
2487 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2488 EXPECT_EQ(nullptr, callee()->data_channel());
2489}
2490
2491// This test sets up a call between two parties with audio, and video. When
2492// audio and video is setup and flowing, an RTP data channel is negotiated.
2493TEST_F(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
2494 FakeConstraints setup_constraints;
2495 setup_constraints.SetAllowRtpDataChannels();
2496 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2497 &setup_constraints));
2498 ConnectFakeSignaling();
2499 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08002500 caller()->AddAudioVideoTracks();
2501 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002502 caller()->CreateAndSetAndSignalOffer();
2503 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2504 // Create data channel and do new offer and answer.
2505 caller()->CreateDataChannel();
2506 caller()->CreateAndSetAndSignalOffer();
2507 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2508 ASSERT_NE(nullptr, caller()->data_channel());
2509 ASSERT_NE(nullptr, callee()->data_channel());
2510 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2511 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2512 // Ensure data can be sent in both directions.
2513 std::string data = "hello world";
2514 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2515 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2516 kDefaultTimeout);
2517 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2518 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2519 kDefaultTimeout);
2520}
2521
2522#ifdef HAVE_SCTP
2523
2524// This test sets up a call between two parties with audio, video and an SCTP
2525// data channel.
2526TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
2527 ASSERT_TRUE(CreatePeerConnectionWrappers());
2528 ConnectFakeSignaling();
2529 // Expect that data channel created on caller side will show up for callee as
2530 // well.
2531 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002532 caller()->AddAudioVideoTracks();
2533 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002534 caller()->CreateAndSetAndSignalOffer();
2535 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2536 // Ensure the existence of the SCTP data channel didn't impede audio/video.
2537 ExpectNewFramesReceivedWithWait(
2538 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2539 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2540 kMaxWaitForFramesMs);
2541 // Caller data channel should already exist (it created one). Callee data
2542 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2543 ASSERT_NE(nullptr, caller()->data_channel());
2544 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2545 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2546 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2547
2548 // Ensure data can be sent in both directions.
2549 std::string data = "hello world";
2550 caller()->data_channel()->Send(DataBuffer(data));
2551 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2552 kDefaultTimeout);
2553 callee()->data_channel()->Send(DataBuffer(data));
2554 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2555 kDefaultTimeout);
2556}
2557
2558// Ensure that when the callee closes an SCTP data channel, the closing
2559// procedure results in the data channel being closed for the caller as well.
2560TEST_F(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
2561 // Same procedure as above test.
2562 ASSERT_TRUE(CreatePeerConnectionWrappers());
2563 ConnectFakeSignaling();
2564 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08002565 caller()->AddAudioVideoTracks();
2566 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002567 caller()->CreateAndSetAndSignalOffer();
2568 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2569 ASSERT_NE(nullptr, caller()->data_channel());
2570 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2571 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2572 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2573
2574 // Close the data channel on the callee side, and wait for it to reach the
2575 // "closed" state on both sides.
2576 callee()->data_channel()->Close();
2577 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
2578 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
2579}
2580
Steve Antonda6c0952017-10-23 11:41:54 -07002581TEST_F(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
2582 ASSERT_TRUE(CreatePeerConnectionWrappers());
2583 ConnectFakeSignaling();
2584 webrtc::DataChannelInit init;
2585 init.id = 53;
2586 init.maxRetransmits = 52;
2587 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08002588 caller()->AddAudioVideoTracks();
2589 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07002590 caller()->CreateAndSetAndSignalOffer();
2591 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07002592 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2593 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07002594 EXPECT_EQ(init.id, callee()->data_channel()->id());
2595 EXPECT_EQ("data-channel", callee()->data_channel()->label());
2596 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
2597 EXPECT_FALSE(callee()->data_channel()->negotiated());
2598}
2599
deadbeef1dcb1642017-03-29 21:08:16 -07002600// Test usrsctp's ability to process unordered data stream, where data actually
2601// arrives out of order using simulated delays. Previously there have been some
2602// bugs in this area.
2603TEST_F(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
2604 // Introduce random network delays.
2605 // Otherwise it's not a true "unordered" test.
2606 virtual_socket_server()->set_delay_mean(20);
2607 virtual_socket_server()->set_delay_stddev(5);
2608 virtual_socket_server()->UpdateDelayDistribution();
2609 // Normal procedure, but with unordered data channel config.
2610 ASSERT_TRUE(CreatePeerConnectionWrappers());
2611 ConnectFakeSignaling();
2612 webrtc::DataChannelInit init;
2613 init.ordered = false;
2614 caller()->CreateDataChannel(&init);
2615 caller()->CreateAndSetAndSignalOffer();
2616 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2617 ASSERT_NE(nullptr, caller()->data_channel());
2618 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2619 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2620 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2621
2622 static constexpr int kNumMessages = 100;
2623 // Deliberately chosen to be larger than the MTU so messages get fragmented.
2624 static constexpr size_t kMaxMessageSize = 4096;
2625 // Create and send random messages.
2626 std::vector<std::string> sent_messages;
2627 for (int i = 0; i < kNumMessages; ++i) {
2628 size_t length =
2629 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
2630 std::string message;
2631 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
2632 caller()->data_channel()->Send(DataBuffer(message));
2633 callee()->data_channel()->Send(DataBuffer(message));
2634 sent_messages.push_back(message);
2635 }
2636
2637 // Wait for all messages to be received.
2638 EXPECT_EQ_WAIT(kNumMessages,
2639 caller()->data_observer()->received_message_count(),
2640 kDefaultTimeout);
2641 EXPECT_EQ_WAIT(kNumMessages,
2642 callee()->data_observer()->received_message_count(),
2643 kDefaultTimeout);
2644
2645 // Sort and compare to make sure none of the messages were corrupted.
2646 std::vector<std::string> caller_received_messages =
2647 caller()->data_observer()->messages();
2648 std::vector<std::string> callee_received_messages =
2649 callee()->data_observer()->messages();
2650 std::sort(sent_messages.begin(), sent_messages.end());
2651 std::sort(caller_received_messages.begin(), caller_received_messages.end());
2652 std::sort(callee_received_messages.begin(), callee_received_messages.end());
2653 EXPECT_EQ(sent_messages, caller_received_messages);
2654 EXPECT_EQ(sent_messages, callee_received_messages);
2655}
2656
2657// This test sets up a call between two parties with audio, and video. When
2658// audio and video are setup and flowing, an SCTP data channel is negotiated.
2659TEST_F(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
2660 ASSERT_TRUE(CreatePeerConnectionWrappers());
2661 ConnectFakeSignaling();
2662 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08002663 caller()->AddAudioVideoTracks();
2664 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002665 caller()->CreateAndSetAndSignalOffer();
2666 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2667 // Create data channel and do new offer and answer.
2668 caller()->CreateDataChannel();
2669 caller()->CreateAndSetAndSignalOffer();
2670 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2671 // Caller data channel should already exist (it created one). Callee data
2672 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2673 ASSERT_NE(nullptr, caller()->data_channel());
2674 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2675 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2676 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2677 // Ensure data can be sent in both directions.
2678 std::string data = "hello world";
2679 caller()->data_channel()->Send(DataBuffer(data));
2680 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2681 kDefaultTimeout);
2682 callee()->data_channel()->Send(DataBuffer(data));
2683 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2684 kDefaultTimeout);
2685}
2686
deadbeef7914b8c2017-04-21 03:23:33 -07002687// Set up a connection initially just using SCTP data channels, later upgrading
2688// to audio/video, ensuring frames are received end-to-end. Effectively the
2689// inverse of the test above.
2690// This was broken in M57; see https://crbug.com/711243
2691TEST_F(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
2692 ASSERT_TRUE(CreatePeerConnectionWrappers());
2693 ConnectFakeSignaling();
2694 // Do initial offer/answer with just data channel.
2695 caller()->CreateDataChannel();
2696 caller()->CreateAndSetAndSignalOffer();
2697 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2698 // Wait until data can be sent over the data channel.
2699 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2700 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2701 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2702
2703 // Do subsequent offer/answer with two-way audio and video. Audio and video
2704 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08002705 caller()->AddAudioVideoTracks();
2706 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07002707 caller()->CreateAndSetAndSignalOffer();
2708 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2709 ExpectNewFramesReceivedWithWait(
2710 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2711 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2712 kMaxWaitForFramesMs);
2713}
2714
deadbeef8b7e9ad2017-05-25 09:38:55 -07002715static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07002716 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08002717 GetFirstDataContentDescription(desc);
2718 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07002719 dcd_offer->set_use_sctpmap(false);
2720 dcd_offer->set_protocol("UDP/DTLS/SCTP");
2721}
2722
2723// Test that the data channel works when a spec-compliant SCTP m= section is
2724// offered (using "a=sctp-port" instead of "a=sctpmap", and using
2725// "UDP/DTLS/SCTP" as the protocol).
2726TEST_F(PeerConnectionIntegrationTest,
2727 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
2728 ASSERT_TRUE(CreatePeerConnectionWrappers());
2729 ConnectFakeSignaling();
2730 caller()->CreateDataChannel();
2731 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
2732 caller()->CreateAndSetAndSignalOffer();
2733 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2734 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2735 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2736 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2737
2738 // Ensure data can be sent in both directions.
2739 std::string data = "hello world";
2740 caller()->data_channel()->Send(DataBuffer(data));
2741 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2742 kDefaultTimeout);
2743 callee()->data_channel()->Send(DataBuffer(data));
2744 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2745 kDefaultTimeout);
2746}
2747
deadbeef1dcb1642017-03-29 21:08:16 -07002748#endif // HAVE_SCTP
2749
2750// Test that the ICE connection and gathering states eventually reach
2751// "complete".
2752TEST_F(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
2753 ASSERT_TRUE(CreatePeerConnectionWrappers());
2754 ConnectFakeSignaling();
2755 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002756 caller()->AddAudioVideoTracks();
2757 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002758 caller()->CreateAndSetAndSignalOffer();
2759 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2760 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2761 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
2762 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2763 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
2764 // After the best candidate pair is selected and all candidates are signaled,
2765 // the ICE connection state should reach "complete".
2766 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
2767 // answerer/"callee" by default) only reaches "connected". When this is
2768 // fixed, this test should be updated.
2769 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2770 caller()->ice_connection_state(), kDefaultTimeout);
2771 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2772 callee()->ice_connection_state(), kDefaultTimeout);
2773}
2774
Steve Antonede9ca52017-10-16 13:04:27 -07002775// Test that firewalling the ICE connection causes the clients to identify the
2776// disconnected state and then removing the firewall causes them to reconnect.
2777class PeerConnectionIntegrationIceStatesTest
2778 : public PeerConnectionIntegrationTest,
2779 public ::testing::WithParamInterface<std::tuple<std::string, uint32_t>> {
2780 protected:
2781 PeerConnectionIntegrationIceStatesTest() {
2782 port_allocator_flags_ = std::get<1>(GetParam());
2783 }
2784
2785 void StartStunServer(const SocketAddress& server_address) {
2786 stun_server_.reset(
2787 cricket::TestStunServer::Create(network_thread(), server_address));
2788 }
2789
2790 bool TestIPv6() {
2791 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
2792 }
2793
2794 void SetPortAllocatorFlags() {
2795 caller()->port_allocator()->set_flags(port_allocator_flags_);
2796 callee()->port_allocator()->set_flags(port_allocator_flags_);
2797 }
2798
2799 std::vector<SocketAddress> CallerAddresses() {
2800 std::vector<SocketAddress> addresses;
2801 addresses.push_back(SocketAddress("1.1.1.1", 0));
2802 if (TestIPv6()) {
2803 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
2804 }
2805 return addresses;
2806 }
2807
2808 std::vector<SocketAddress> CalleeAddresses() {
2809 std::vector<SocketAddress> addresses;
2810 addresses.push_back(SocketAddress("2.2.2.2", 0));
2811 if (TestIPv6()) {
2812 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
2813 }
2814 return addresses;
2815 }
2816
2817 void SetUpNetworkInterfaces() {
2818 // Remove the default interfaces added by the test infrastructure.
2819 caller()->network()->RemoveInterface(kDefaultLocalAddress);
2820 callee()->network()->RemoveInterface(kDefaultLocalAddress);
2821
2822 // Add network addresses for test.
2823 for (const auto& caller_address : CallerAddresses()) {
2824 caller()->network()->AddInterface(caller_address);
2825 }
2826 for (const auto& callee_address : CalleeAddresses()) {
2827 callee()->network()->AddInterface(callee_address);
2828 }
2829 }
2830
2831 private:
2832 uint32_t port_allocator_flags_;
2833 std::unique_ptr<cricket::TestStunServer> stun_server_;
2834};
2835
2836// Tests that the PeerConnection goes through all the ICE gathering/connection
2837// states over the duration of the call. This includes Disconnected and Failed
2838// states, induced by putting a firewall between the peers and waiting for them
2839// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08002840TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
2841 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
2842 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
2843 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07002844
2845 const SocketAddress kStunServerAddress =
2846 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
2847 StartStunServer(kStunServerAddress);
2848
2849 PeerConnectionInterface::RTCConfiguration config;
2850 PeerConnectionInterface::IceServer ice_stun_server;
2851 ice_stun_server.urls.push_back(
2852 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
2853 kStunServerAddress.PortAsString());
2854 config.servers.push_back(ice_stun_server);
2855
2856 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
2857 ConnectFakeSignaling();
2858 SetPortAllocatorFlags();
2859 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08002860 caller()->AddAudioVideoTracks();
2861 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07002862
2863 // Initial state before anything happens.
2864 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
2865 caller()->ice_gathering_state());
2866 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
2867 caller()->ice_connection_state());
2868
2869 // Start the call by creating the offer, setting it as the local description,
2870 // then sending it to the peer who will respond with an answer. This happens
2871 // asynchronously so that we can watch the states as it runs in the
2872 // background.
2873 caller()->CreateAndSetAndSignalOffer();
2874
Steve Anton83119dd2017-11-10 16:19:52 -08002875 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
2876 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002877
2878 // Verify that the observer was notified of the intermediate transitions.
2879 EXPECT_THAT(caller()->ice_connection_state_history(),
2880 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
2881 PeerConnectionInterface::kIceConnectionConnected,
2882 PeerConnectionInterface::kIceConnectionCompleted));
2883 EXPECT_THAT(caller()->ice_gathering_state_history(),
2884 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
2885 PeerConnectionInterface::kIceGatheringComplete));
2886
2887 // Block connections to/from the caller and wait for ICE to become
2888 // disconnected.
2889 for (const auto& caller_address : CallerAddresses()) {
2890 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
2891 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002892 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08002893 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
2894 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002895
2896 // Let ICE re-establish by removing the firewall rules.
2897 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01002898 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08002899 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
2900 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002901
2902 // According to RFC7675, if there is no response within 30 seconds then the
2903 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08002904 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07002905 constexpr int kConsentTimeout = 30000;
2906 for (const auto& caller_address : CallerAddresses()) {
2907 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
2908 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002909 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08002910 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
2911 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07002912}
2913
2914// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
2915// and that the statistics in the metric observers are updated correctly.
2916TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
2917 ASSERT_TRUE(CreatePeerConnectionWrappers());
2918 ConnectFakeSignaling();
2919 SetPortAllocatorFlags();
2920 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08002921 caller()->AddAudioVideoTracks();
2922 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07002923
2924 rtc::scoped_refptr<webrtc::FakeMetricsObserver> metrics_observer(
2925 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>());
2926 caller()->pc()->RegisterUMAObserver(metrics_observer.get());
2927
2928 caller()->CreateAndSetAndSignalOffer();
2929
2930 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2931
2932 const int num_best_ipv4 = metrics_observer->GetEnumCounter(
2933 webrtc::kEnumCounterAddressFamily, webrtc::kBestConnections_IPv4);
2934 const int num_best_ipv6 = metrics_observer->GetEnumCounter(
2935 webrtc::kEnumCounterAddressFamily, webrtc::kBestConnections_IPv6);
2936 if (TestIPv6()) {
2937 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
2938 // connection.
2939 EXPECT_EQ(0u, num_best_ipv4);
2940 EXPECT_EQ(1u, num_best_ipv6);
2941 } else {
2942 EXPECT_EQ(1u, num_best_ipv4);
2943 EXPECT_EQ(0u, num_best_ipv6);
2944 }
2945
2946 EXPECT_EQ(0u, metrics_observer->GetEnumCounter(
2947 webrtc::kEnumCounterIceCandidatePairTypeUdp,
2948 webrtc::kIceCandidatePairHostHost));
2949 EXPECT_EQ(1u, metrics_observer->GetEnumCounter(
2950 webrtc::kEnumCounterIceCandidatePairTypeUdp,
2951 webrtc::kIceCandidatePairHostPublicHostPublic));
2952}
2953
2954constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
2955 cricket::PORTALLOCATOR_DISABLE_STUN |
2956 cricket::PORTALLOCATOR_DISABLE_RELAY;
2957constexpr uint32_t kFlagsIPv6NoStun =
2958 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
2959 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
2960constexpr uint32_t kFlagsIPv4Stun =
2961 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
2962
2963INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
2964 PeerConnectionIntegrationIceStatesTest,
2965 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
2966 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
2967 std::make_pair("IPv4 with STUN",
2968 kFlagsIPv4Stun)));
2969
deadbeef1dcb1642017-03-29 21:08:16 -07002970// This test sets up a call between two parties with audio and video.
2971// During the call, the caller restarts ICE and the test verifies that
2972// new ICE candidates are generated and audio and video still can flow, and the
2973// ICE state reaches completed again.
2974TEST_F(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
2975 ASSERT_TRUE(CreatePeerConnectionWrappers());
2976 ConnectFakeSignaling();
2977 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08002978 caller()->AddAudioVideoTracks();
2979 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002980 caller()->CreateAndSetAndSignalOffer();
2981 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2982 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2983 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2984 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2985 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2986
2987 // To verify that the ICE restart actually occurs, get
2988 // ufrag/password/candidates before and after restart.
2989 // Create an SDP string of the first audio candidate for both clients.
2990 const webrtc::IceCandidateCollection* audio_candidates_caller =
2991 caller()->pc()->local_description()->candidates(0);
2992 const webrtc::IceCandidateCollection* audio_candidates_callee =
2993 callee()->pc()->local_description()->candidates(0);
2994 ASSERT_GT(audio_candidates_caller->count(), 0u);
2995 ASSERT_GT(audio_candidates_callee->count(), 0u);
2996 std::string caller_candidate_pre_restart;
2997 ASSERT_TRUE(
2998 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
2999 std::string callee_candidate_pre_restart;
3000 ASSERT_TRUE(
3001 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
3002 const cricket::SessionDescription* desc =
3003 caller()->pc()->local_description()->description();
3004 std::string caller_ufrag_pre_restart =
3005 desc->transport_infos()[0].description.ice_ufrag;
3006 desc = callee()->pc()->local_description()->description();
3007 std::string callee_ufrag_pre_restart =
3008 desc->transport_infos()[0].description.ice_ufrag;
3009
3010 // Have the caller initiate an ICE restart.
3011 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
3012 caller()->CreateAndSetAndSignalOffer();
3013 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3014 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3015 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3016 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3017 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3018
3019 // Grab the ufrags/candidates again.
3020 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
3021 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
3022 ASSERT_GT(audio_candidates_caller->count(), 0u);
3023 ASSERT_GT(audio_candidates_callee->count(), 0u);
3024 std::string caller_candidate_post_restart;
3025 ASSERT_TRUE(
3026 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
3027 std::string callee_candidate_post_restart;
3028 ASSERT_TRUE(
3029 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
3030 desc = caller()->pc()->local_description()->description();
3031 std::string caller_ufrag_post_restart =
3032 desc->transport_infos()[0].description.ice_ufrag;
3033 desc = callee()->pc()->local_description()->description();
3034 std::string callee_ufrag_post_restart =
3035 desc->transport_infos()[0].description.ice_ufrag;
3036 // Sanity check that an ICE restart was actually negotiated in SDP.
3037 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
3038 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
3039 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
3040 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
3041
3042 // Ensure that additional frames are received after the ICE restart.
3043 ExpectNewFramesReceivedWithWait(
3044 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3045 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3046 kMaxWaitForFramesMs);
3047}
3048
3049// Verify that audio/video can be received end-to-end when ICE renomination is
3050// enabled.
3051TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
3052 PeerConnectionInterface::RTCConfiguration config;
3053 config.enable_ice_renomination = true;
3054 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3055 ConnectFakeSignaling();
3056 // Do normal offer/answer and wait for some frames to be received in each
3057 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003058 caller()->AddAudioVideoTracks();
3059 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003060 caller()->CreateAndSetAndSignalOffer();
3061 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3062 // Sanity check that ICE renomination was actually negotiated.
3063 const cricket::SessionDescription* desc =
3064 caller()->pc()->local_description()->description();
3065 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003066 ASSERT_NE(
3067 info.description.transport_options.end(),
3068 std::find(info.description.transport_options.begin(),
3069 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003070 }
3071 desc = callee()->pc()->local_description()->description();
3072 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003073 ASSERT_NE(
3074 info.description.transport_options.end(),
3075 std::find(info.description.transport_options.begin(),
3076 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003077 }
3078 ExpectNewFramesReceivedWithWait(
3079 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3080 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3081 kMaxWaitForFramesMs);
3082}
3083
Steve Anton6f25b092017-10-23 09:39:20 -07003084// With a max bundle policy and RTCP muxing, adding a new media description to
3085// the connection should not affect ICE at all because the new media will use
3086// the existing connection.
3087TEST_F(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003088 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07003089 PeerConnectionInterface::RTCConfiguration config;
3090 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3091 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3092 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
3093 config, PeerConnectionInterface::RTCConfiguration()));
3094 ConnectFakeSignaling();
3095
Steve Anton15324772018-01-16 10:26:49 -08003096 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003097 caller()->CreateAndSetAndSignalOffer();
3098 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07003099 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3100 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07003101
3102 caller()->clear_ice_connection_state_history();
3103
Steve Anton15324772018-01-16 10:26:49 -08003104 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07003105 caller()->CreateAndSetAndSignalOffer();
3106 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3107
3108 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
3109}
3110
deadbeef1dcb1642017-03-29 21:08:16 -07003111// This test sets up a call between two parties with audio and video. It then
3112// renegotiates setting the video m-line to "port 0", then later renegotiates
3113// again, enabling video.
3114TEST_F(PeerConnectionIntegrationTest,
3115 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
3116 ASSERT_TRUE(CreatePeerConnectionWrappers());
3117 ConnectFakeSignaling();
3118
3119 // Do initial negotiation, only sending media from the caller. Will result in
3120 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08003121 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003122 caller()->CreateAndSetAndSignalOffer();
3123 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3124
3125 // Negotiate again, disabling the video "m=" section (the callee will set the
3126 // port to 0 due to offer_to_receive_video = 0).
3127 PeerConnectionInterface::RTCOfferAnswerOptions options;
3128 options.offer_to_receive_video = 0;
3129 callee()->SetOfferAnswerOptions(options);
3130 caller()->CreateAndSetAndSignalOffer();
3131 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3132 // Sanity check that video "m=" section was actually rejected.
3133 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
3134 callee()->pc()->local_description()->description());
3135 ASSERT_NE(nullptr, answer_video_content);
3136 ASSERT_TRUE(answer_video_content->rejected);
3137
3138 // Enable video and do negotiation again, making sure video is received
3139 // end-to-end, also adding media stream to callee.
3140 options.offer_to_receive_video = 1;
3141 callee()->SetOfferAnswerOptions(options);
Steve Anton15324772018-01-16 10:26:49 -08003142 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003143 caller()->CreateAndSetAndSignalOffer();
3144 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3145 // Verify the caller receives frames from the newly added stream, and the
3146 // callee receives additional frames from the re-enabled video m= section.
3147 ExpectNewFramesReceivedWithWait(
3148 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3149 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3150 kMaxWaitForFramesMs);
3151}
3152
3153// This test sets up a Jsep call between two parties with external
3154// VideoDecoderFactory.
3155// TODO(holmer): Disabled due to sometimes crashing on buildbots.
3156// See issue webrtc/2378.
3157TEST_F(PeerConnectionIntegrationTest,
3158 DISABLED_EndToEndCallWithVideoDecoderFactory) {
3159 ASSERT_TRUE(CreatePeerConnectionWrappers());
3160 EnableVideoDecoderFactory();
3161 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003162 caller()->AddAudioVideoTracks();
3163 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003164 caller()->CreateAndSetAndSignalOffer();
3165 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3166 ExpectNewFramesReceivedWithWait(
3167 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3168 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3169 kMaxWaitForFramesMs);
3170}
3171
3172// This tests that if we negotiate after calling CreateSender but before we
3173// have a track, then set a track later, frames from the newly-set track are
3174// received end-to-end.
3175// TODO(deadbeef): Change this test to use AddTransceiver, once that's
3176// implemented.
3177TEST_F(PeerConnectionIntegrationTest,
3178 MediaFlowsAfterEarlyWarmupWithCreateSender) {
3179 ASSERT_TRUE(CreatePeerConnectionWrappers());
3180 ConnectFakeSignaling();
3181 auto caller_audio_sender =
3182 caller()->pc()->CreateSender("audio", "caller_stream");
3183 auto caller_video_sender =
3184 caller()->pc()->CreateSender("video", "caller_stream");
3185 auto callee_audio_sender =
3186 callee()->pc()->CreateSender("audio", "callee_stream");
3187 auto callee_video_sender =
3188 callee()->pc()->CreateSender("video", "callee_stream");
3189 caller()->CreateAndSetAndSignalOffer();
3190 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3191 // Wait for ICE to complete, without any tracks being set.
3192 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3193 caller()->ice_connection_state(), kMaxWaitForFramesMs);
3194 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3195 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3196 // Now set the tracks, and expect frames to immediately start flowing.
3197 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
3198 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
3199 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
3200 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
3201 ExpectNewFramesReceivedWithWait(
3202 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3203 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3204 kMaxWaitForFramesMs);
3205}
3206
3207// This test verifies that a remote video track can be added via AddStream,
3208// and sent end-to-end. For this particular test, it's simply echoed back
3209// from the caller to the callee, rather than being forwarded to a third
3210// PeerConnection.
3211TEST_F(PeerConnectionIntegrationTest, CanSendRemoteVideoTrack) {
3212 ASSERT_TRUE(CreatePeerConnectionWrappers());
3213 ConnectFakeSignaling();
3214 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08003215 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07003216 caller()->CreateAndSetAndSignalOffer();
3217 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3218 ASSERT_EQ(1, callee()->remote_streams()->count());
3219
3220 // Echo the stream back, and do a new offer/anwer (initiated by callee this
3221 // time).
3222 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
3223 callee()->CreateAndSetAndSignalOffer();
3224 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
3225
3226 int expected_caller_received_video_frames = kDefaultExpectedVideoFrameCount;
3227 ExpectNewFramesReceivedWithWait(0, expected_caller_received_video_frames, 0,
3228 0, kMaxWaitForFramesMs);
3229}
3230
3231// Test that we achieve the expected end-to-end connection time, using a
3232// fake clock and simulated latency on the media and signaling paths.
3233// We use a TURN<->TURN connection because this is usually the quickest to
3234// set up initially, especially when we're confident the connection will work
3235// and can start sending media before we get a STUN response.
3236//
3237// With various optimizations enabled, here are the network delays we expect to
3238// be on the critical path:
3239// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
3240// signaling answer (with DTLS fingerprint).
3241// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
3242// using TURN<->TURN pair, and DTLS exchange is 4 packets,
3243// the first of which should have arrived before the answer.
3244TEST_F(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
3245 rtc::ScopedFakeClock fake_clock;
3246 // Some things use a time of "0" as a special value, so we need to start out
3247 // the fake clock at a nonzero time.
3248 // TODO(deadbeef): Fix this.
3249 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
3250
3251 static constexpr int media_hop_delay_ms = 50;
3252 static constexpr int signaling_trip_delay_ms = 500;
3253 // For explanation of these values, see comment above.
3254 static constexpr int required_media_hops = 9;
3255 static constexpr int required_signaling_trips = 2;
3256 // For internal delays (such as posting an event asychronously).
3257 static constexpr int allowed_internal_delay_ms = 20;
3258 static constexpr int total_connection_time_ms =
3259 media_hop_delay_ms * required_media_hops +
3260 signaling_trip_delay_ms * required_signaling_trips +
3261 allowed_internal_delay_ms;
3262
3263 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3264 3478};
3265 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3266 0};
3267 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3268 3478};
3269 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3270 0};
3271 cricket::TestTurnServer turn_server_1(network_thread(),
3272 turn_server_1_internal_address,
3273 turn_server_1_external_address);
3274 cricket::TestTurnServer turn_server_2(network_thread(),
3275 turn_server_2_internal_address,
3276 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02003277
deadbeef1dcb1642017-03-29 21:08:16 -07003278 // Bypass permission check on received packets so media can be sent before
3279 // the candidate is signaled.
3280 turn_server_1.set_enable_permission_checks(false);
3281 turn_server_2.set_enable_permission_checks(false);
3282
3283 PeerConnectionInterface::RTCConfiguration client_1_config;
3284 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3285 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3286 ice_server_1.username = "test";
3287 ice_server_1.password = "test";
3288 client_1_config.servers.push_back(ice_server_1);
3289 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3290 client_1_config.presume_writable_when_fully_relayed = true;
3291
3292 PeerConnectionInterface::RTCConfiguration client_2_config;
3293 webrtc::PeerConnectionInterface::IceServer ice_server_2;
3294 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
3295 ice_server_2.username = "test";
3296 ice_server_2.password = "test";
3297 client_2_config.servers.push_back(ice_server_2);
3298 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
3299 client_2_config.presume_writable_when_fully_relayed = true;
3300
3301 ASSERT_TRUE(
3302 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
3303 // Set up the simulated delays.
3304 SetSignalingDelayMs(signaling_trip_delay_ms);
3305 ConnectFakeSignaling();
3306 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
3307 virtual_socket_server()->UpdateDelayDistribution();
3308
3309 // Set "offer to receive audio/video" without adding any tracks, so we just
3310 // set up ICE/DTLS with no media.
3311 PeerConnectionInterface::RTCOfferAnswerOptions options;
3312 options.offer_to_receive_audio = 1;
3313 options.offer_to_receive_video = 1;
3314 caller()->SetOfferAnswerOptions(options);
3315 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07003316 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
3317 fake_clock);
deadbeef1dcb1642017-03-29 21:08:16 -07003318 // Need to free the clients here since they're using things we created on
3319 // the stack.
3320 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
3321 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
3322}
3323
Jonas Orelandbdcee282017-10-10 14:01:40 +02003324// Verify that a TurnCustomizer passed in through RTCConfiguration
3325// is actually used by the underlying TURN candidate pair.
3326// Note that turnport_unittest.cc contains more detailed, lower-level tests.
3327TEST_F(PeerConnectionIntegrationTest, \
3328 TurnCustomizerUsedForTurnConnections) {
3329 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
3330 3478};
3331 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
3332 0};
3333 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
3334 3478};
3335 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
3336 0};
3337 cricket::TestTurnServer turn_server_1(network_thread(),
3338 turn_server_1_internal_address,
3339 turn_server_1_external_address);
3340 cricket::TestTurnServer turn_server_2(network_thread(),
3341 turn_server_2_internal_address,
3342 turn_server_2_external_address);
3343
3344 PeerConnectionInterface::RTCConfiguration client_1_config;
3345 webrtc::PeerConnectionInterface::IceServer ice_server_1;
3346 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
3347 ice_server_1.username = "test";
3348 ice_server_1.password = "test";
3349 client_1_config.servers.push_back(ice_server_1);
3350 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
3351 auto customizer1 = rtc::MakeUnique<cricket::TestTurnCustomizer>();
3352 client_1_config.turn_customizer = customizer1.get();
3353
3354 PeerConnectionInterface::RTCConfiguration client_2_config;
3355 webrtc::PeerConnectionInterface::IceServer ice_server_2;
3356 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
3357 ice_server_2.username = "test";
3358 ice_server_2.password = "test";
3359 client_2_config.servers.push_back(ice_server_2);
3360 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
3361 auto customizer2 = rtc::MakeUnique<cricket::TestTurnCustomizer>();
3362 client_2_config.turn_customizer = customizer2.get();
3363
3364 ASSERT_TRUE(
3365 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
3366 ConnectFakeSignaling();
3367
3368 // Set "offer to receive audio/video" without adding any tracks, so we just
3369 // set up ICE/DTLS with no media.
3370 PeerConnectionInterface::RTCOfferAnswerOptions options;
3371 options.offer_to_receive_audio = 1;
3372 options.offer_to_receive_video = 1;
3373 caller()->SetOfferAnswerOptions(options);
3374 caller()->CreateAndSetAndSignalOffer();
3375 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
3376
3377 EXPECT_GT(customizer1->allow_channel_data_cnt_, 0u);
3378 EXPECT_GT(customizer1->modify_cnt_, 0u);
3379
3380 EXPECT_GT(customizer2->allow_channel_data_cnt_, 0u);
3381 EXPECT_GT(customizer2->modify_cnt_, 0u);
3382
3383 // Need to free the clients here since they're using things we created on
3384 // the stack.
3385 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
3386 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
3387}
3388
deadbeefc964d0b2017-04-03 10:03:35 -07003389// Test that audio and video flow end-to-end when codec names don't use the
3390// expected casing, given that they're supposed to be case insensitive. To test
3391// this, all but one codec is removed from each media description, and its
3392// casing is changed.
3393//
3394// In the past, this has regressed and caused crashes/black video, due to the
3395// fact that code at some layers was doing case-insensitive comparisons and
3396// code at other layers was not.
3397TEST_F(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
3398 ASSERT_TRUE(CreatePeerConnectionWrappers());
3399 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003400 caller()->AddAudioVideoTracks();
3401 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07003402
3403 // Remove all but one audio/video codec (opus and VP8), and change the
3404 // casing of the caller's generated offer.
3405 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
3406 cricket::AudioContentDescription* audio =
3407 GetFirstAudioContentDescription(description);
3408 ASSERT_NE(nullptr, audio);
3409 auto audio_codecs = audio->codecs();
3410 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
3411 [](const cricket::AudioCodec& codec) {
3412 return codec.name != "opus";
3413 }),
3414 audio_codecs.end());
3415 ASSERT_EQ(1u, audio_codecs.size());
3416 audio_codecs[0].name = "OpUs";
3417 audio->set_codecs(audio_codecs);
3418
3419 cricket::VideoContentDescription* video =
3420 GetFirstVideoContentDescription(description);
3421 ASSERT_NE(nullptr, video);
3422 auto video_codecs = video->codecs();
3423 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
3424 [](const cricket::VideoCodec& codec) {
3425 return codec.name != "VP8";
3426 }),
3427 video_codecs.end());
3428 ASSERT_EQ(1u, video_codecs.size());
3429 video_codecs[0].name = "vP8";
3430 video->set_codecs(video_codecs);
3431 });
3432
3433 caller()->CreateAndSetAndSignalOffer();
3434 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3435
3436 // Verify frames are still received end-to-end.
3437 ExpectNewFramesReceivedWithWait(
3438 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3439 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3440 kMaxWaitForFramesMs);
3441}
3442
hbos8d609f62017-04-10 07:39:05 -07003443TEST_F(PeerConnectionIntegrationTest, GetSources) {
3444 ASSERT_TRUE(CreatePeerConnectionWrappers());
3445 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003446 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07003447 caller()->CreateAndSetAndSignalOffer();
3448 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07003449 // Wait for one audio frame to be received by the callee.
hbos8d609f62017-04-10 07:39:05 -07003450 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
3451 ASSERT_GT(callee()->pc()->GetReceivers().size(), 0u);
3452 auto receiver = callee()->pc()->GetReceivers()[0];
3453 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
3454
3455 auto contributing_sources = receiver->GetSources();
3456 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
3457 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
3458 contributing_sources[0].source_id());
3459}
3460
deadbeef2f425aa2017-04-14 10:41:32 -07003461// Test that if a track is removed and added again with a different stream ID,
3462// the new stream ID is successfully communicated in SDP and media continues to
3463// flow end-to-end.
3464TEST_F(PeerConnectionIntegrationTest, RemoveAndAddTrackWithNewStreamId) {
3465 ASSERT_TRUE(CreatePeerConnectionWrappers());
3466 ConnectFakeSignaling();
3467
3468 rtc::scoped_refptr<MediaStreamInterface> stream_1 =
3469 caller()->pc_factory()->CreateLocalMediaStream("stream_1");
3470 rtc::scoped_refptr<MediaStreamInterface> stream_2 =
3471 caller()->pc_factory()->CreateLocalMediaStream("stream_2");
3472
3473 // Add track using stream 1, do offer/answer.
3474 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
3475 caller()->CreateLocalAudioTrack();
3476 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
3477 caller()->pc()->AddTrack(track, {stream_1.get()});
3478 caller()->CreateAndSetAndSignalOffer();
3479 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3480 // Wait for one audio frame to be received by the callee.
3481 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
3482
3483 // Remove the sender, and create a new one with the new stream.
3484 caller()->pc()->RemoveTrack(sender);
3485 sender = caller()->pc()->AddTrack(track, {stream_2.get()});
3486 caller()->CreateAndSetAndSignalOffer();
3487 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3488 // Wait for additional audio frames to be received by the callee.
3489 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount, 0,
3490 kMaxWaitForFramesMs);
3491}
3492
Elad Alon99c3fe52017-10-13 16:29:40 +02003493TEST_F(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
3494 ASSERT_TRUE(CreatePeerConnectionWrappers());
3495 ConnectFakeSignaling();
3496
3497 auto output = rtc::MakeUnique<testing::NiceMock<MockRtcEventLogOutput>>();
3498 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
3499 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
3500 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01003501 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
3502 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02003503
Steve Anton15324772018-01-16 10:26:49 -08003504 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02003505 caller()->CreateAndSetAndSignalOffer();
3506 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3507}
3508
Steve Antonede9ca52017-10-16 13:04:27 -07003509// Test that if candidates are only signaled by applying full session
3510// descriptions (instead of using AddIceCandidate), the peers can connect to
3511// each other and exchange media.
3512TEST_F(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
3513 ASSERT_TRUE(CreatePeerConnectionWrappers());
3514 // Each side will signal the session descriptions but not candidates.
3515 ConnectFakeSignalingForSdpOnly();
3516
3517 // Add audio video track and exchange the initial offer/answer with media
3518 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08003519 caller()->AddAudioVideoTracks();
3520 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003521 caller()->CreateAndSetAndSignalOffer();
3522
3523 // Wait for all candidates to be gathered on both the caller and callee.
3524 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
3525 caller()->ice_gathering_state(), kDefaultTimeout);
3526 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
3527 callee()->ice_gathering_state(), kDefaultTimeout);
3528
3529 // The candidates will now be included in the session description, so
3530 // signaling them will start the ICE connection.
3531 caller()->CreateAndSetAndSignalOffer();
3532 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3533
3534 // Ensure that media flows in both directions.
3535 ExpectNewFramesReceivedWithWait(
3536 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3537 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3538 kMaxWaitForFramesMs);
3539}
3540
henrika5f6bf242017-11-01 11:06:56 +01003541// Test that SetAudioPlayout can be used to disable audio playout from the
3542// start, then later enable it. This may be useful, for example, if the caller
3543// needs to play a local ringtone until some event occurs, after which it
3544// switches to playing the received audio.
3545TEST_F(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
3546 ASSERT_TRUE(CreatePeerConnectionWrappers());
3547 ConnectFakeSignaling();
3548
3549 // Set up audio-only call where audio playout is disabled on caller's side.
3550 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08003551 caller()->AddAudioTrack();
3552 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01003553 caller()->CreateAndSetAndSignalOffer();
3554 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3555
3556 // Pump messages for a second.
3557 WAIT(false, 1000);
3558 // Since audio playout is disabled, the caller shouldn't have received
3559 // anything (at the playout level, at least).
3560 EXPECT_EQ(0, caller()->audio_frames_received());
3561 // As a sanity check, make sure the callee (for which playout isn't disabled)
3562 // did still see frames on its audio level.
3563 ASSERT_GT(callee()->audio_frames_received(), 0);
3564
3565 // Enable playout again, and ensure audio starts flowing.
3566 caller()->pc()->SetAudioPlayout(true);
3567 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
3568 kDefaultExpectedAudioFrameCount, 0,
3569 kMaxWaitForFramesMs);
3570}
3571
3572double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
3573 auto report = pc->NewGetStats();
3574 auto track_stats_list =
3575 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3576 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
3577 for (const auto* track_stats : track_stats_list) {
3578 if (track_stats->remote_source.is_defined() &&
3579 *track_stats->remote_source) {
3580 remote_track_stats = track_stats;
3581 break;
3582 }
3583 }
3584
3585 if (!remote_track_stats->total_audio_energy.is_defined()) {
3586 return 0.0;
3587 }
3588 return *remote_track_stats->total_audio_energy;
3589}
3590
3591// Test that if audio playout is disabled via the SetAudioPlayout() method, then
3592// incoming audio is still processed and statistics are generated.
3593TEST_F(PeerConnectionIntegrationTest,
3594 DisableAudioPlayoutStillGeneratesAudioStats) {
3595 ASSERT_TRUE(CreatePeerConnectionWrappers());
3596 ConnectFakeSignaling();
3597
3598 // Set up audio-only call where playout is disabled but audio-processing is
3599 // still active.
Steve Anton15324772018-01-16 10:26:49 -08003600 caller()->AddAudioTrack();
3601 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01003602 caller()->pc()->SetAudioPlayout(false);
3603
3604 caller()->CreateAndSetAndSignalOffer();
3605 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3606
3607 // Wait for the callee to receive audio stats.
3608 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
3609}
3610
henrika4f167df2017-11-01 14:45:55 +01003611// Test that SetAudioRecording can be used to disable audio recording from the
3612// start, then later enable it. This may be useful, for example, if the caller
3613// wants to ensure that no audio resources are active before a certain state
3614// is reached.
3615TEST_F(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
3616 ASSERT_TRUE(CreatePeerConnectionWrappers());
3617 ConnectFakeSignaling();
3618
3619 // Set up audio-only call where audio recording is disabled on caller's side.
3620 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08003621 caller()->AddAudioTrack();
3622 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01003623 caller()->CreateAndSetAndSignalOffer();
3624 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3625
3626 // Pump messages for a second.
3627 WAIT(false, 1000);
3628 // Since caller has disabled audio recording, the callee shouldn't have
3629 // received anything.
3630 EXPECT_EQ(0, callee()->audio_frames_received());
3631 // As a sanity check, make sure the caller did still see frames on its
3632 // audio level since audio recording is enabled on the calle side.
3633 ASSERT_GT(caller()->audio_frames_received(), 0);
3634
3635 // Enable audio recording again, and ensure audio starts flowing.
3636 caller()->pc()->SetAudioRecording(true);
3637 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
3638 kDefaultExpectedAudioFrameCount, 0,
3639 kMaxWaitForFramesMs);
3640}
3641
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08003642// Test that after closing PeerConnections, they stop sending any packets (ICE,
3643// DTLS, RTP...).
3644TEST_F(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
3645 // Set up audio/video/data, wait for some frames to be received.
3646 ASSERT_TRUE(CreatePeerConnectionWrappers());
3647 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003648 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08003649#ifdef HAVE_SCTP
3650 caller()->CreateDataChannel();
3651#endif
3652 caller()->CreateAndSetAndSignalOffer();
3653 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3654 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount,
3655 kDefaultExpectedAudioFrameCount,
3656 kMaxWaitForFramesMs);
3657 // Close PeerConnections.
3658 caller()->pc()->Close();
3659 callee()->pc()->Close();
3660 // Pump messages for a second, and ensure no new packets end up sent.
3661 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
3662 WAIT(false, 1000);
3663 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
3664 EXPECT_EQ(sent_packets_a, sent_packets_b);
3665}
3666
Steve Antond3679212018-01-17 17:41:02 -08003667// Test that a basic 1 audio and 1 video track call works when Unified Plan
3668// semantics configured for both sides.
3669TEST_F(PeerConnectionIntegrationTest, UnifiedPlanMediaFlows) {
3670 PeerConnectionInterface::RTCConfiguration config;
3671 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
3672 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3673 ConnectFakeSignaling();
3674 caller()->AddAudioVideoTracks();
3675 callee()->AddAudioVideoTracks();
3676 caller()->CreateAndSetAndSignalOffer();
3677 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3678 ExpectNewFramesReceivedWithWait(
3679 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3680 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3681 kMaxWaitForFramesMs);
3682}
3683
Steve Anton74255ff2018-01-24 18:32:57 -08003684// Tests that verify interoperability between Plan B and Unified Plan
3685// PeerConnections.
3686class PeerConnectionIntegrationInteropTest
3687 : public PeerConnectionIntegrationTest,
3688 public ::testing::WithParamInterface<
3689 std::tuple<SdpSemantics, SdpSemantics>> {
3690 protected:
3691 PeerConnectionIntegrationInteropTest()
3692 : caller_semantics_(std::get<0>(GetParam())),
3693 callee_semantics_(std::get<1>(GetParam())) {}
3694
3695 bool CreatePeerConnectionWrappersWithSemantics() {
3696 RTCConfiguration caller_config;
3697 caller_config.sdp_semantics = caller_semantics_;
3698 RTCConfiguration callee_config;
3699 callee_config.sdp_semantics = callee_semantics_;
3700 return CreatePeerConnectionWrappersWithConfig(caller_config, callee_config);
3701 }
3702
3703 const SdpSemantics caller_semantics_;
3704 const SdpSemantics callee_semantics_;
3705};
3706
3707TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
3708 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3709 ConnectFakeSignaling();
3710
3711 caller()->CreateAndSetAndSignalOffer();
3712 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3713}
3714
3715TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
3716 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3717 ConnectFakeSignaling();
3718 auto audio_sender = caller()->AddAudioTrack();
3719
3720 caller()->CreateAndSetAndSignalOffer();
3721 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3722
3723 // Verify that one audio receiver has been created on the remote and that it
3724 // has the same track ID as the sending track.
3725 auto receivers = callee()->pc()->GetReceivers();
3726 ASSERT_EQ(1u, receivers.size());
3727 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
3728 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
3729
3730 // Expect to receive only audio frames on the callee.
3731 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount, 0,
3732 kMaxWaitForFramesMs);
3733}
3734
3735TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
3736 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3737 ConnectFakeSignaling();
3738 auto video_sender = caller()->AddVideoTrack();
3739 auto audio_sender = caller()->AddAudioTrack();
3740
3741 caller()->CreateAndSetAndSignalOffer();
3742 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3743
3744 // Verify that one audio and one video receiver have been created on the
3745 // remote and that they have the same track IDs as the sending tracks.
3746 auto audio_receivers =
3747 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
3748 ASSERT_EQ(1u, audio_receivers.size());
3749 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
3750 auto video_receivers =
3751 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
3752 ASSERT_EQ(1u, video_receivers.size());
3753 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
3754
3755 // Expect to receive audio and video frames only on the callee.
3756 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount,
3757 kDefaultExpectedVideoFrameCount,
3758 kMaxWaitForFramesMs);
3759}
3760
3761TEST_P(PeerConnectionIntegrationInteropTest,
3762 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
3763 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3764 ConnectFakeSignaling();
3765 caller()->AddAudioVideoTracks();
3766 callee()->AddAudioVideoTracks();
3767
3768 caller()->CreateAndSetAndSignalOffer();
3769 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3770
3771 ExpectNewFramesReceivedWithWait(
3772 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3773 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
3774 kMaxWaitForFramesMs);
3775}
3776
3777TEST_P(PeerConnectionIntegrationInteropTest,
3778 ReverseRolesOneAudioLocalToOneVideoRemote) {
3779 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3780 ConnectFakeSignaling();
3781 caller()->AddAudioTrack();
3782 callee()->AddVideoTrack();
3783
3784 caller()->CreateAndSetAndSignalOffer();
3785 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3786
3787 // Verify that only the audio track has been negotiated.
3788 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
3789 // Might also check that the callee's NegotiationNeeded flag is set.
3790
3791 // Reverse roles.
3792 callee()->CreateAndSetAndSignalOffer();
3793 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3794
3795 // Expect to receive audio frames on the callee and video frames on the
3796 // caller.
3797 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount,
3798 kDefaultExpectedAudioFrameCount, 0,
3799 kMaxWaitForFramesMs);
3800}
3801
3802// Test that if one side offers two video tracks then the other side will only
3803// see the first one and ignore the second.
3804TEST_P(PeerConnectionIntegrationInteropTest, TwoVideoLocalToNoMediaRemote) {
3805 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3806 ConnectFakeSignaling();
3807 auto first_sender = caller()->AddVideoTrack();
3808 caller()->AddVideoTrack();
3809
3810 caller()->CreateAndSetAndSignalOffer();
3811 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3812
3813 // Verify that there is only one receiver and it corresponds to the first
3814 // added track.
3815 auto receivers = callee()->pc()->GetReceivers();
3816 ASSERT_EQ(1u, receivers.size());
3817 EXPECT_TRUE(receivers[0]->track()->enabled());
3818 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
3819
3820 // Expect to receive video frames from the one track.
3821 ExpectNewFramesReceivedWithWait(0, 0,
3822 0, kDefaultExpectedVideoFrameCount,
3823 kMaxWaitForFramesMs);
3824}
3825
3826// Test that in the multi-track case each endpoint only looks at the first track
3827// and ignores the second one.
3828TEST_P(PeerConnectionIntegrationInteropTest, TwoVideoLocalToTwoVideoRemote) {
3829 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
3830 ConnectFakeSignaling();
3831 caller()->AddVideoTrack();
3832 caller()->AddVideoTrack();
3833 callee()->AddVideoTrack();
3834 callee()->AddVideoTrack();
3835
3836 caller()->CreateAndSetAndSignalOffer();
3837 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3838
3839 PeerConnectionWrapper* plan_b =
3840 (caller_semantics_ == SdpSemantics::kPlanB ? caller() : callee());
3841 PeerConnectionWrapper* unified_plan =
3842 (caller_semantics_ == SdpSemantics::kUnifiedPlan ? caller() : callee());
3843
3844 // Should have two senders each, one for each track.
3845 EXPECT_EQ(2u, plan_b->pc()->GetSenders().size());
3846 EXPECT_EQ(2u, unified_plan->pc()->GetSenders().size());
3847
3848 // Plan B will have one receiver since it only looks at the first video
3849 // section. The receiver should have the same track ID as the sender's first
3850 // track.
3851 ASSERT_EQ(1u, plan_b->pc()->GetReceivers().size());
3852 EXPECT_EQ(unified_plan->pc()->GetSenders()[0]->track()->id(),
3853 plan_b->pc()->GetReceivers()[0]->track()->id());
3854
3855 // Unified Plan will have two receivers since they were created with the
3856 // transceivers when the tracks were added.
3857 ASSERT_EQ(2u, unified_plan->pc()->GetReceivers().size());
3858
3859 if (unified_plan == caller()) {
3860 // If the Unified Plan endpoint was the caller, then the Plan B endpoint
3861 // would have rejected the second video media section so we would expect the
3862 // transceiver to be stopped.
3863 EXPECT_FALSE(unified_plan->pc()->GetTransceivers()[0]->stopped());
3864 EXPECT_TRUE(unified_plan->pc()->GetTransceivers()[1]->stopped());
3865 } else {
3866 // If the Unified Plan endpoint was the callee, then the Plan B endpoint
3867 // would have offered only one video section so we would expect the first
3868 // transceiver to map to the first track and the second transceiver to be
3869 // missing a mid.
3870 EXPECT_TRUE(unified_plan->pc()->GetTransceivers()[0]->mid());
3871 EXPECT_FALSE(unified_plan->pc()->GetTransceivers()[1]->mid());
3872 }
3873
3874 // Should be exchanging video frames for the first tracks on each endpoint.
3875 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount, 0,
3876 kDefaultExpectedVideoFrameCount,
3877 kMaxWaitForFramesMs);
3878}
3879
3880INSTANTIATE_TEST_CASE_P(
3881 PeerConnectionIntegrationTest,
3882 PeerConnectionIntegrationInteropTest,
3883 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
3884 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
3885
deadbeef1dcb1642017-03-29 21:08:16 -07003886} // namespace
3887
3888#endif // if !defined(THREAD_SANITIZER)