blob: f8126501b6017ddd0a581bac4fa0433065aca1f6 [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
25#include "webrtc/api/fakemetricsobserver.h"
26#include "webrtc/api/mediastreaminterface.h"
27#include "webrtc/api/peerconnectioninterface.h"
28#include "webrtc/api/test/fakeconstraints.h"
29#include "webrtc/base/asyncinvoker.h"
30#include "webrtc/base/fakenetwork.h"
31#include "webrtc/base/gunit.h"
32#include "webrtc/base/helpers.h"
33#include "webrtc/base/physicalsocketserver.h"
34#include "webrtc/base/ssladapter.h"
35#include "webrtc/base/sslstreamadapter.h"
36#include "webrtc/base/thread.h"
37#include "webrtc/base/virtualsocketserver.h"
38#include "webrtc/media/engine/fakewebrtcvideoengine.h"
39#include "webrtc/p2p/base/p2pconstants.h"
40#include "webrtc/p2p/base/portinterface.h"
41#include "webrtc/p2p/base/sessiondescription.h"
42#include "webrtc/p2p/base/testturnserver.h"
43#include "webrtc/p2p/client/basicportallocator.h"
44#include "webrtc/pc/dtmfsender.h"
45#include "webrtc/pc/localaudiosource.h"
46#include "webrtc/pc/mediasession.h"
47#include "webrtc/pc/peerconnection.h"
48#include "webrtc/pc/peerconnectionfactory.h"
49#include "webrtc/pc/test/fakeaudiocapturemodule.h"
50#include "webrtc/pc/test/fakeperiodicvideocapturer.h"
51#include "webrtc/pc/test/fakertccertificategenerator.h"
52#include "webrtc/pc/test/fakevideotrackrenderer.h"
53#include "webrtc/pc/test/mockpeerconnectionobservers.h"
54
55using cricket::ContentInfo;
56using cricket::FakeWebRtcVideoDecoder;
57using cricket::FakeWebRtcVideoDecoderFactory;
58using cricket::FakeWebRtcVideoEncoder;
59using cricket::FakeWebRtcVideoEncoderFactory;
60using cricket::MediaContentDescription;
61using webrtc::DataBuffer;
62using webrtc::DataChannelInterface;
63using webrtc::DtmfSender;
64using webrtc::DtmfSenderInterface;
65using webrtc::DtmfSenderObserverInterface;
66using webrtc::FakeConstraints;
67using webrtc::MediaConstraintsInterface;
68using webrtc::MediaStreamInterface;
69using webrtc::MediaStreamTrackInterface;
70using webrtc::MockCreateSessionDescriptionObserver;
71using webrtc::MockDataChannelObserver;
72using webrtc::MockSetSessionDescriptionObserver;
73using webrtc::MockStatsObserver;
74using webrtc::ObserverInterface;
75using webrtc::PeerConnectionInterface;
76using webrtc::PeerConnectionFactory;
77using webrtc::SessionDescriptionInterface;
78using webrtc::StreamCollectionInterface;
79
80namespace {
81
82static const int kDefaultTimeout = 10000;
83static const int kMaxWaitForStatsMs = 3000;
84static const int kMaxWaitForActivationMs = 5000;
85static const int kMaxWaitForFramesMs = 10000;
86// Default number of audio/video frames to wait for before considering a test
87// successful.
88static const int kDefaultExpectedAudioFrameCount = 3;
89static const int kDefaultExpectedVideoFrameCount = 3;
90
91static const char kDefaultStreamLabel[] = "stream_label";
92static const char kDefaultVideoTrackId[] = "video_track";
93static const char kDefaultAudioTrackId[] = "audio_track";
94static const char kDataChannelLabel[] = "data_channel";
95
96// SRTP cipher name negotiated by the tests. This must be updated if the
97// default changes.
98static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_32;
99static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
100
101// Helper function for constructing offer/answer options to initiate an ICE
102// restart.
103PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
104 PeerConnectionInterface::RTCOfferAnswerOptions options;
105 options.ice_restart = true;
106 return options;
107}
108
deadbeefd8ad7882017-04-18 16:01:17 -0700109// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
110// attribute from received SDP, simulating a legacy endpoint.
111void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
112 for (ContentInfo& content : desc->contents()) {
113 MediaContentDescription* media_desc =
114 static_cast<MediaContentDescription*>(content.description);
115 media_desc->mutable_streams().clear();
116 }
117 desc->set_msid_supported(false);
118}
119
deadbeef1dcb1642017-03-29 21:08:16 -0700120class SignalingMessageReceiver {
121 public:
122 virtual void ReceiveSdpMessage(const std::string& type,
123 const std::string& msg) = 0;
124 virtual void ReceiveIceMessage(const std::string& sdp_mid,
125 int sdp_mline_index,
126 const std::string& msg) = 0;
127
128 protected:
129 SignalingMessageReceiver() {}
130 virtual ~SignalingMessageReceiver() {}
131};
132
133class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
134 public:
135 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
136 : expected_media_type_(media_type) {}
137
138 void OnFirstPacketReceived(cricket::MediaType media_type) override {
139 ASSERT_EQ(expected_media_type_, media_type);
140 first_packet_received_ = true;
141 }
142
143 bool first_packet_received() const { return first_packet_received_; }
144
145 virtual ~MockRtpReceiverObserver() {}
146
147 private:
148 bool first_packet_received_ = false;
149 cricket::MediaType expected_media_type_;
150};
151
152// Helper class that wraps a peer connection, observes it, and can accept
153// signaling messages from another wrapper.
154//
155// Uses a fake network, fake A/V capture, and optionally fake
156// encoders/decoders, though they aren't used by default since they don't
157// advertise support of any codecs.
158class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
159 public SignalingMessageReceiver,
160 public ObserverInterface {
161 public:
162 // Different factory methods for convenience.
163 // TODO(deadbeef): Could use the pattern of:
164 //
165 // PeerConnectionWrapper =
166 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
167 //
168 // To reduce some code duplication.
169 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
170 const std::string& debug_name,
171 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
172 rtc::Thread* network_thread,
173 rtc::Thread* worker_thread) {
174 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
175 if (!client->Init(nullptr, nullptr, nullptr, std::move(cert_generator),
176 network_thread, worker_thread)) {
177 delete client;
178 return nullptr;
179 }
180 return client;
181 }
182
183 static PeerConnectionWrapper* CreateWithConfig(
184 const std::string& debug_name,
185 const PeerConnectionInterface::RTCConfiguration& config,
186 rtc::Thread* network_thread,
187 rtc::Thread* worker_thread) {
188 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
189 new FakeRTCCertificateGenerator());
190 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
191 if (!client->Init(nullptr, nullptr, &config, std::move(cert_generator),
192 network_thread, worker_thread)) {
193 delete client;
194 return nullptr;
195 }
196 return client;
197 }
198
199 static PeerConnectionWrapper* CreateWithOptions(
200 const std::string& debug_name,
201 const PeerConnectionFactory::Options& options,
202 rtc::Thread* network_thread,
203 rtc::Thread* worker_thread) {
204 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
205 new FakeRTCCertificateGenerator());
206 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
207 if (!client->Init(nullptr, &options, nullptr, std::move(cert_generator),
208 network_thread, worker_thread)) {
209 delete client;
210 return nullptr;
211 }
212 return client;
213 }
214
215 static PeerConnectionWrapper* CreateWithConstraints(
216 const std::string& debug_name,
217 const MediaConstraintsInterface* constraints,
218 rtc::Thread* network_thread,
219 rtc::Thread* worker_thread) {
220 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
221 new FakeRTCCertificateGenerator());
222 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
223 if (!client->Init(constraints, nullptr, nullptr, std::move(cert_generator),
224 network_thread, worker_thread)) {
225 delete client;
226 return nullptr;
227 }
228 return client;
229 }
230
deadbeef2f425aa2017-04-14 10:41:32 -0700231 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
232 return peer_connection_factory_.get();
233 }
234
deadbeef1dcb1642017-03-29 21:08:16 -0700235 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
236
237 // If a signaling message receiver is set (via ConnectFakeSignaling), this
238 // will set the whole offer/answer exchange in motion. Just need to wait for
239 // the signaling state to reach "stable".
240 void CreateAndSetAndSignalOffer() {
241 auto offer = CreateOffer();
242 ASSERT_NE(nullptr, offer);
243 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
244 }
245
246 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
247 // when a remote offer is received (via fake signaling) and an answer is
248 // generated. By default, uses default options.
249 void SetOfferAnswerOptions(
250 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
251 offer_answer_options_ = options;
252 }
253
254 // Set a callback to be invoked when SDP is received via the fake signaling
255 // channel, which provides an opportunity to munge (modify) the SDP. This is
256 // used to test SDP being applied that a PeerConnection would normally not
257 // generate, but a non-JSEP endpoint might.
258 void SetReceivedSdpMunger(
259 std::function<void(cricket::SessionDescription*)> munger) {
260 received_sdp_munger_ = munger;
261 }
262
deadbeefc964d0b2017-04-03 10:03:35 -0700263 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700264 // generated.
265 void SetGeneratedSdpMunger(
266 std::function<void(cricket::SessionDescription*)> munger) {
267 generated_sdp_munger_ = munger;
268 }
269
270 // Number of times the gathering state has transitioned to "gathering".
271 // Useful for telling if an ICE restart occurred as expected.
272 int transitions_to_gathering_state() const {
273 return transitions_to_gathering_state_;
274 }
275
276 // TODO(deadbeef): Switch the majority of these tests to use AddTrack instead
277 // of AddStream since AddStream is deprecated.
278 void AddAudioVideoMediaStream() {
279 AddMediaStreamFromTracks(CreateLocalAudioTrack(), CreateLocalVideoTrack());
280 }
281
282 void AddAudioOnlyMediaStream() {
283 AddMediaStreamFromTracks(CreateLocalAudioTrack(), nullptr);
284 }
285
286 void AddVideoOnlyMediaStream() {
287 AddMediaStreamFromTracks(nullptr, CreateLocalVideoTrack());
288 }
289
290 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
291 FakeConstraints constraints;
292 // Disable highpass filter so that we can get all the test audio frames.
293 constraints.AddMandatory(MediaConstraintsInterface::kHighpassFilter, false);
294 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
295 peer_connection_factory_->CreateAudioSource(&constraints);
296 // TODO(perkj): Test audio source when it is implemented. Currently audio
297 // always use the default input.
298 return peer_connection_factory_->CreateAudioTrack(kDefaultAudioTrackId,
299 source);
300 }
301
302 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
303 return CreateLocalVideoTrackInternal(
304 kDefaultVideoTrackId, FakeConstraints(), webrtc::kVideoRotation_0);
305 }
306
307 rtc::scoped_refptr<webrtc::VideoTrackInterface>
308 CreateLocalVideoTrackWithConstraints(const FakeConstraints& constraints) {
309 return CreateLocalVideoTrackInternal(kDefaultVideoTrackId, constraints,
310 webrtc::kVideoRotation_0);
311 }
312
313 rtc::scoped_refptr<webrtc::VideoTrackInterface>
314 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
315 return CreateLocalVideoTrackInternal(kDefaultVideoTrackId,
316 FakeConstraints(), rotation);
317 }
318
319 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackWithId(
320 const std::string& id) {
321 return CreateLocalVideoTrackInternal(id, FakeConstraints(),
322 webrtc::kVideoRotation_0);
323 }
324
325 void AddMediaStreamFromTracks(
326 rtc::scoped_refptr<webrtc::AudioTrackInterface> audio,
327 rtc::scoped_refptr<webrtc::VideoTrackInterface> video) {
328 AddMediaStreamFromTracksWithLabel(audio, video, kDefaultStreamLabel);
329 }
330
331 void AddMediaStreamFromTracksWithLabel(
332 rtc::scoped_refptr<webrtc::AudioTrackInterface> audio,
333 rtc::scoped_refptr<webrtc::VideoTrackInterface> video,
334 const std::string& stream_label) {
335 rtc::scoped_refptr<MediaStreamInterface> stream =
336 peer_connection_factory_->CreateLocalMediaStream(stream_label);
337 if (audio) {
338 stream->AddTrack(audio);
339 }
340 if (video) {
341 stream->AddTrack(video);
342 }
343 EXPECT_TRUE(pc()->AddStream(stream));
344 }
345
346 bool SignalingStateStable() {
347 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
348 }
349
350 void CreateDataChannel() { CreateDataChannel(nullptr); }
351
352 void CreateDataChannel(const webrtc::DataChannelInit* init) {
353 data_channel_ = pc()->CreateDataChannel(kDataChannelLabel, init);
354 ASSERT_TRUE(data_channel_.get() != nullptr);
355 data_observer_.reset(new MockDataChannelObserver(data_channel_));
356 }
357
358 DataChannelInterface* data_channel() { return data_channel_; }
359 const MockDataChannelObserver* data_observer() const {
360 return data_observer_.get();
361 }
362
363 int audio_frames_received() const {
364 return fake_audio_capture_module_->frames_received();
365 }
366
367 // Takes minimum of video frames received for each track.
368 //
369 // Can be used like:
370 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
371 //
372 // To ensure that all video tracks received at least a certain number of
373 // frames.
374 int min_video_frames_received_per_track() const {
375 int min_frames = INT_MAX;
376 if (video_decoder_factory_enabled_) {
377 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
378 fake_video_decoder_factory_->decoders();
379 if (decoders.empty()) {
380 return 0;
381 }
382 for (FakeWebRtcVideoDecoder* decoder : decoders) {
383 min_frames = std::min(min_frames, decoder->GetNumFramesReceived());
384 }
385 return min_frames;
386 } else {
387 if (fake_video_renderers_.empty()) {
388 return 0;
389 }
390
391 for (const auto& pair : fake_video_renderers_) {
392 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
393 }
394 return min_frames;
395 }
396 }
397
398 // In contrast to the above, sums the video frames received for all tracks.
399 // Can be used to verify that no video frames were received, or that the
400 // counts didn't increase.
401 int total_video_frames_received() const {
402 int total = 0;
403 if (video_decoder_factory_enabled_) {
404 const std::vector<FakeWebRtcVideoDecoder*>& decoders =
405 fake_video_decoder_factory_->decoders();
406 for (const FakeWebRtcVideoDecoder* decoder : decoders) {
407 total += decoder->GetNumFramesReceived();
408 }
409 } else {
410 for (const auto& pair : fake_video_renderers_) {
411 total += pair.second->num_rendered_frames();
412 }
413 for (const auto& renderer : removed_fake_video_renderers_) {
414 total += renderer->num_rendered_frames();
415 }
416 }
417 return total;
418 }
419
420 // Returns a MockStatsObserver in a state after stats gathering finished,
421 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700422 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700423 webrtc::MediaStreamTrackInterface* track) {
424 rtc::scoped_refptr<MockStatsObserver> observer(
425 new rtc::RefCountedObject<MockStatsObserver>());
426 EXPECT_TRUE(peer_connection_->GetStats(
427 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
428 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
429 return observer;
430 }
431
432 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700433 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
434 return OldGetStatsForTrack(nullptr);
435 }
436
437 // Synchronously gets stats and returns them. If it times out, fails the test
438 // and returns null.
439 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
440 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
441 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
442 peer_connection_->GetStats(callback);
443 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
444 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700445 }
446
447 int rendered_width() {
448 EXPECT_FALSE(fake_video_renderers_.empty());
449 return fake_video_renderers_.empty()
450 ? 0
451 : fake_video_renderers_.begin()->second->width();
452 }
453
454 int rendered_height() {
455 EXPECT_FALSE(fake_video_renderers_.empty());
456 return fake_video_renderers_.empty()
457 ? 0
458 : fake_video_renderers_.begin()->second->height();
459 }
460
461 double rendered_aspect_ratio() {
462 if (rendered_height() == 0) {
463 return 0.0;
464 }
465 return static_cast<double>(rendered_width()) / rendered_height();
466 }
467
468 webrtc::VideoRotation rendered_rotation() {
469 EXPECT_FALSE(fake_video_renderers_.empty());
470 return fake_video_renderers_.empty()
471 ? webrtc::kVideoRotation_0
472 : fake_video_renderers_.begin()->second->rotation();
473 }
474
475 int local_rendered_width() {
476 return local_video_renderer_ ? local_video_renderer_->width() : 0;
477 }
478
479 int local_rendered_height() {
480 return local_video_renderer_ ? local_video_renderer_->height() : 0;
481 }
482
483 double local_rendered_aspect_ratio() {
484 if (local_rendered_height() == 0) {
485 return 0.0;
486 }
487 return static_cast<double>(local_rendered_width()) /
488 local_rendered_height();
489 }
490
491 size_t number_of_remote_streams() {
492 if (!pc()) {
493 return 0;
494 }
495 return pc()->remote_streams()->count();
496 }
497
498 StreamCollectionInterface* remote_streams() const {
499 if (!pc()) {
500 ADD_FAILURE();
501 return nullptr;
502 }
503 return pc()->remote_streams();
504 }
505
506 StreamCollectionInterface* local_streams() {
507 if (!pc()) {
508 ADD_FAILURE();
509 return nullptr;
510 }
511 return pc()->local_streams();
512 }
513
514 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
515 return pc()->signaling_state();
516 }
517
518 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
519 return pc()->ice_connection_state();
520 }
521
522 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
523 return pc()->ice_gathering_state();
524 }
525
526 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
527 // GetReceivers. They're updated automatically when a remote offer/answer
528 // from the fake signaling channel is applied, or when
529 // ResetRtpReceiverObservers below is called.
530 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
531 rtp_receiver_observers() {
532 return rtp_receiver_observers_;
533 }
534
535 void ResetRtpReceiverObservers() {
536 rtp_receiver_observers_.clear();
537 for (auto receiver : pc()->GetReceivers()) {
538 std::unique_ptr<MockRtpReceiverObserver> observer(
539 new MockRtpReceiverObserver(receiver->media_type()));
540 receiver->SetObserver(observer.get());
541 rtp_receiver_observers_.push_back(std::move(observer));
542 }
543 }
544
545 private:
546 explicit PeerConnectionWrapper(const std::string& debug_name)
547 : debug_name_(debug_name) {}
548
549 bool Init(
550 const MediaConstraintsInterface* constraints,
551 const PeerConnectionFactory::Options* options,
552 const PeerConnectionInterface::RTCConfiguration* config,
553 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
554 rtc::Thread* network_thread,
555 rtc::Thread* worker_thread) {
556 // There's an error in this test code if Init ends up being called twice.
557 RTC_DCHECK(!peer_connection_);
558 RTC_DCHECK(!peer_connection_factory_);
559
560 fake_network_manager_.reset(new rtc::FakeNetworkManager());
561 fake_network_manager_->AddInterface(rtc::SocketAddress("192.168.1.1", 0));
562
563 std::unique_ptr<cricket::PortAllocator> port_allocator(
564 new cricket::BasicPortAllocator(fake_network_manager_.get()));
565 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
566 if (!fake_audio_capture_module_) {
567 return false;
568 }
569 // Note that these factories don't end up getting used unless supported
570 // codecs are added to them.
571 fake_video_decoder_factory_ = new FakeWebRtcVideoDecoderFactory();
572 fake_video_encoder_factory_ = new FakeWebRtcVideoEncoderFactory();
573 rtc::Thread* const signaling_thread = rtc::Thread::Current();
574 peer_connection_factory_ = webrtc::CreatePeerConnectionFactory(
575 network_thread, worker_thread, signaling_thread,
576 fake_audio_capture_module_, fake_video_encoder_factory_,
577 fake_video_decoder_factory_);
578 if (!peer_connection_factory_) {
579 return false;
580 }
581 if (options) {
582 peer_connection_factory_->SetOptions(*options);
583 }
584 peer_connection_ =
585 CreatePeerConnection(std::move(port_allocator), constraints, config,
586 std::move(cert_generator));
587 return peer_connection_.get() != nullptr;
588 }
589
590 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
591 std::unique_ptr<cricket::PortAllocator> port_allocator,
592 const MediaConstraintsInterface* constraints,
593 const PeerConnectionInterface::RTCConfiguration* config,
594 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator) {
595 PeerConnectionInterface::RTCConfiguration modified_config;
596 // If |config| is null, this will result in a default configuration being
597 // used.
598 if (config) {
599 modified_config = *config;
600 }
601 // Disable resolution adaptation; we don't want it interfering with the
602 // test results.
603 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
604 // ratios and not specific resolutions, is this even necessary?
605 modified_config.set_cpu_adaptation(false);
606
607 return peer_connection_factory_->CreatePeerConnection(
608 modified_config, constraints, std::move(port_allocator),
609 std::move(cert_generator), this);
610 }
611
612 void set_signaling_message_receiver(
613 SignalingMessageReceiver* signaling_message_receiver) {
614 signaling_message_receiver_ = signaling_message_receiver;
615 }
616
617 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
618
619 void EnableVideoDecoderFactory() {
620 video_decoder_factory_enabled_ = true;
621 fake_video_decoder_factory_->AddSupportedVideoCodecType(
622 webrtc::kVideoCodecVP8);
623 }
624
625 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
626 const std::string& track_id,
627 const FakeConstraints& constraints,
628 webrtc::VideoRotation rotation) {
629 // Set max frame rate to 10fps to reduce the risk of test flakiness.
630 // TODO(deadbeef): Do something more robust.
631 FakeConstraints source_constraints = constraints;
632 source_constraints.SetMandatoryMaxFrameRate(10);
633
634 cricket::FakeVideoCapturer* fake_capturer =
635 new webrtc::FakePeriodicVideoCapturer();
636 fake_capturer->SetRotation(rotation);
637 video_capturers_.push_back(fake_capturer);
638 rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> source =
639 peer_connection_factory_->CreateVideoSource(fake_capturer,
640 &source_constraints);
641 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
642 peer_connection_factory_->CreateVideoTrack(track_id, source));
643 if (!local_video_renderer_) {
644 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
645 }
646 return track;
647 }
648
649 void HandleIncomingOffer(const std::string& msg) {
650 LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
651 std::unique_ptr<SessionDescriptionInterface> desc(
652 webrtc::CreateSessionDescription("offer", msg, nullptr));
653 if (received_sdp_munger_) {
654 received_sdp_munger_(desc->description());
655 }
656
657 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
658 // Setting a remote description may have changed the number of receivers,
659 // so reset the receiver observers.
660 ResetRtpReceiverObservers();
661 auto answer = CreateAnswer();
662 ASSERT_NE(nullptr, answer);
663 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
664 }
665
666 void HandleIncomingAnswer(const std::string& msg) {
667 LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
668 std::unique_ptr<SessionDescriptionInterface> desc(
669 webrtc::CreateSessionDescription("answer", msg, nullptr));
670 if (received_sdp_munger_) {
671 received_sdp_munger_(desc->description());
672 }
673
674 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
675 // Set the RtpReceiverObserver after receivers are created.
676 ResetRtpReceiverObservers();
677 }
678
679 // Returns null on failure.
680 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
681 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
682 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
683 pc()->CreateOffer(observer, offer_answer_options_);
684 return WaitForDescriptionFromObserver(observer);
685 }
686
687 // Returns null on failure.
688 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
689 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
690 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
691 pc()->CreateAnswer(observer, offer_answer_options_);
692 return WaitForDescriptionFromObserver(observer);
693 }
694
695 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
696 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer) {
697 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
698 if (!observer->result()) {
699 return nullptr;
700 }
701 auto description = observer->MoveDescription();
702 if (generated_sdp_munger_) {
703 generated_sdp_munger_(description->description());
704 }
705 return description;
706 }
707
708 // Setting the local description and sending the SDP message over the fake
709 // signaling channel are combined into the same method because the SDP
710 // message needs to be sent as soon as SetLocalDescription finishes, without
711 // waiting for the observer to be called. This ensures that ICE candidates
712 // don't outrace the description.
713 bool SetLocalDescriptionAndSendSdpMessage(
714 std::unique_ptr<SessionDescriptionInterface> desc) {
715 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
716 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
717 LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
718 std::string type = desc->type();
719 std::string sdp;
720 EXPECT_TRUE(desc->ToString(&sdp));
721 pc()->SetLocalDescription(observer, desc.release());
722 // As mentioned above, we need to send the message immediately after
723 // SetLocalDescription.
724 SendSdpMessage(type, sdp);
725 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
726 return true;
727 }
728
729 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
730 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
731 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
732 LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
733 pc()->SetRemoteDescription(observer, desc.release());
734 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
735 return observer->result();
736 }
737
738 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
739 // default).
740 void SendSdpMessage(const std::string& type, const std::string& msg) {
741 if (signaling_delay_ms_ == 0) {
742 RelaySdpMessageIfReceiverExists(type, msg);
743 } else {
744 invoker_.AsyncInvokeDelayed<void>(
745 RTC_FROM_HERE, rtc::Thread::Current(),
746 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
747 this, type, msg),
748 signaling_delay_ms_);
749 }
750 }
751
752 void RelaySdpMessageIfReceiverExists(const std::string& type,
753 const std::string& msg) {
754 if (signaling_message_receiver_) {
755 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
756 }
757 }
758
759 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
760 // default).
761 void SendIceMessage(const std::string& sdp_mid,
762 int sdp_mline_index,
763 const std::string& msg) {
764 if (signaling_delay_ms_ == 0) {
765 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
766 } else {
767 invoker_.AsyncInvokeDelayed<void>(
768 RTC_FROM_HERE, rtc::Thread::Current(),
769 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
770 this, sdp_mid, sdp_mline_index, msg),
771 signaling_delay_ms_);
772 }
773 }
774
775 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
776 int sdp_mline_index,
777 const std::string& msg) {
778 if (signaling_message_receiver_) {
779 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
780 msg);
781 }
782 }
783
784 // SignalingMessageReceiver callbacks.
785 void ReceiveSdpMessage(const std::string& type,
786 const std::string& msg) override {
787 if (type == webrtc::SessionDescriptionInterface::kOffer) {
788 HandleIncomingOffer(msg);
789 } else {
790 HandleIncomingAnswer(msg);
791 }
792 }
793
794 void ReceiveIceMessage(const std::string& sdp_mid,
795 int sdp_mline_index,
796 const std::string& msg) override {
797 LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
798 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
799 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
800 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
801 }
802
803 // PeerConnectionObserver callbacks.
804 void OnSignalingChange(
805 webrtc::PeerConnectionInterface::SignalingState new_state) override {
806 EXPECT_EQ(pc()->signaling_state(), new_state);
807 }
808 void OnAddStream(
809 rtc::scoped_refptr<MediaStreamInterface> media_stream) override {
810 media_stream->RegisterObserver(this);
811 for (size_t i = 0; i < media_stream->GetVideoTracks().size(); ++i) {
812 const std::string id = media_stream->GetVideoTracks()[i]->id();
813 ASSERT_TRUE(fake_video_renderers_.find(id) ==
814 fake_video_renderers_.end());
815 fake_video_renderers_[id].reset(new webrtc::FakeVideoTrackRenderer(
816 media_stream->GetVideoTracks()[i]));
817 }
818 }
819 void OnRemoveStream(
820 rtc::scoped_refptr<MediaStreamInterface> media_stream) override {}
821 void OnRenegotiationNeeded() override {}
822 void OnIceConnectionChange(
823 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
824 EXPECT_EQ(pc()->ice_connection_state(), new_state);
825 }
826 void OnIceGatheringChange(
827 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
828 if (new_state == PeerConnectionInterface::kIceGatheringGathering) {
829 ++transitions_to_gathering_state_;
830 }
831 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
832 }
833 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
834 LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
835
836 std::string ice_sdp;
837 EXPECT_TRUE(candidate->ToString(&ice_sdp));
838 if (signaling_message_receiver_ == nullptr) {
839 // Remote party may be deleted.
840 return;
841 }
842 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
843 }
844 void OnDataChannel(
845 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
846 LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
847 data_channel_ = data_channel;
848 data_observer_.reset(new MockDataChannelObserver(data_channel));
849 }
850
851 // MediaStreamInterface callback
852 void OnChanged() override {
853 // Track added or removed from MediaStream, so update our renderers.
854 rtc::scoped_refptr<StreamCollectionInterface> remote_streams =
855 pc()->remote_streams();
856 // Remove renderers for tracks that were removed.
857 for (auto it = fake_video_renderers_.begin();
858 it != fake_video_renderers_.end();) {
859 if (remote_streams->FindVideoTrack(it->first) == nullptr) {
860 auto to_remove = it++;
861 removed_fake_video_renderers_.push_back(std::move(to_remove->second));
862 fake_video_renderers_.erase(to_remove);
863 } else {
864 ++it;
865 }
866 }
867 // Create renderers for new video tracks.
868 for (size_t stream_index = 0; stream_index < remote_streams->count();
869 ++stream_index) {
870 MediaStreamInterface* remote_stream = remote_streams->at(stream_index);
871 for (size_t track_index = 0;
872 track_index < remote_stream->GetVideoTracks().size();
873 ++track_index) {
874 const std::string id =
875 remote_stream->GetVideoTracks()[track_index]->id();
876 if (fake_video_renderers_.find(id) != fake_video_renderers_.end()) {
877 continue;
878 }
879 fake_video_renderers_[id].reset(new webrtc::FakeVideoTrackRenderer(
880 remote_stream->GetVideoTracks()[track_index]));
881 }
882 }
883 }
884
885 std::string debug_name_;
886
887 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
888
889 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
890 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
891 peer_connection_factory_;
892
893 // Needed to keep track of number of frames sent.
894 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
895 // Needed to keep track of number of frames received.
896 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
897 fake_video_renderers_;
898 // Needed to ensure frames aren't received for removed tracks.
899 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
900 removed_fake_video_renderers_;
901 // Needed to keep track of number of frames received when external decoder
902 // used.
903 FakeWebRtcVideoDecoderFactory* fake_video_decoder_factory_ = nullptr;
904 FakeWebRtcVideoEncoderFactory* fake_video_encoder_factory_ = nullptr;
905 bool video_decoder_factory_enabled_ = false;
906
907 // For remote peer communication.
908 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
909 int signaling_delay_ms_ = 0;
910
911 // Store references to the video capturers we've created, so that we can stop
912 // them, if required.
913 std::vector<cricket::FakeVideoCapturer*> video_capturers_;
914 // |local_video_renderer_| attached to the first created local video track.
915 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
916
917 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
918 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
919 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
920
921 rtc::scoped_refptr<DataChannelInterface> data_channel_;
922 std::unique_ptr<MockDataChannelObserver> data_observer_;
923
924 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
925
926 int transitions_to_gathering_state_ = 0;
927
928 rtc::AsyncInvoker invoker_;
929
930 friend class PeerConnectionIntegrationTest;
931};
932
933// Tests two PeerConnections connecting to each other end-to-end, using a
934// virtual network, fake A/V capture and fake encoder/decoders. The
935// PeerConnections share the threads/socket servers, but use separate versions
936// of everything else (including "PeerConnectionFactory"s).
937class PeerConnectionIntegrationTest : public testing::Test {
938 public:
939 PeerConnectionIntegrationTest()
940 : pss_(new rtc::PhysicalSocketServer),
941 ss_(new rtc::VirtualSocketServer(pss_.get())),
942 network_thread_(new rtc::Thread(ss_.get())),
943 worker_thread_(rtc::Thread::Create()) {
944 RTC_CHECK(network_thread_->Start());
945 RTC_CHECK(worker_thread_->Start());
946 }
947
948 ~PeerConnectionIntegrationTest() {
949 if (caller_) {
950 caller_->set_signaling_message_receiver(nullptr);
951 }
952 if (callee_) {
953 callee_->set_signaling_message_receiver(nullptr);
954 }
955 }
956
957 bool SignalingStateStable() {
958 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
959 }
960
961 bool CreatePeerConnectionWrappers() {
962 return CreatePeerConnectionWrappersWithConfig(
963 PeerConnectionInterface::RTCConfiguration(),
964 PeerConnectionInterface::RTCConfiguration());
965 }
966
967 bool CreatePeerConnectionWrappersWithConstraints(
968 MediaConstraintsInterface* caller_constraints,
969 MediaConstraintsInterface* callee_constraints) {
970 caller_.reset(PeerConnectionWrapper::CreateWithConstraints(
971 "Caller", caller_constraints, network_thread_.get(),
972 worker_thread_.get()));
973 callee_.reset(PeerConnectionWrapper::CreateWithConstraints(
974 "Callee", callee_constraints, network_thread_.get(),
975 worker_thread_.get()));
976 return caller_ && callee_;
977 }
978
979 bool CreatePeerConnectionWrappersWithConfig(
980 const PeerConnectionInterface::RTCConfiguration& caller_config,
981 const PeerConnectionInterface::RTCConfiguration& callee_config) {
982 caller_.reset(PeerConnectionWrapper::CreateWithConfig(
983 "Caller", caller_config, network_thread_.get(), worker_thread_.get()));
984 callee_.reset(PeerConnectionWrapper::CreateWithConfig(
985 "Callee", callee_config, network_thread_.get(), worker_thread_.get()));
986 return caller_ && callee_;
987 }
988
989 bool CreatePeerConnectionWrappersWithOptions(
990 const PeerConnectionFactory::Options& caller_options,
991 const PeerConnectionFactory::Options& callee_options) {
992 caller_.reset(PeerConnectionWrapper::CreateWithOptions(
993 "Caller", caller_options, network_thread_.get(), worker_thread_.get()));
994 callee_.reset(PeerConnectionWrapper::CreateWithOptions(
995 "Callee", callee_options, network_thread_.get(), worker_thread_.get()));
996 return caller_ && callee_;
997 }
998
999 PeerConnectionWrapper* CreatePeerConnectionWrapperWithAlternateKey() {
1000 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1001 new FakeRTCCertificateGenerator());
1002 cert_generator->use_alternate_key();
1003
1004 // Make sure the new client is using a different certificate.
1005 return PeerConnectionWrapper::CreateWithDtlsIdentityStore(
1006 "New Peer", std::move(cert_generator), network_thread_.get(),
1007 worker_thread_.get());
1008 }
1009
1010 // Once called, SDP blobs and ICE candidates will be automatically signaled
1011 // between PeerConnections.
1012 void ConnectFakeSignaling() {
1013 caller_->set_signaling_message_receiver(callee_.get());
1014 callee_->set_signaling_message_receiver(caller_.get());
1015 }
1016
1017 void SetSignalingDelayMs(int delay_ms) {
1018 caller_->set_signaling_delay_ms(delay_ms);
1019 callee_->set_signaling_delay_ms(delay_ms);
1020 }
1021
1022 void EnableVideoDecoderFactory() {
1023 caller_->EnableVideoDecoderFactory();
1024 callee_->EnableVideoDecoderFactory();
1025 }
1026
1027 // Messages may get lost on the unreliable DataChannel, so we send multiple
1028 // times to avoid test flakiness.
1029 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1030 const std::string& data,
1031 int retries) {
1032 for (int i = 0; i < retries; ++i) {
1033 dc->Send(DataBuffer(data));
1034 }
1035 }
1036
1037 rtc::Thread* network_thread() { return network_thread_.get(); }
1038
1039 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1040
1041 PeerConnectionWrapper* caller() { return caller_.get(); }
1042
1043 // Set the |caller_| to the |wrapper| passed in and return the
1044 // original |caller_|.
1045 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1046 PeerConnectionWrapper* wrapper) {
1047 PeerConnectionWrapper* old = caller_.release();
1048 caller_.reset(wrapper);
1049 return old;
1050 }
1051
1052 PeerConnectionWrapper* callee() { return callee_.get(); }
1053
1054 // Set the |callee_| to the |wrapper| passed in and return the
1055 // original |callee_|.
1056 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1057 PeerConnectionWrapper* wrapper) {
1058 PeerConnectionWrapper* old = callee_.release();
1059 callee_.reset(wrapper);
1060 return old;
1061 }
1062
1063 // Expects the provided number of new frames to be received within |wait_ms|.
1064 // "New frames" meaning that it waits for the current frame counts to
1065 // *increase* by the provided values. For video, uses
1066 // RecievedVideoFramesForEachTrack for the case of multiple video tracks
1067 // being received.
1068 void ExpectNewFramesReceivedWithWait(
1069 int expected_caller_received_audio_frames,
1070 int expected_caller_received_video_frames,
1071 int expected_callee_received_audio_frames,
1072 int expected_callee_received_video_frames,
1073 int wait_ms) {
1074 // Add current frame counts to the provided values, in order to wait for
1075 // the frame count to increase.
1076 expected_caller_received_audio_frames += caller()->audio_frames_received();
1077 expected_caller_received_video_frames +=
1078 caller()->min_video_frames_received_per_track();
1079 expected_callee_received_audio_frames += callee()->audio_frames_received();
1080 expected_callee_received_video_frames +=
1081 callee()->min_video_frames_received_per_track();
1082
1083 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
1084 expected_caller_received_audio_frames &&
1085 caller()->min_video_frames_received_per_track() >=
1086 expected_caller_received_video_frames &&
1087 callee()->audio_frames_received() >=
1088 expected_callee_received_audio_frames &&
1089 callee()->min_video_frames_received_per_track() >=
1090 expected_callee_received_video_frames,
1091 wait_ms);
1092
1093 // After the combined wait, do an "expect" for each individual count, to
1094 // print out a more detailed message upon failure.
1095 EXPECT_GE(caller()->audio_frames_received(),
1096 expected_caller_received_audio_frames);
1097 EXPECT_GE(caller()->min_video_frames_received_per_track(),
1098 expected_caller_received_video_frames);
1099 EXPECT_GE(callee()->audio_frames_received(),
1100 expected_callee_received_audio_frames);
1101 EXPECT_GE(callee()->min_video_frames_received_per_track(),
1102 expected_callee_received_video_frames);
1103 }
1104
1105 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1106 bool remote_gcm_enabled,
1107 int expected_cipher_suite) {
1108 PeerConnectionFactory::Options caller_options;
1109 caller_options.crypto_options.enable_gcm_crypto_suites = local_gcm_enabled;
1110 PeerConnectionFactory::Options callee_options;
1111 callee_options.crypto_options.enable_gcm_crypto_suites = remote_gcm_enabled;
1112 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1113 callee_options));
1114 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1115 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1116 caller()->pc()->RegisterUMAObserver(caller_observer);
1117 ConnectFakeSignaling();
1118 caller()->AddAudioVideoMediaStream();
1119 callee()->AddAudioVideoMediaStream();
1120 caller()->CreateAndSetAndSignalOffer();
1121 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1122 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001123 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001124 EXPECT_EQ(
1125 1, caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1126 expected_cipher_suite));
1127 caller()->pc()->RegisterUMAObserver(nullptr);
1128 }
1129
1130 private:
1131 // |ss_| is used by |network_thread_| so it must be destroyed later.
1132 std::unique_ptr<rtc::PhysicalSocketServer> pss_;
1133 std::unique_ptr<rtc::VirtualSocketServer> ss_;
1134 // |network_thread_| and |worker_thread_| are used by both
1135 // |caller_| and |callee_| so they must be destroyed
1136 // later.
1137 std::unique_ptr<rtc::Thread> network_thread_;
1138 std::unique_ptr<rtc::Thread> worker_thread_;
1139 std::unique_ptr<PeerConnectionWrapper> caller_;
1140 std::unique_ptr<PeerConnectionWrapper> callee_;
1141};
1142
1143// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1144// includes testing that the callback is invoked if an observer is connected
1145// after the first packet has already been received.
1146TEST_F(PeerConnectionIntegrationTest,
1147 RtpReceiverObserverOnFirstPacketReceived) {
1148 ASSERT_TRUE(CreatePeerConnectionWrappers());
1149 ConnectFakeSignaling();
1150 caller()->AddAudioVideoMediaStream();
1151 callee()->AddAudioVideoMediaStream();
1152 // Start offer/answer exchange and wait for it to complete.
1153 caller()->CreateAndSetAndSignalOffer();
1154 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1155 // Should be one receiver each for audio/video.
1156 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1157 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1158 // Wait for all "first packet received" callbacks to be fired.
1159 EXPECT_TRUE_WAIT(
1160 std::all_of(caller()->rtp_receiver_observers().begin(),
1161 caller()->rtp_receiver_observers().end(),
1162 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1163 return o->first_packet_received();
1164 }),
1165 kMaxWaitForFramesMs);
1166 EXPECT_TRUE_WAIT(
1167 std::all_of(callee()->rtp_receiver_observers().begin(),
1168 callee()->rtp_receiver_observers().end(),
1169 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1170 return o->first_packet_received();
1171 }),
1172 kMaxWaitForFramesMs);
1173 // If new observers are set after the first packet was already received, the
1174 // callback should still be invoked.
1175 caller()->ResetRtpReceiverObservers();
1176 callee()->ResetRtpReceiverObservers();
1177 EXPECT_EQ(2, caller()->rtp_receiver_observers().size());
1178 EXPECT_EQ(2, callee()->rtp_receiver_observers().size());
1179 EXPECT_TRUE(
1180 std::all_of(caller()->rtp_receiver_observers().begin(),
1181 caller()->rtp_receiver_observers().end(),
1182 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1183 return o->first_packet_received();
1184 }));
1185 EXPECT_TRUE(
1186 std::all_of(callee()->rtp_receiver_observers().begin(),
1187 callee()->rtp_receiver_observers().end(),
1188 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1189 return o->first_packet_received();
1190 }));
1191}
1192
1193class DummyDtmfObserver : public DtmfSenderObserverInterface {
1194 public:
1195 DummyDtmfObserver() : completed_(false) {}
1196
1197 // Implements DtmfSenderObserverInterface.
1198 void OnToneChange(const std::string& tone) override {
1199 tones_.push_back(tone);
1200 if (tone.empty()) {
1201 completed_ = true;
1202 }
1203 }
1204
1205 const std::vector<std::string>& tones() const { return tones_; }
1206 bool completed() const { return completed_; }
1207
1208 private:
1209 bool completed_;
1210 std::vector<std::string> tones_;
1211};
1212
1213// Assumes |sender| already has an audio track added and the offer/answer
1214// exchange is done.
1215void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1216 PeerConnectionWrapper* receiver) {
1217 DummyDtmfObserver observer;
1218 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender;
1219
1220 // We should be able to create a DTMF sender from a local track.
1221 webrtc::AudioTrackInterface* localtrack =
1222 sender->local_streams()->at(0)->GetAudioTracks()[0];
1223 dtmf_sender = sender->pc()->CreateDtmfSender(localtrack);
1224 ASSERT_NE(nullptr, dtmf_sender.get());
1225 dtmf_sender->RegisterObserver(&observer);
1226
1227 // Test the DtmfSender object just created.
1228 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1229 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1230
1231 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1232 std::vector<std::string> tones = {"1", "a", ""};
1233 EXPECT_EQ(tones, observer.tones());
1234 dtmf_sender->UnregisterObserver();
1235 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1236}
1237
1238// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1239// direction).
1240TEST_F(PeerConnectionIntegrationTest, DtmfSenderObserver) {
1241 ASSERT_TRUE(CreatePeerConnectionWrappers());
1242 ConnectFakeSignaling();
1243 // Only need audio for DTMF.
1244 caller()->AddAudioOnlyMediaStream();
1245 callee()->AddAudioOnlyMediaStream();
1246 caller()->CreateAndSetAndSignalOffer();
1247 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1248 TestDtmfFromSenderToReceiver(caller(), callee());
1249 TestDtmfFromSenderToReceiver(callee(), caller());
1250}
1251
1252// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1253// between two connections, using DTLS-SRTP.
1254TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
1255 ASSERT_TRUE(CreatePeerConnectionWrappers());
1256 ConnectFakeSignaling();
1257 // Do normal offer/answer and wait for some frames to be received in each
1258 // direction.
1259 caller()->AddAudioVideoMediaStream();
1260 callee()->AddAudioVideoMediaStream();
1261 caller()->CreateAndSetAndSignalOffer();
1262 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1263 ExpectNewFramesReceivedWithWait(
1264 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1265 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1266 kMaxWaitForFramesMs);
1267}
1268
1269// Uses SDES instead of DTLS for key agreement.
1270TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
1271 PeerConnectionInterface::RTCConfiguration sdes_config;
1272 sdes_config.enable_dtls_srtp.emplace(false);
1273 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1274 ConnectFakeSignaling();
1275
1276 // Do normal offer/answer and wait for some frames to be received in each
1277 // direction.
1278 caller()->AddAudioVideoMediaStream();
1279 callee()->AddAudioVideoMediaStream();
1280 caller()->CreateAndSetAndSignalOffer();
1281 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1282 ExpectNewFramesReceivedWithWait(
1283 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1284 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1285 kMaxWaitForFramesMs);
1286}
1287
1288// This test sets up a call between two parties (using DTLS) and tests that we
1289// can get a video aspect ratio of 16:9.
1290TEST_F(PeerConnectionIntegrationTest, SendAndReceive16To9AspectRatio) {
1291 ASSERT_TRUE(CreatePeerConnectionWrappers());
1292 ConnectFakeSignaling();
1293
1294 // Add video tracks with 16:9 constraint.
1295 FakeConstraints constraints;
1296 double requested_ratio = 16.0 / 9;
1297 constraints.SetMandatoryMinAspectRatio(requested_ratio);
1298 caller()->AddMediaStreamFromTracks(
1299 nullptr, caller()->CreateLocalVideoTrackWithConstraints(constraints));
1300 callee()->AddMediaStreamFromTracks(
1301 nullptr, callee()->CreateLocalVideoTrackWithConstraints(constraints));
1302
1303 // Do normal offer/answer and wait for at least one frame to be received in
1304 // each direction.
1305 caller()->CreateAndSetAndSignalOffer();
1306 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1307 callee()->min_video_frames_received_per_track() > 0,
1308 kMaxWaitForFramesMs);
1309
1310 // Check rendered aspect ratio.
1311 EXPECT_EQ(requested_ratio, caller()->local_rendered_aspect_ratio());
1312 EXPECT_EQ(requested_ratio, caller()->rendered_aspect_ratio());
1313 EXPECT_EQ(requested_ratio, callee()->local_rendered_aspect_ratio());
1314 EXPECT_EQ(requested_ratio, callee()->rendered_aspect_ratio());
1315}
1316
1317// This test sets up a call between two parties with a source resolution of
1318// 1280x720 and verifies that a 16:9 aspect ratio is received.
1319TEST_F(PeerConnectionIntegrationTest,
1320 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1321 ASSERT_TRUE(CreatePeerConnectionWrappers());
1322 ConnectFakeSignaling();
1323
1324 // Similar to above test, but uses MandatoryMin[Width/Height] constraint
1325 // instead of aspect ratio constraint.
1326 FakeConstraints constraints;
1327 constraints.SetMandatoryMinWidth(1280);
1328 constraints.SetMandatoryMinHeight(720);
1329 caller()->AddMediaStreamFromTracks(
1330 nullptr, caller()->CreateLocalVideoTrackWithConstraints(constraints));
1331 callee()->AddMediaStreamFromTracks(
1332 nullptr, callee()->CreateLocalVideoTrackWithConstraints(constraints));
1333
1334 // Do normal offer/answer and wait for at least one frame to be received in
1335 // each direction.
1336 caller()->CreateAndSetAndSignalOffer();
1337 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1338 callee()->min_video_frames_received_per_track() > 0,
1339 kMaxWaitForFramesMs);
1340
1341 // Check rendered aspect ratio.
1342 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1343 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1344 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1345 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1346}
1347
1348// This test sets up an one-way call, with media only from caller to
1349// callee.
1350TEST_F(PeerConnectionIntegrationTest, OneWayMediaCall) {
1351 ASSERT_TRUE(CreatePeerConnectionWrappers());
1352 ConnectFakeSignaling();
1353 caller()->AddAudioVideoMediaStream();
1354 caller()->CreateAndSetAndSignalOffer();
1355 int caller_received_frames = 0;
1356 ExpectNewFramesReceivedWithWait(
1357 caller_received_frames, caller_received_frames,
1358 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1359 kMaxWaitForFramesMs);
1360}
1361
1362// This test sets up a audio call initially, with the callee rejecting video
1363// initially. Then later the callee decides to upgrade to audio/video, and
1364// initiates a new offer/answer exchange.
1365TEST_F(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
1366 ASSERT_TRUE(CreatePeerConnectionWrappers());
1367 ConnectFakeSignaling();
1368 // Initially, offer an audio/video stream from the caller, but refuse to
1369 // send/receive video on the callee side.
1370 caller()->AddAudioVideoMediaStream();
1371 callee()->AddMediaStreamFromTracks(callee()->CreateLocalAudioTrack(),
1372 nullptr);
1373 PeerConnectionInterface::RTCOfferAnswerOptions options;
1374 options.offer_to_receive_video = 0;
1375 callee()->SetOfferAnswerOptions(options);
1376 // Do offer/answer and make sure audio is still received end-to-end.
1377 caller()->CreateAndSetAndSignalOffer();
1378 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1379 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1380 kDefaultExpectedAudioFrameCount, 0,
1381 kMaxWaitForFramesMs);
1382 // Sanity check that the callee's description has a rejected video section.
1383 ASSERT_NE(nullptr, callee()->pc()->local_description());
1384 const ContentInfo* callee_video_content =
1385 GetFirstVideoContent(callee()->pc()->local_description()->description());
1386 ASSERT_NE(nullptr, callee_video_content);
1387 EXPECT_TRUE(callee_video_content->rejected);
1388 // Now negotiate with video and ensure negotiation succeeds, with video
1389 // frames and additional audio frames being received.
1390 callee()->AddMediaStreamFromTracksWithLabel(
1391 nullptr, callee()->CreateLocalVideoTrack(), "video_only_stream");
1392 options.offer_to_receive_video = 1;
1393 callee()->SetOfferAnswerOptions(options);
1394 callee()->CreateAndSetAndSignalOffer();
1395 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1396 // Expect additional audio frames to be received after the upgrade.
1397 ExpectNewFramesReceivedWithWait(
1398 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1399 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1400 kMaxWaitForFramesMs);
1401}
1402
1403// This test sets up a call that's transferred to a new caller with a different
1404// DTLS fingerprint.
1405TEST_F(PeerConnectionIntegrationTest, CallTransferredForCallee) {
1406 ASSERT_TRUE(CreatePeerConnectionWrappers());
1407 ConnectFakeSignaling();
1408 caller()->AddAudioVideoMediaStream();
1409 callee()->AddAudioVideoMediaStream();
1410 caller()->CreateAndSetAndSignalOffer();
1411 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1412
1413 // Keep the original peer around which will still send packets to the
1414 // receiving client. These SRTP packets will be dropped.
1415 std::unique_ptr<PeerConnectionWrapper> original_peer(
1416 SetCallerPcWrapperAndReturnCurrent(
1417 CreatePeerConnectionWrapperWithAlternateKey()));
1418 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1419 // directly above.
1420 original_peer->pc()->Close();
1421
1422 ConnectFakeSignaling();
1423 caller()->AddAudioVideoMediaStream();
1424 caller()->CreateAndSetAndSignalOffer();
1425 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1426 // Wait for some additional frames to be transmitted end-to-end.
1427 ExpectNewFramesReceivedWithWait(
1428 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1429 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1430 kMaxWaitForFramesMs);
1431}
1432
1433// This test sets up a call that's transferred to a new callee with a different
1434// DTLS fingerprint.
1435TEST_F(PeerConnectionIntegrationTest, CallTransferredForCaller) {
1436 ASSERT_TRUE(CreatePeerConnectionWrappers());
1437 ConnectFakeSignaling();
1438 caller()->AddAudioVideoMediaStream();
1439 callee()->AddAudioVideoMediaStream();
1440 caller()->CreateAndSetAndSignalOffer();
1441 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1442
1443 // Keep the original peer around which will still send packets to the
1444 // receiving client. These SRTP packets will be dropped.
1445 std::unique_ptr<PeerConnectionWrapper> original_peer(
1446 SetCalleePcWrapperAndReturnCurrent(
1447 CreatePeerConnectionWrapperWithAlternateKey()));
1448 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1449 // directly above.
1450 original_peer->pc()->Close();
1451
1452 ConnectFakeSignaling();
1453 callee()->AddAudioVideoMediaStream();
1454 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1455 caller()->CreateAndSetAndSignalOffer();
1456 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1457 // Wait for some additional frames to be transmitted end-to-end.
1458 ExpectNewFramesReceivedWithWait(
1459 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1460 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1461 kMaxWaitForFramesMs);
1462}
1463
1464// This test sets up a non-bundled call and negotiates bundling at the same
1465// time as starting an ICE restart. When bundling is in effect in the restart,
1466// the DTLS-SRTP context should be successfully reset.
1467TEST_F(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
1468 ASSERT_TRUE(CreatePeerConnectionWrappers());
1469 ConnectFakeSignaling();
1470
1471 caller()->AddAudioVideoMediaStream();
1472 callee()->AddAudioVideoMediaStream();
1473 // Remove the bundle group from the SDP received by the callee.
1474 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1475 desc->RemoveGroupByName("BUNDLE");
1476 });
1477 caller()->CreateAndSetAndSignalOffer();
1478 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1479 ExpectNewFramesReceivedWithWait(
1480 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1481 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1482 kMaxWaitForFramesMs);
1483
1484 // Now stop removing the BUNDLE group, and trigger an ICE restart.
1485 callee()->SetReceivedSdpMunger(nullptr);
1486 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
1487 caller()->CreateAndSetAndSignalOffer();
1488 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1489
1490 // Expect additional frames to be received after the ICE restart.
1491 ExpectNewFramesReceivedWithWait(
1492 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1493 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1494 kMaxWaitForFramesMs);
1495}
1496
1497// Test CVO (Coordination of Video Orientation). If a video source is rotated
1498// and both peers support the CVO RTP header extension, the actual video frames
1499// don't need to be encoded in different resolutions, since the rotation is
1500// communicated through the RTP header extension.
1501TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
1502 ASSERT_TRUE(CreatePeerConnectionWrappers());
1503 ConnectFakeSignaling();
1504 // Add rotated video tracks.
1505 caller()->AddMediaStreamFromTracks(
1506 nullptr,
1507 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
1508 callee()->AddMediaStreamFromTracks(
1509 nullptr,
1510 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1511
1512 // Wait for video frames to be received by both sides.
1513 caller()->CreateAndSetAndSignalOffer();
1514 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1515 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1516 callee()->min_video_frames_received_per_track() > 0,
1517 kMaxWaitForFramesMs);
1518
1519 // Ensure that the aspect ratio is unmodified.
1520 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1521 // not just assumed.
1522 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
1523 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
1524 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
1525 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
1526 // Ensure that the CVO bits were surfaced to the renderer.
1527 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
1528 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
1529}
1530
1531// Test that when the CVO extension isn't supported, video is rotated the
1532// old-fashioned way, by encoding rotated frames.
1533TEST_F(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
1534 ASSERT_TRUE(CreatePeerConnectionWrappers());
1535 ConnectFakeSignaling();
1536 // Add rotated video tracks.
1537 caller()->AddMediaStreamFromTracks(
1538 nullptr,
1539 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
1540 callee()->AddMediaStreamFromTracks(
1541 nullptr,
1542 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
1543
1544 // Remove the CVO extension from the offered SDP.
1545 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
1546 cricket::VideoContentDescription* video =
1547 GetFirstVideoContentDescription(desc);
1548 video->ClearRtpHeaderExtensions();
1549 });
1550 // Wait for video frames to be received by both sides.
1551 caller()->CreateAndSetAndSignalOffer();
1552 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1553 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1554 callee()->min_video_frames_received_per_track() > 0,
1555 kMaxWaitForFramesMs);
1556
1557 // Expect that the aspect ratio is inversed to account for the 90/270 degree
1558 // rotation.
1559 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
1560 // not just assumed.
1561 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
1562 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
1563 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
1564 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
1565 // Expect that each endpoint is unaware of the rotation of the other endpoint.
1566 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
1567 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
1568}
1569
1570// TODO(deadbeef): The tests below rely on RTCOfferAnswerOptions to reject an
1571// m= section. When we implement Unified Plan SDP, the right way to do this
1572// would be by stopping an RtpTransceiver.
1573
1574// Test that if the answerer rejects the audio m= section, no audio is sent or
1575// received, but video still can be.
1576TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
1577 ASSERT_TRUE(CreatePeerConnectionWrappers());
1578 ConnectFakeSignaling();
1579 caller()->AddAudioVideoMediaStream();
1580 // Only add video track for callee, and set offer_to_receive_audio to 0, so
1581 // it will reject the audio m= section completely.
1582 PeerConnectionInterface::RTCOfferAnswerOptions options;
1583 options.offer_to_receive_audio = 0;
1584 callee()->SetOfferAnswerOptions(options);
1585 callee()->AddMediaStreamFromTracks(nullptr,
1586 callee()->CreateLocalVideoTrack());
1587 // Do offer/answer and wait for successful end-to-end video frames.
1588 caller()->CreateAndSetAndSignalOffer();
1589 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1590 ExpectNewFramesReceivedWithWait(0, kDefaultExpectedVideoFrameCount, 0,
1591 kDefaultExpectedVideoFrameCount,
1592 kMaxWaitForFramesMs);
1593 // Shouldn't have received audio frames at any point.
1594 EXPECT_EQ(0, caller()->audio_frames_received());
1595 EXPECT_EQ(0, callee()->audio_frames_received());
1596 // Sanity check that the callee's description has a rejected audio section.
1597 ASSERT_NE(nullptr, callee()->pc()->local_description());
1598 const ContentInfo* callee_audio_content =
1599 GetFirstAudioContent(callee()->pc()->local_description()->description());
1600 ASSERT_NE(nullptr, callee_audio_content);
1601 EXPECT_TRUE(callee_audio_content->rejected);
1602}
1603
1604// Test that if the answerer rejects the video m= section, no video is sent or
1605// received, but audio still can be.
1606TEST_F(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
1607 ASSERT_TRUE(CreatePeerConnectionWrappers());
1608 ConnectFakeSignaling();
1609 caller()->AddAudioVideoMediaStream();
1610 // Only add audio track for callee, and set offer_to_receive_video to 0, so
1611 // it will reject the video m= section completely.
1612 PeerConnectionInterface::RTCOfferAnswerOptions options;
1613 options.offer_to_receive_video = 0;
1614 callee()->SetOfferAnswerOptions(options);
1615 callee()->AddMediaStreamFromTracks(callee()->CreateLocalAudioTrack(),
1616 nullptr);
1617 // Do offer/answer and wait for successful end-to-end audio frames.
1618 caller()->CreateAndSetAndSignalOffer();
1619 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1620 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1621 kDefaultExpectedAudioFrameCount, 0,
1622 kMaxWaitForFramesMs);
1623 // Shouldn't have received video frames at any point.
1624 EXPECT_EQ(0, caller()->total_video_frames_received());
1625 EXPECT_EQ(0, callee()->total_video_frames_received());
1626 // Sanity check that the callee's description has a rejected video section.
1627 ASSERT_NE(nullptr, callee()->pc()->local_description());
1628 const ContentInfo* callee_video_content =
1629 GetFirstVideoContent(callee()->pc()->local_description()->description());
1630 ASSERT_NE(nullptr, callee_video_content);
1631 EXPECT_TRUE(callee_video_content->rejected);
1632}
1633
1634// Test that if the answerer rejects both audio and video m= sections, nothing
1635// bad happens.
1636// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
1637// test anything but the fact that negotiation succeeds, which doesn't mean
1638// much.
1639TEST_F(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
1640 ASSERT_TRUE(CreatePeerConnectionWrappers());
1641 ConnectFakeSignaling();
1642 caller()->AddAudioVideoMediaStream();
1643 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
1644 // will reject both audio and video m= sections.
1645 PeerConnectionInterface::RTCOfferAnswerOptions options;
1646 options.offer_to_receive_audio = 0;
1647 options.offer_to_receive_video = 0;
1648 callee()->SetOfferAnswerOptions(options);
1649 // Do offer/answer and wait for stable signaling state.
1650 caller()->CreateAndSetAndSignalOffer();
1651 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1652 // Sanity check that the callee's description has rejected m= sections.
1653 ASSERT_NE(nullptr, callee()->pc()->local_description());
1654 const ContentInfo* callee_audio_content =
1655 GetFirstAudioContent(callee()->pc()->local_description()->description());
1656 ASSERT_NE(nullptr, callee_audio_content);
1657 EXPECT_TRUE(callee_audio_content->rejected);
1658 const ContentInfo* callee_video_content =
1659 GetFirstVideoContent(callee()->pc()->local_description()->description());
1660 ASSERT_NE(nullptr, callee_video_content);
1661 EXPECT_TRUE(callee_video_content->rejected);
1662}
1663
1664// This test sets up an audio and video call between two parties. After the
1665// call runs for a while, the caller sends an updated offer with video being
1666// rejected. Once the re-negotiation is done, the video flow should stop and
1667// the audio flow should continue.
1668TEST_F(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
1669 ASSERT_TRUE(CreatePeerConnectionWrappers());
1670 ConnectFakeSignaling();
1671 caller()->AddAudioVideoMediaStream();
1672 callee()->AddAudioVideoMediaStream();
1673 caller()->CreateAndSetAndSignalOffer();
1674 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1675 ExpectNewFramesReceivedWithWait(
1676 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1677 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1678 kMaxWaitForFramesMs);
1679
1680 // Renegotiate, rejecting the video m= section.
1681 // TODO(deadbeef): When an RtpTransceiver API is available, use that to
1682 // reject the video m= section.
1683 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
1684 for (cricket::ContentInfo& content : description->contents()) {
1685 if (cricket::IsVideoContent(&content)) {
1686 content.rejected = true;
1687 }
1688 }
1689 });
1690 caller()->CreateAndSetAndSignalOffer();
1691 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
1692
1693 // Sanity check that the caller's description has a rejected video section.
1694 ASSERT_NE(nullptr, caller()->pc()->local_description());
1695 const ContentInfo* caller_video_content =
1696 GetFirstVideoContent(caller()->pc()->local_description()->description());
1697 ASSERT_NE(nullptr, caller_video_content);
1698 EXPECT_TRUE(caller_video_content->rejected);
1699
1700 int caller_video_received = caller()->total_video_frames_received();
1701 int callee_video_received = callee()->total_video_frames_received();
1702
1703 // Wait for some additional audio frames to be received.
1704 ExpectNewFramesReceivedWithWait(kDefaultExpectedAudioFrameCount, 0,
1705 kDefaultExpectedAudioFrameCount, 0,
1706 kMaxWaitForFramesMs);
1707
1708 // During this time, we shouldn't have received any additional video frames
1709 // for the rejected video tracks.
1710 EXPECT_EQ(caller_video_received, caller()->total_video_frames_received());
1711 EXPECT_EQ(callee_video_received, callee()->total_video_frames_received());
1712}
1713
1714// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
1715// is needed to support legacy endpoints.
1716// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
1717// add a test for an end-to-end test without MID signaling either (basically,
1718// the minimum acceptable SDP).
1719TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
1720 ASSERT_TRUE(CreatePeerConnectionWrappers());
1721 ConnectFakeSignaling();
1722 // Add audio and video, testing that packets can be demuxed on payload type.
1723 caller()->AddAudioVideoMediaStream();
1724 callee()->AddAudioVideoMediaStream();
deadbeefd8ad7882017-04-18 16:01:17 -07001725 // Remove SSRCs and MSIDs from the received offer SDP.
1726 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07001727 caller()->CreateAndSetAndSignalOffer();
1728 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1729 ExpectNewFramesReceivedWithWait(
1730 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1731 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1732 kMaxWaitForFramesMs);
1733}
1734
1735// Test that if two video tracks are sent (from caller to callee, in this test),
1736// they're transmitted correctly end-to-end.
1737TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
1738 ASSERT_TRUE(CreatePeerConnectionWrappers());
1739 ConnectFakeSignaling();
1740 // Add one audio/video stream, and one video-only stream.
1741 caller()->AddAudioVideoMediaStream();
1742 caller()->AddMediaStreamFromTracksWithLabel(
1743 nullptr, caller()->CreateLocalVideoTrackWithId("extra_track"),
1744 "extra_stream");
1745 caller()->CreateAndSetAndSignalOffer();
1746 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1747 ASSERT_EQ(2u, callee()->number_of_remote_streams());
1748 int expected_callee_received_frames = kDefaultExpectedVideoFrameCount;
1749 ExpectNewFramesReceivedWithWait(0, 0, 0, expected_callee_received_frames,
1750 kMaxWaitForFramesMs);
1751}
1752
1753static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
1754 bool first = true;
1755 for (cricket::ContentInfo& content : desc->contents()) {
1756 if (first) {
1757 first = false;
1758 continue;
1759 }
1760 content.bundle_only = true;
1761 }
1762 first = true;
1763 for (cricket::TransportInfo& transport : desc->transport_infos()) {
1764 if (first) {
1765 first = false;
1766 continue;
1767 }
1768 transport.description.ice_ufrag.clear();
1769 transport.description.ice_pwd.clear();
1770 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
1771 transport.description.identity_fingerprint.reset(nullptr);
1772 }
1773}
1774
1775// Test that if applying a true "max bundle" offer, which uses ports of 0,
1776// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
1777// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
1778// successfully and media flows.
1779// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
1780// TODO(deadbeef): Won't need this test once we start generating actual
1781// standards-compliant SDP.
1782TEST_F(PeerConnectionIntegrationTest,
1783 EndToEndCallWithSpecCompliantMaxBundleOffer) {
1784 ASSERT_TRUE(CreatePeerConnectionWrappers());
1785 ConnectFakeSignaling();
1786 caller()->AddAudioVideoMediaStream();
1787 callee()->AddAudioVideoMediaStream();
1788 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
1789 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
1790 // but the first m= section.
1791 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
1792 caller()->CreateAndSetAndSignalOffer();
1793 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1794 ExpectNewFramesReceivedWithWait(
1795 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1796 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1797 kMaxWaitForFramesMs);
1798}
1799
1800// Test that we can receive the audio output level from a remote audio track.
1801// TODO(deadbeef): Use a fake audio source and verify that the output level is
1802// exactly what the source on the other side was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001803TEST_F(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001804 ASSERT_TRUE(CreatePeerConnectionWrappers());
1805 ConnectFakeSignaling();
1806 // Just add an audio track.
1807 caller()->AddMediaStreamFromTracks(caller()->CreateLocalAudioTrack(),
1808 nullptr);
1809 caller()->CreateAndSetAndSignalOffer();
1810 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1811
1812 // Get the audio output level stats. Note that the level is not available
1813 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07001814 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001815 kMaxWaitForFramesMs);
1816}
1817
1818// Test that an audio input level is reported.
1819// TODO(deadbeef): Use a fake audio source and verify that the input level is
1820// exactly what the source was configured with.
deadbeefd8ad7882017-04-18 16:01:17 -07001821TEST_F(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001822 ASSERT_TRUE(CreatePeerConnectionWrappers());
1823 ConnectFakeSignaling();
1824 // Just add an audio track.
1825 caller()->AddMediaStreamFromTracks(caller()->CreateLocalAudioTrack(),
1826 nullptr);
1827 caller()->CreateAndSetAndSignalOffer();
1828 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1829
1830 // Get the audio input level stats. The level should be available very
1831 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07001832 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07001833 kMaxWaitForStatsMs);
1834}
1835
1836// Test that we can get incoming byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001837TEST_F(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001838 ASSERT_TRUE(CreatePeerConnectionWrappers());
1839 ConnectFakeSignaling();
1840 caller()->AddAudioVideoMediaStream();
1841 // Do offer/answer, wait for the callee to receive some frames.
1842 caller()->CreateAndSetAndSignalOffer();
1843 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1844 int expected_caller_received_frames = 0;
1845 ExpectNewFramesReceivedWithWait(
1846 expected_caller_received_frames, expected_caller_received_frames,
1847 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1848 kMaxWaitForFramesMs);
1849
1850 // Get a handle to the remote tracks created, so they can be used as GetStats
1851 // filters.
1852 StreamCollectionInterface* remote_streams = callee()->remote_streams();
1853 ASSERT_EQ(1u, remote_streams->count());
1854 ASSERT_EQ(1u, remote_streams->at(0)->GetAudioTracks().size());
1855 ASSERT_EQ(1u, remote_streams->at(0)->GetVideoTracks().size());
1856 MediaStreamTrackInterface* remote_audio_track =
1857 remote_streams->at(0)->GetAudioTracks()[0];
1858 MediaStreamTrackInterface* remote_video_track =
1859 remote_streams->at(0)->GetVideoTracks()[0];
1860
1861 // We received frames, so we definitely should have nonzero "received bytes"
1862 // stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07001863 EXPECT_GT(callee()->OldGetStatsForTrack(remote_audio_track)->BytesReceived(),
1864 0);
1865 EXPECT_GT(callee()->OldGetStatsForTrack(remote_video_track)->BytesReceived(),
1866 0);
deadbeef1dcb1642017-03-29 21:08:16 -07001867}
1868
1869// Test that we can get outgoing byte counts from both audio and video tracks.
deadbeefd8ad7882017-04-18 16:01:17 -07001870TEST_F(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07001871 ASSERT_TRUE(CreatePeerConnectionWrappers());
1872 ConnectFakeSignaling();
1873 auto audio_track = caller()->CreateLocalAudioTrack();
1874 auto video_track = caller()->CreateLocalVideoTrack();
1875 caller()->AddMediaStreamFromTracks(audio_track, video_track);
1876 // Do offer/answer, wait for the callee to receive some frames.
1877 caller()->CreateAndSetAndSignalOffer();
1878 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1879 int expected_caller_received_frames = 0;
1880 ExpectNewFramesReceivedWithWait(
1881 expected_caller_received_frames, expected_caller_received_frames,
1882 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1883 kMaxWaitForFramesMs);
1884
1885 // The callee received frames, so we definitely should have nonzero "sent
1886 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07001887 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
1888 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
1889}
1890
1891// Test that we can get stats (using the new stats implemnetation) for
1892// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
1893// SDP.
1894TEST_F(PeerConnectionIntegrationTest,
1895 GetStatsForUnsignaledStreamWithNewStatsApi) {
1896 ASSERT_TRUE(CreatePeerConnectionWrappers());
1897 ConnectFakeSignaling();
1898 caller()->AddAudioOnlyMediaStream();
1899 // Remove SSRCs and MSIDs from the received offer SDP.
1900 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
1901 caller()->CreateAndSetAndSignalOffer();
1902 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1903 // Wait for one audio frame to be received by the callee.
1904 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
1905
1906 // We received a frame, so we should have nonzero "bytes received" stats for
1907 // the unsignaled stream, if stats are working for it.
1908 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
1909 callee()->NewGetStats();
1910 ASSERT_NE(nullptr, report);
1911 auto inbound_stream_stats =
1912 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
1913 ASSERT_EQ(1U, inbound_stream_stats.size());
1914 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
1915 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
1916 // TODO(deadbeef): Test that track_id is defined. This is not currently
1917 // working since SSRCs are used to match RtpReceivers (and their tracks) with
1918 // received stream stats in TrackMediaInfoMap.
deadbeef1dcb1642017-03-29 21:08:16 -07001919}
1920
1921// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
1922TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
1923 PeerConnectionFactory::Options dtls_10_options;
1924 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
1925 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
1926 dtls_10_options));
1927 ConnectFakeSignaling();
1928 // Do normal offer/answer and wait for some frames to be received in each
1929 // direction.
1930 caller()->AddAudioVideoMediaStream();
1931 callee()->AddAudioVideoMediaStream();
1932 caller()->CreateAndSetAndSignalOffer();
1933 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1934 ExpectNewFramesReceivedWithWait(
1935 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1936 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
1937 kMaxWaitForFramesMs);
1938}
1939
1940// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
1941TEST_F(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
1942 PeerConnectionFactory::Options dtls_10_options;
1943 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
1944 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
1945 dtls_10_options));
1946 ConnectFakeSignaling();
1947 // Register UMA observer before signaling begins.
1948 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1949 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1950 caller()->pc()->RegisterUMAObserver(caller_observer);
1951 caller()->AddAudioVideoMediaStream();
1952 callee()->AddAudioVideoMediaStream();
1953 caller()->CreateAndSetAndSignalOffer();
1954 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1955 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07001956 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07001957 kDefaultTimeout);
1958 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07001959 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001960 EXPECT_EQ(1,
1961 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1962 kDefaultSrtpCryptoSuite));
1963}
1964
1965// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
1966TEST_F(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
1967 PeerConnectionFactory::Options dtls_12_options;
1968 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
1969 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
1970 dtls_12_options));
1971 ConnectFakeSignaling();
1972 // Register UMA observer before signaling begins.
1973 rtc::scoped_refptr<webrtc::FakeMetricsObserver> caller_observer =
1974 new rtc::RefCountedObject<webrtc::FakeMetricsObserver>();
1975 caller()->pc()->RegisterUMAObserver(caller_observer);
1976 caller()->AddAudioVideoMediaStream();
1977 callee()->AddAudioVideoMediaStream();
1978 caller()->CreateAndSetAndSignalOffer();
1979 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1980 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07001981 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07001982 kDefaultTimeout);
1983 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07001984 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001985 EXPECT_EQ(1,
1986 caller_observer->GetEnumCounter(webrtc::kEnumCounterAudioSrtpCipher,
1987 kDefaultSrtpCryptoSuite));
1988}
1989
1990// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
1991// callee only supports 1.0.
1992TEST_F(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
1993 PeerConnectionFactory::Options caller_options;
1994 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
1995 PeerConnectionFactory::Options callee_options;
1996 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
1997 ASSERT_TRUE(
1998 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
1999 ConnectFakeSignaling();
2000 // Do normal offer/answer and wait for some frames to be received in each
2001 // direction.
2002 caller()->AddAudioVideoMediaStream();
2003 callee()->AddAudioVideoMediaStream();
2004 caller()->CreateAndSetAndSignalOffer();
2005 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2006 ExpectNewFramesReceivedWithWait(
2007 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2008 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2009 kMaxWaitForFramesMs);
2010}
2011
2012// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2013// callee supports 1.2.
2014TEST_F(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
2015 PeerConnectionFactory::Options caller_options;
2016 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2017 PeerConnectionFactory::Options callee_options;
2018 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2019 ASSERT_TRUE(
2020 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2021 ConnectFakeSignaling();
2022 // Do normal offer/answer and wait for some frames to be received in each
2023 // direction.
2024 caller()->AddAudioVideoMediaStream();
2025 callee()->AddAudioVideoMediaStream();
2026 caller()->CreateAndSetAndSignalOffer();
2027 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2028 ExpectNewFramesReceivedWithWait(
2029 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2030 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2031 kMaxWaitForFramesMs);
2032}
2033
2034// Test that a non-GCM cipher is used if both sides only support non-GCM.
2035TEST_F(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
2036 bool local_gcm_enabled = false;
2037 bool remote_gcm_enabled = false;
2038 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2039 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2040 expected_cipher_suite);
2041}
2042
2043// Test that a GCM cipher is used if both ends support it.
2044TEST_F(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
2045 bool local_gcm_enabled = true;
2046 bool remote_gcm_enabled = true;
2047 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
2048 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2049 expected_cipher_suite);
2050}
2051
2052// Test that GCM isn't used if only the offerer supports it.
2053TEST_F(PeerConnectionIntegrationTest,
2054 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
2055 bool local_gcm_enabled = true;
2056 bool remote_gcm_enabled = false;
2057 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2058 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2059 expected_cipher_suite);
2060}
2061
2062// Test that GCM isn't used if only the answerer supports it.
2063TEST_F(PeerConnectionIntegrationTest,
2064 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
2065 bool local_gcm_enabled = false;
2066 bool remote_gcm_enabled = true;
2067 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
2068 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
2069 expected_cipher_suite);
2070}
2071
2072// This test sets up a call between two parties with audio, video and an RTP
2073// data channel.
2074TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
2075 FakeConstraints setup_constraints;
2076 setup_constraints.SetAllowRtpDataChannels();
2077 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2078 &setup_constraints));
2079 ConnectFakeSignaling();
2080 // Expect that data channel created on caller side will show up for callee as
2081 // well.
2082 caller()->CreateDataChannel();
2083 caller()->AddAudioVideoMediaStream();
2084 callee()->AddAudioVideoMediaStream();
2085 caller()->CreateAndSetAndSignalOffer();
2086 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2087 // Ensure the existence of the RTP data channel didn't impede audio/video.
2088 ExpectNewFramesReceivedWithWait(
2089 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2090 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2091 kMaxWaitForFramesMs);
2092 ASSERT_NE(nullptr, caller()->data_channel());
2093 ASSERT_NE(nullptr, callee()->data_channel());
2094 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2095 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2096
2097 // Ensure data can be sent in both directions.
2098 std::string data = "hello world";
2099 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2100 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2101 kDefaultTimeout);
2102 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2103 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2104 kDefaultTimeout);
2105}
2106
2107// Ensure that an RTP data channel is signaled as closed for the caller when
2108// the callee rejects it in a subsequent offer.
2109TEST_F(PeerConnectionIntegrationTest,
2110 RtpDataChannelSignaledClosedInCalleeOffer) {
2111 // Same procedure as above test.
2112 FakeConstraints setup_constraints;
2113 setup_constraints.SetAllowRtpDataChannels();
2114 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2115 &setup_constraints));
2116 ConnectFakeSignaling();
2117 caller()->CreateDataChannel();
2118 caller()->AddAudioVideoMediaStream();
2119 callee()->AddAudioVideoMediaStream();
2120 caller()->CreateAndSetAndSignalOffer();
2121 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2122 ASSERT_NE(nullptr, caller()->data_channel());
2123 ASSERT_NE(nullptr, callee()->data_channel());
2124 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2125 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2126
2127 // Close the data channel on the callee, and do an updated offer/answer.
2128 callee()->data_channel()->Close();
2129 callee()->CreateAndSetAndSignalOffer();
2130 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2131 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2132 EXPECT_FALSE(callee()->data_observer()->IsOpen());
2133}
2134
2135// Tests that data is buffered in an RTP data channel until an observer is
2136// registered for it.
2137//
2138// NOTE: RTP data channels can receive data before the underlying
2139// transport has detected that a channel is writable and thus data can be
2140// received before the data channel state changes to open. That is hard to test
2141// but the same buffering is expected to be used in that case.
2142TEST_F(PeerConnectionIntegrationTest,
2143 DataBufferedUntilRtpDataChannelObserverRegistered) {
2144 // Use fake clock and simulated network delay so that we predictably can wait
2145 // until an SCTP message has been delivered without "sleep()"ing.
2146 rtc::ScopedFakeClock fake_clock;
2147 // Some things use a time of "0" as a special value, so we need to start out
2148 // the fake clock at a nonzero time.
2149 // TODO(deadbeef): Fix this.
2150 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2151 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
2152 virtual_socket_server()->UpdateDelayDistribution();
2153
2154 FakeConstraints constraints;
2155 constraints.SetAllowRtpDataChannels();
2156 ASSERT_TRUE(
2157 CreatePeerConnectionWrappersWithConstraints(&constraints, &constraints));
2158 ConnectFakeSignaling();
2159 caller()->CreateDataChannel();
2160 caller()->CreateAndSetAndSignalOffer();
2161 ASSERT_TRUE(caller()->data_channel() != nullptr);
2162 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
2163 kDefaultTimeout, fake_clock);
2164 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
2165 kDefaultTimeout, fake_clock);
2166 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
2167 callee()->data_channel()->state(), kDefaultTimeout,
2168 fake_clock);
2169
2170 // Unregister the observer which is normally automatically registered.
2171 callee()->data_channel()->UnregisterObserver();
2172 // Send data and advance fake clock until it should have been received.
2173 std::string data = "hello world";
2174 caller()->data_channel()->Send(DataBuffer(data));
2175 SIMULATED_WAIT(false, 50, fake_clock);
2176
2177 // Attach data channel and expect data to be received immediately. Note that
2178 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
2179 // further, but data can be received even if the callback is asynchronous.
2180 MockDataChannelObserver new_observer(callee()->data_channel());
2181 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
2182 fake_clock);
2183}
2184
2185// This test sets up a call between two parties with audio, video and but only
2186// the caller client supports RTP data channels.
2187TEST_F(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
2188 FakeConstraints setup_constraints_1;
2189 setup_constraints_1.SetAllowRtpDataChannels();
2190 // Must disable DTLS to make negotiation succeed.
2191 setup_constraints_1.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2192 false);
2193 FakeConstraints setup_constraints_2;
2194 setup_constraints_2.SetMandatory(MediaConstraintsInterface::kEnableDtlsSrtp,
2195 false);
2196 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(
2197 &setup_constraints_1, &setup_constraints_2));
2198 ConnectFakeSignaling();
2199 caller()->CreateDataChannel();
2200 caller()->AddAudioVideoMediaStream();
2201 callee()->AddAudioVideoMediaStream();
2202 caller()->CreateAndSetAndSignalOffer();
2203 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2204 // The caller should still have a data channel, but it should be closed, and
2205 // one should ever have been created for the callee.
2206 EXPECT_TRUE(caller()->data_channel() != nullptr);
2207 EXPECT_FALSE(caller()->data_observer()->IsOpen());
2208 EXPECT_EQ(nullptr, callee()->data_channel());
2209}
2210
2211// This test sets up a call between two parties with audio, and video. When
2212// audio and video is setup and flowing, an RTP data channel is negotiated.
2213TEST_F(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
2214 FakeConstraints setup_constraints;
2215 setup_constraints.SetAllowRtpDataChannels();
2216 ASSERT_TRUE(CreatePeerConnectionWrappersWithConstraints(&setup_constraints,
2217 &setup_constraints));
2218 ConnectFakeSignaling();
2219 // Do initial offer/answer with audio/video.
2220 caller()->AddAudioVideoMediaStream();
2221 callee()->AddAudioVideoMediaStream();
2222 caller()->CreateAndSetAndSignalOffer();
2223 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2224 // Create data channel and do new offer and answer.
2225 caller()->CreateDataChannel();
2226 caller()->CreateAndSetAndSignalOffer();
2227 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2228 ASSERT_NE(nullptr, caller()->data_channel());
2229 ASSERT_NE(nullptr, callee()->data_channel());
2230 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2231 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2232 // Ensure data can be sent in both directions.
2233 std::string data = "hello world";
2234 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
2235 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2236 kDefaultTimeout);
2237 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
2238 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2239 kDefaultTimeout);
2240}
2241
2242#ifdef HAVE_SCTP
2243
2244// This test sets up a call between two parties with audio, video and an SCTP
2245// data channel.
2246TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
2247 ASSERT_TRUE(CreatePeerConnectionWrappers());
2248 ConnectFakeSignaling();
2249 // Expect that data channel created on caller side will show up for callee as
2250 // well.
2251 caller()->CreateDataChannel();
2252 caller()->AddAudioVideoMediaStream();
2253 callee()->AddAudioVideoMediaStream();
2254 caller()->CreateAndSetAndSignalOffer();
2255 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2256 // Ensure the existence of the SCTP data channel didn't impede audio/video.
2257 ExpectNewFramesReceivedWithWait(
2258 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2259 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2260 kMaxWaitForFramesMs);
2261 // Caller data channel should already exist (it created one). Callee data
2262 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2263 ASSERT_NE(nullptr, caller()->data_channel());
2264 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2265 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2266 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2267
2268 // Ensure data can be sent in both directions.
2269 std::string data = "hello world";
2270 caller()->data_channel()->Send(DataBuffer(data));
2271 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2272 kDefaultTimeout);
2273 callee()->data_channel()->Send(DataBuffer(data));
2274 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2275 kDefaultTimeout);
2276}
2277
2278// Ensure that when the callee closes an SCTP data channel, the closing
2279// procedure results in the data channel being closed for the caller as well.
2280TEST_F(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
2281 // Same procedure as above test.
2282 ASSERT_TRUE(CreatePeerConnectionWrappers());
2283 ConnectFakeSignaling();
2284 caller()->CreateDataChannel();
2285 caller()->AddAudioVideoMediaStream();
2286 callee()->AddAudioVideoMediaStream();
2287 caller()->CreateAndSetAndSignalOffer();
2288 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2289 ASSERT_NE(nullptr, caller()->data_channel());
2290 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2291 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2292 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2293
2294 // Close the data channel on the callee side, and wait for it to reach the
2295 // "closed" state on both sides.
2296 callee()->data_channel()->Close();
2297 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
2298 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
2299}
2300
2301// Test usrsctp's ability to process unordered data stream, where data actually
2302// arrives out of order using simulated delays. Previously there have been some
2303// bugs in this area.
2304TEST_F(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
2305 // Introduce random network delays.
2306 // Otherwise it's not a true "unordered" test.
2307 virtual_socket_server()->set_delay_mean(20);
2308 virtual_socket_server()->set_delay_stddev(5);
2309 virtual_socket_server()->UpdateDelayDistribution();
2310 // Normal procedure, but with unordered data channel config.
2311 ASSERT_TRUE(CreatePeerConnectionWrappers());
2312 ConnectFakeSignaling();
2313 webrtc::DataChannelInit init;
2314 init.ordered = false;
2315 caller()->CreateDataChannel(&init);
2316 caller()->CreateAndSetAndSignalOffer();
2317 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2318 ASSERT_NE(nullptr, caller()->data_channel());
2319 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2320 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2321 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2322
2323 static constexpr int kNumMessages = 100;
2324 // Deliberately chosen to be larger than the MTU so messages get fragmented.
2325 static constexpr size_t kMaxMessageSize = 4096;
2326 // Create and send random messages.
2327 std::vector<std::string> sent_messages;
2328 for (int i = 0; i < kNumMessages; ++i) {
2329 size_t length =
2330 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
2331 std::string message;
2332 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
2333 caller()->data_channel()->Send(DataBuffer(message));
2334 callee()->data_channel()->Send(DataBuffer(message));
2335 sent_messages.push_back(message);
2336 }
2337
2338 // Wait for all messages to be received.
2339 EXPECT_EQ_WAIT(kNumMessages,
2340 caller()->data_observer()->received_message_count(),
2341 kDefaultTimeout);
2342 EXPECT_EQ_WAIT(kNumMessages,
2343 callee()->data_observer()->received_message_count(),
2344 kDefaultTimeout);
2345
2346 // Sort and compare to make sure none of the messages were corrupted.
2347 std::vector<std::string> caller_received_messages =
2348 caller()->data_observer()->messages();
2349 std::vector<std::string> callee_received_messages =
2350 callee()->data_observer()->messages();
2351 std::sort(sent_messages.begin(), sent_messages.end());
2352 std::sort(caller_received_messages.begin(), caller_received_messages.end());
2353 std::sort(callee_received_messages.begin(), callee_received_messages.end());
2354 EXPECT_EQ(sent_messages, caller_received_messages);
2355 EXPECT_EQ(sent_messages, callee_received_messages);
2356}
2357
2358// This test sets up a call between two parties with audio, and video. When
2359// audio and video are setup and flowing, an SCTP data channel is negotiated.
2360TEST_F(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
2361 ASSERT_TRUE(CreatePeerConnectionWrappers());
2362 ConnectFakeSignaling();
2363 // Do initial offer/answer with audio/video.
2364 caller()->AddAudioVideoMediaStream();
2365 callee()->AddAudioVideoMediaStream();
2366 caller()->CreateAndSetAndSignalOffer();
2367 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2368 // Create data channel and do new offer and answer.
2369 caller()->CreateDataChannel();
2370 caller()->CreateAndSetAndSignalOffer();
2371 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2372 // Caller data channel should already exist (it created one). Callee data
2373 // channel may not exist yet, since negotiation happens in-band, not in SDP.
2374 ASSERT_NE(nullptr, caller()->data_channel());
2375 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
2376 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
2377 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
2378 // Ensure data can be sent in both directions.
2379 std::string data = "hello world";
2380 caller()->data_channel()->Send(DataBuffer(data));
2381 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
2382 kDefaultTimeout);
2383 callee()->data_channel()->Send(DataBuffer(data));
2384 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
2385 kDefaultTimeout);
2386}
2387
2388#endif // HAVE_SCTP
2389
2390// Test that the ICE connection and gathering states eventually reach
2391// "complete".
2392TEST_F(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
2393 ASSERT_TRUE(CreatePeerConnectionWrappers());
2394 ConnectFakeSignaling();
2395 // Do normal offer/answer.
2396 caller()->AddAudioVideoMediaStream();
2397 callee()->AddAudioVideoMediaStream();
2398 caller()->CreateAndSetAndSignalOffer();
2399 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2400 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2401 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
2402 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
2403 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
2404 // After the best candidate pair is selected and all candidates are signaled,
2405 // the ICE connection state should reach "complete".
2406 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
2407 // answerer/"callee" by default) only reaches "connected". When this is
2408 // fixed, this test should be updated.
2409 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2410 caller()->ice_connection_state(), kDefaultTimeout);
2411 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2412 callee()->ice_connection_state(), kDefaultTimeout);
2413}
2414
2415// This test sets up a call between two parties with audio and video.
2416// During the call, the caller restarts ICE and the test verifies that
2417// new ICE candidates are generated and audio and video still can flow, and the
2418// ICE state reaches completed again.
2419TEST_F(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
2420 ASSERT_TRUE(CreatePeerConnectionWrappers());
2421 ConnectFakeSignaling();
2422 // Do normal offer/answer and wait for ICE to complete.
2423 caller()->AddAudioVideoMediaStream();
2424 callee()->AddAudioVideoMediaStream();
2425 caller()->CreateAndSetAndSignalOffer();
2426 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2427 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2428 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2429 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2430 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2431
2432 // To verify that the ICE restart actually occurs, get
2433 // ufrag/password/candidates before and after restart.
2434 // Create an SDP string of the first audio candidate for both clients.
2435 const webrtc::IceCandidateCollection* audio_candidates_caller =
2436 caller()->pc()->local_description()->candidates(0);
2437 const webrtc::IceCandidateCollection* audio_candidates_callee =
2438 callee()->pc()->local_description()->candidates(0);
2439 ASSERT_GT(audio_candidates_caller->count(), 0u);
2440 ASSERT_GT(audio_candidates_callee->count(), 0u);
2441 std::string caller_candidate_pre_restart;
2442 ASSERT_TRUE(
2443 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
2444 std::string callee_candidate_pre_restart;
2445 ASSERT_TRUE(
2446 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
2447 const cricket::SessionDescription* desc =
2448 caller()->pc()->local_description()->description();
2449 std::string caller_ufrag_pre_restart =
2450 desc->transport_infos()[0].description.ice_ufrag;
2451 desc = callee()->pc()->local_description()->description();
2452 std::string callee_ufrag_pre_restart =
2453 desc->transport_infos()[0].description.ice_ufrag;
2454
2455 // Have the caller initiate an ICE restart.
2456 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2457 caller()->CreateAndSetAndSignalOffer();
2458 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2459 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2460 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2461 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2462 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2463
2464 // Grab the ufrags/candidates again.
2465 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
2466 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
2467 ASSERT_GT(audio_candidates_caller->count(), 0u);
2468 ASSERT_GT(audio_candidates_callee->count(), 0u);
2469 std::string caller_candidate_post_restart;
2470 ASSERT_TRUE(
2471 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
2472 std::string callee_candidate_post_restart;
2473 ASSERT_TRUE(
2474 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
2475 desc = caller()->pc()->local_description()->description();
2476 std::string caller_ufrag_post_restart =
2477 desc->transport_infos()[0].description.ice_ufrag;
2478 desc = callee()->pc()->local_description()->description();
2479 std::string callee_ufrag_post_restart =
2480 desc->transport_infos()[0].description.ice_ufrag;
2481 // Sanity check that an ICE restart was actually negotiated in SDP.
2482 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
2483 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
2484 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
2485 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
2486
2487 // Ensure that additional frames are received after the ICE restart.
2488 ExpectNewFramesReceivedWithWait(
2489 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2490 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2491 kMaxWaitForFramesMs);
2492}
2493
2494// Verify that audio/video can be received end-to-end when ICE renomination is
2495// enabled.
2496TEST_F(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
2497 PeerConnectionInterface::RTCConfiguration config;
2498 config.enable_ice_renomination = true;
2499 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
2500 ConnectFakeSignaling();
2501 // Do normal offer/answer and wait for some frames to be received in each
2502 // direction.
2503 caller()->AddAudioVideoMediaStream();
2504 callee()->AddAudioVideoMediaStream();
2505 caller()->CreateAndSetAndSignalOffer();
2506 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2507 // Sanity check that ICE renomination was actually negotiated.
2508 const cricket::SessionDescription* desc =
2509 caller()->pc()->local_description()->description();
2510 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07002511 ASSERT_NE(
2512 info.description.transport_options.end(),
2513 std::find(info.description.transport_options.begin(),
2514 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07002515 }
2516 desc = callee()->pc()->local_description()->description();
2517 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07002518 ASSERT_NE(
2519 info.description.transport_options.end(),
2520 std::find(info.description.transport_options.begin(),
2521 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07002522 }
2523 ExpectNewFramesReceivedWithWait(
2524 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2525 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2526 kMaxWaitForFramesMs);
2527}
2528
2529// This test sets up a call between two parties with audio and video. It then
2530// renegotiates setting the video m-line to "port 0", then later renegotiates
2531// again, enabling video.
2532TEST_F(PeerConnectionIntegrationTest,
2533 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
2534 ASSERT_TRUE(CreatePeerConnectionWrappers());
2535 ConnectFakeSignaling();
2536
2537 // Do initial negotiation, only sending media from the caller. Will result in
2538 // video and audio recvonly "m=" sections.
2539 caller()->AddAudioVideoMediaStream();
2540 caller()->CreateAndSetAndSignalOffer();
2541 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2542
2543 // Negotiate again, disabling the video "m=" section (the callee will set the
2544 // port to 0 due to offer_to_receive_video = 0).
2545 PeerConnectionInterface::RTCOfferAnswerOptions options;
2546 options.offer_to_receive_video = 0;
2547 callee()->SetOfferAnswerOptions(options);
2548 caller()->CreateAndSetAndSignalOffer();
2549 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2550 // Sanity check that video "m=" section was actually rejected.
2551 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
2552 callee()->pc()->local_description()->description());
2553 ASSERT_NE(nullptr, answer_video_content);
2554 ASSERT_TRUE(answer_video_content->rejected);
2555
2556 // Enable video and do negotiation again, making sure video is received
2557 // end-to-end, also adding media stream to callee.
2558 options.offer_to_receive_video = 1;
2559 callee()->SetOfferAnswerOptions(options);
2560 callee()->AddAudioVideoMediaStream();
2561 caller()->CreateAndSetAndSignalOffer();
2562 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2563 // Verify the caller receives frames from the newly added stream, and the
2564 // callee receives additional frames from the re-enabled video m= section.
2565 ExpectNewFramesReceivedWithWait(
2566 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2567 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2568 kMaxWaitForFramesMs);
2569}
2570
2571// This test sets up a Jsep call between two parties with external
2572// VideoDecoderFactory.
2573// TODO(holmer): Disabled due to sometimes crashing on buildbots.
2574// See issue webrtc/2378.
2575TEST_F(PeerConnectionIntegrationTest,
2576 DISABLED_EndToEndCallWithVideoDecoderFactory) {
2577 ASSERT_TRUE(CreatePeerConnectionWrappers());
2578 EnableVideoDecoderFactory();
2579 ConnectFakeSignaling();
2580 caller()->AddAudioVideoMediaStream();
2581 callee()->AddAudioVideoMediaStream();
2582 caller()->CreateAndSetAndSignalOffer();
2583 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2584 ExpectNewFramesReceivedWithWait(
2585 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2586 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2587 kMaxWaitForFramesMs);
2588}
2589
2590// This tests that if we negotiate after calling CreateSender but before we
2591// have a track, then set a track later, frames from the newly-set track are
2592// received end-to-end.
2593// TODO(deadbeef): Change this test to use AddTransceiver, once that's
2594// implemented.
2595TEST_F(PeerConnectionIntegrationTest,
2596 MediaFlowsAfterEarlyWarmupWithCreateSender) {
2597 ASSERT_TRUE(CreatePeerConnectionWrappers());
2598 ConnectFakeSignaling();
2599 auto caller_audio_sender =
2600 caller()->pc()->CreateSender("audio", "caller_stream");
2601 auto caller_video_sender =
2602 caller()->pc()->CreateSender("video", "caller_stream");
2603 auto callee_audio_sender =
2604 callee()->pc()->CreateSender("audio", "callee_stream");
2605 auto callee_video_sender =
2606 callee()->pc()->CreateSender("video", "callee_stream");
2607 caller()->CreateAndSetAndSignalOffer();
2608 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2609 // Wait for ICE to complete, without any tracks being set.
2610 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
2611 caller()->ice_connection_state(), kMaxWaitForFramesMs);
2612 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
2613 callee()->ice_connection_state(), kMaxWaitForFramesMs);
2614 // Now set the tracks, and expect frames to immediately start flowing.
2615 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
2616 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
2617 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
2618 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
2619 ExpectNewFramesReceivedWithWait(
2620 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2621 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2622 kMaxWaitForFramesMs);
2623}
2624
2625// This test verifies that a remote video track can be added via AddStream,
2626// and sent end-to-end. For this particular test, it's simply echoed back
2627// from the caller to the callee, rather than being forwarded to a third
2628// PeerConnection.
2629TEST_F(PeerConnectionIntegrationTest, CanSendRemoteVideoTrack) {
2630 ASSERT_TRUE(CreatePeerConnectionWrappers());
2631 ConnectFakeSignaling();
2632 // Just send a video track from the caller.
2633 caller()->AddMediaStreamFromTracks(nullptr,
2634 caller()->CreateLocalVideoTrack());
2635 caller()->CreateAndSetAndSignalOffer();
2636 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2637 ASSERT_EQ(1, callee()->remote_streams()->count());
2638
2639 // Echo the stream back, and do a new offer/anwer (initiated by callee this
2640 // time).
2641 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
2642 callee()->CreateAndSetAndSignalOffer();
2643 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2644
2645 int expected_caller_received_video_frames = kDefaultExpectedVideoFrameCount;
2646 ExpectNewFramesReceivedWithWait(0, expected_caller_received_video_frames, 0,
2647 0, kMaxWaitForFramesMs);
2648}
2649
2650// Test that we achieve the expected end-to-end connection time, using a
2651// fake clock and simulated latency on the media and signaling paths.
2652// We use a TURN<->TURN connection because this is usually the quickest to
2653// set up initially, especially when we're confident the connection will work
2654// and can start sending media before we get a STUN response.
2655//
2656// With various optimizations enabled, here are the network delays we expect to
2657// be on the critical path:
2658// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
2659// signaling answer (with DTLS fingerprint).
2660// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
2661// using TURN<->TURN pair, and DTLS exchange is 4 packets,
2662// the first of which should have arrived before the answer.
2663TEST_F(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
2664 rtc::ScopedFakeClock fake_clock;
2665 // Some things use a time of "0" as a special value, so we need to start out
2666 // the fake clock at a nonzero time.
2667 // TODO(deadbeef): Fix this.
2668 fake_clock.AdvanceTime(rtc::TimeDelta::FromSeconds(1));
2669
2670 static constexpr int media_hop_delay_ms = 50;
2671 static constexpr int signaling_trip_delay_ms = 500;
2672 // For explanation of these values, see comment above.
2673 static constexpr int required_media_hops = 9;
2674 static constexpr int required_signaling_trips = 2;
2675 // For internal delays (such as posting an event asychronously).
2676 static constexpr int allowed_internal_delay_ms = 20;
2677 static constexpr int total_connection_time_ms =
2678 media_hop_delay_ms * required_media_hops +
2679 signaling_trip_delay_ms * required_signaling_trips +
2680 allowed_internal_delay_ms;
2681
2682 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
2683 3478};
2684 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
2685 0};
2686 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
2687 3478};
2688 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
2689 0};
2690 cricket::TestTurnServer turn_server_1(network_thread(),
2691 turn_server_1_internal_address,
2692 turn_server_1_external_address);
2693 cricket::TestTurnServer turn_server_2(network_thread(),
2694 turn_server_2_internal_address,
2695 turn_server_2_external_address);
2696 // Bypass permission check on received packets so media can be sent before
2697 // the candidate is signaled.
2698 turn_server_1.set_enable_permission_checks(false);
2699 turn_server_2.set_enable_permission_checks(false);
2700
2701 PeerConnectionInterface::RTCConfiguration client_1_config;
2702 webrtc::PeerConnectionInterface::IceServer ice_server_1;
2703 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
2704 ice_server_1.username = "test";
2705 ice_server_1.password = "test";
2706 client_1_config.servers.push_back(ice_server_1);
2707 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
2708 client_1_config.presume_writable_when_fully_relayed = true;
2709
2710 PeerConnectionInterface::RTCConfiguration client_2_config;
2711 webrtc::PeerConnectionInterface::IceServer ice_server_2;
2712 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
2713 ice_server_2.username = "test";
2714 ice_server_2.password = "test";
2715 client_2_config.servers.push_back(ice_server_2);
2716 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
2717 client_2_config.presume_writable_when_fully_relayed = true;
2718
2719 ASSERT_TRUE(
2720 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
2721 // Set up the simulated delays.
2722 SetSignalingDelayMs(signaling_trip_delay_ms);
2723 ConnectFakeSignaling();
2724 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
2725 virtual_socket_server()->UpdateDelayDistribution();
2726
2727 // Set "offer to receive audio/video" without adding any tracks, so we just
2728 // set up ICE/DTLS with no media.
2729 PeerConnectionInterface::RTCOfferAnswerOptions options;
2730 options.offer_to_receive_audio = 1;
2731 options.offer_to_receive_video = 1;
2732 caller()->SetOfferAnswerOptions(options);
2733 caller()->CreateAndSetAndSignalOffer();
2734 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
2735 // are connected. This is an important distinction. Once we have separate ICE
2736 // and DTLS state, this check needs to use the DTLS state.
2737 EXPECT_TRUE_SIMULATED_WAIT(
2738 (callee()->ice_connection_state() ==
2739 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
2740 callee()->ice_connection_state() ==
2741 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
2742 (caller()->ice_connection_state() ==
2743 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
2744 caller()->ice_connection_state() ==
2745 webrtc::PeerConnectionInterface::kIceConnectionCompleted),
2746 total_connection_time_ms, fake_clock);
2747 // Need to free the clients here since they're using things we created on
2748 // the stack.
2749 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
2750 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
2751}
2752
deadbeefc964d0b2017-04-03 10:03:35 -07002753// Test that audio and video flow end-to-end when codec names don't use the
2754// expected casing, given that they're supposed to be case insensitive. To test
2755// this, all but one codec is removed from each media description, and its
2756// casing is changed.
2757//
2758// In the past, this has regressed and caused crashes/black video, due to the
2759// fact that code at some layers was doing case-insensitive comparisons and
2760// code at other layers was not.
2761TEST_F(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
2762 ASSERT_TRUE(CreatePeerConnectionWrappers());
2763 ConnectFakeSignaling();
2764 caller()->AddAudioVideoMediaStream();
2765 callee()->AddAudioVideoMediaStream();
2766
2767 // Remove all but one audio/video codec (opus and VP8), and change the
2768 // casing of the caller's generated offer.
2769 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
2770 cricket::AudioContentDescription* audio =
2771 GetFirstAudioContentDescription(description);
2772 ASSERT_NE(nullptr, audio);
2773 auto audio_codecs = audio->codecs();
2774 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
2775 [](const cricket::AudioCodec& codec) {
2776 return codec.name != "opus";
2777 }),
2778 audio_codecs.end());
2779 ASSERT_EQ(1u, audio_codecs.size());
2780 audio_codecs[0].name = "OpUs";
2781 audio->set_codecs(audio_codecs);
2782
2783 cricket::VideoContentDescription* video =
2784 GetFirstVideoContentDescription(description);
2785 ASSERT_NE(nullptr, video);
2786 auto video_codecs = video->codecs();
2787 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
2788 [](const cricket::VideoCodec& codec) {
2789 return codec.name != "VP8";
2790 }),
2791 video_codecs.end());
2792 ASSERT_EQ(1u, video_codecs.size());
2793 video_codecs[0].name = "vP8";
2794 video->set_codecs(video_codecs);
2795 });
2796
2797 caller()->CreateAndSetAndSignalOffer();
2798 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2799
2800 // Verify frames are still received end-to-end.
2801 ExpectNewFramesReceivedWithWait(
2802 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2803 kDefaultExpectedAudioFrameCount, kDefaultExpectedVideoFrameCount,
2804 kMaxWaitForFramesMs);
2805}
2806
hbos8d609f62017-04-10 07:39:05 -07002807TEST_F(PeerConnectionIntegrationTest, GetSources) {
2808 ASSERT_TRUE(CreatePeerConnectionWrappers());
2809 ConnectFakeSignaling();
2810 caller()->AddAudioOnlyMediaStream();
2811 caller()->CreateAndSetAndSignalOffer();
2812 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07002813 // Wait for one audio frame to be received by the callee.
hbos8d609f62017-04-10 07:39:05 -07002814 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
2815 ASSERT_GT(callee()->pc()->GetReceivers().size(), 0u);
2816 auto receiver = callee()->pc()->GetReceivers()[0];
2817 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
2818
2819 auto contributing_sources = receiver->GetSources();
2820 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
2821 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
2822 contributing_sources[0].source_id());
2823}
2824
deadbeef2f425aa2017-04-14 10:41:32 -07002825// Test that if a track is removed and added again with a different stream ID,
2826// the new stream ID is successfully communicated in SDP and media continues to
2827// flow end-to-end.
2828TEST_F(PeerConnectionIntegrationTest, RemoveAndAddTrackWithNewStreamId) {
2829 ASSERT_TRUE(CreatePeerConnectionWrappers());
2830 ConnectFakeSignaling();
2831
2832 rtc::scoped_refptr<MediaStreamInterface> stream_1 =
2833 caller()->pc_factory()->CreateLocalMediaStream("stream_1");
2834 rtc::scoped_refptr<MediaStreamInterface> stream_2 =
2835 caller()->pc_factory()->CreateLocalMediaStream("stream_2");
2836
2837 // Add track using stream 1, do offer/answer.
2838 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2839 caller()->CreateLocalAudioTrack();
2840 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2841 caller()->pc()->AddTrack(track, {stream_1.get()});
2842 caller()->CreateAndSetAndSignalOffer();
2843 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2844 // Wait for one audio frame to be received by the callee.
2845 ExpectNewFramesReceivedWithWait(0, 0, 1, 0, kMaxWaitForFramesMs);
2846
2847 // Remove the sender, and create a new one with the new stream.
2848 caller()->pc()->RemoveTrack(sender);
2849 sender = caller()->pc()->AddTrack(track, {stream_2.get()});
2850 caller()->CreateAndSetAndSignalOffer();
2851 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2852 // Wait for additional audio frames to be received by the callee.
2853 ExpectNewFramesReceivedWithWait(0, 0, kDefaultExpectedAudioFrameCount, 0,
2854 kMaxWaitForFramesMs);
2855}
2856
deadbeef1dcb1642017-03-29 21:08:16 -07002857} // namespace
2858
2859#endif // if !defined(THREAD_SANITIZER)