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