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