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