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