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