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