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