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