blob: c296e4c7d76ac1db833c1e61061ef69e327a1573 [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
Qingsi Wang1dac6d82018-12-12 15:28:47 -080025#include "absl/memory/memory.h"
Karl Wiberg1b0eae32017-10-17 14:48:54 +020026#include "api/audio_codecs/builtin_audio_decoder_factory.h"
27#include "api/audio_codecs/builtin_audio_encoder_factory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "api/mediastreaminterface.h"
29#include "api/peerconnectioninterface.h"
Steve Anton8c0f7a72017-10-03 10:03:10 -070030#include "api/peerconnectionproxy.h"
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +010031#include "api/rtpreceiverinterface.h"
Bjorn Mellem175aa2e2018-11-08 11:23:22 -080032#include "api/test/loopback_media_transport.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020033#include "api/umametrics.h"
Anders Carlsson67537952018-05-03 11:28:29 +020034#include "api/video_codecs/builtin_video_decoder_factory.h"
35#include "api/video_codecs/builtin_video_encoder_factory.h"
36#include "api/video_codecs/sdp_video_format.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070037#include "call/call.h"
38#include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
39#include "logging/rtc_event_log/rtc_event_log_factory_interface.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "media/engine/fakewebrtcvideoengine.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070041#include "media/engine/webrtcmediaengine.h"
42#include "modules/audio_processing/include/audio_processing.h"
Zach Stein6fcdc2f2018-08-23 16:25:55 -070043#include "p2p/base/mockasyncresolver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "p2p/base/p2pconstants.h"
45#include "p2p/base/portinterface.h"
Steve Antonede9ca52017-10-16 13:04:27 -070046#include "p2p/base/teststunserver.h"
Jonas Orelandbdcee282017-10-10 14:01:40 +020047#include "p2p/base/testturncustomizer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "p2p/base/testturnserver.h"
49#include "p2p/client/basicportallocator.h"
50#include "pc/dtmfsender.h"
51#include "pc/localaudiosource.h"
52#include "pc/mediasession.h"
53#include "pc/peerconnection.h"
54#include "pc/peerconnectionfactory.h"
Seth Hampson2f0d7022018-02-20 11:54:42 -080055#include "pc/rtpmediautils.h"
Steve Anton4ab68ee2017-12-19 14:26:11 -080056#include "pc/sessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020057#include "pc/test/fakeaudiocapturemodule.h"
Niels Möller0f405822018-05-17 09:16:41 +020058#include "pc/test/fakeperiodicvideotracksource.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020059#include "pc/test/fakertccertificategenerator.h"
60#include "pc/test/fakevideotrackrenderer.h"
61#include "pc/test/mockpeerconnectionobservers.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020062#include "rtc_base/fakenetwork.h"
Steve Antonede9ca52017-10-16 13:04:27 -070063#include "rtc_base/firewallsocketserver.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020064#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020065#include "rtc_base/numerics/safe_conversions.h"
Benjamin Wrightd6f86e82018-05-08 13:12:25 -070066#include "rtc_base/testcertificateverifier.h"
Johannes Kron965e7942018-09-13 15:36:20 +020067#include "rtc_base/timeutils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020068#include "rtc_base/virtualsocketserver.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020069#include "system_wrappers/include/metrics.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020070#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070071
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010072namespace webrtc {
73namespace {
74
75using ::cricket::ContentInfo;
76using ::cricket::StreamParams;
77using ::rtc::SocketAddress;
78using ::testing::_;
Seth Hampson2f0d7022018-02-20 11:54:42 -080079using ::testing::Combine;
Steve Antonede9ca52017-10-16 13:04:27 -070080using ::testing::ElementsAre;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070081using ::testing::Return;
Qingsi Wang1dac6d82018-12-12 15:28:47 -080082using ::testing::NiceMock;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070083using ::testing::SetArgPointee;
Steve Antonffa6ce42018-11-30 09:26:08 -080084using ::testing::UnorderedElementsAreArray;
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010085using ::testing::Values;
Steve Anton74255ff2018-01-24 18:32:57 -080086using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -070087
88static const int kDefaultTimeout = 10000;
89static const int kMaxWaitForStatsMs = 3000;
90static const int kMaxWaitForActivationMs = 5000;
91static const int kMaxWaitForFramesMs = 10000;
92// Default number of audio/video frames to wait for before considering a test
93// successful.
94static const int kDefaultExpectedAudioFrameCount = 3;
95static const int kDefaultExpectedVideoFrameCount = 3;
96
deadbeef1dcb1642017-03-29 21:08:16 -070097static const char kDataChannelLabel[] = "data_channel";
98
99// SRTP cipher name negotiated by the tests. This must be updated if the
100// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700101static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700102static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
103
Steve Antonede9ca52017-10-16 13:04:27 -0700104static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
105
deadbeef1dcb1642017-03-29 21:08:16 -0700106// Helper function for constructing offer/answer options to initiate an ICE
107// restart.
108PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
109 PeerConnectionInterface::RTCOfferAnswerOptions options;
110 options.ice_restart = true;
111 return options;
112}
113
deadbeefd8ad7882017-04-18 16:01:17 -0700114// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
115// attribute from received SDP, simulating a legacy endpoint.
116void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
117 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800118 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700119 }
120 desc->set_msid_supported(false);
Henrik Boström5b147782018-12-04 11:25:05 +0100121 desc->set_msid_signaling(0);
deadbeefd8ad7882017-04-18 16:01:17 -0700122}
123
Seth Hampson5897a6e2018-04-03 11:16:33 -0700124// Removes all stream information besides the stream ids, simulating an
125// endpoint that only signals a=msid lines to convey stream_ids.
126void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
127 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700128 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700129 std::vector<std::string> stream_ids;
130 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700131 const StreamParams& first_stream =
132 content.media_description()->streams()[0];
133 track_id = first_stream.id;
134 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700135 }
136 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700137 StreamParams new_stream;
138 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700139 new_stream.set_stream_ids(stream_ids);
140 content.media_description()->AddStream(new_stream);
141 }
142}
143
zhihuangf8164932017-05-19 13:09:47 -0700144int FindFirstMediaStatsIndexByKind(
145 const std::string& kind,
146 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
147 media_stats_vec) {
148 for (size_t i = 0; i < media_stats_vec.size(); i++) {
149 if (media_stats_vec[i]->kind.ValueToString() == kind) {
150 return i;
151 }
152 }
153 return -1;
154}
155
deadbeef1dcb1642017-03-29 21:08:16 -0700156class SignalingMessageReceiver {
157 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800158 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700159 virtual void ReceiveIceMessage(const std::string& sdp_mid,
160 int sdp_mline_index,
161 const std::string& msg) = 0;
162
163 protected:
164 SignalingMessageReceiver() {}
165 virtual ~SignalingMessageReceiver() {}
166};
167
168class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
169 public:
170 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
171 : expected_media_type_(media_type) {}
172
173 void OnFirstPacketReceived(cricket::MediaType media_type) override {
174 ASSERT_EQ(expected_media_type_, media_type);
175 first_packet_received_ = true;
176 }
177
178 bool first_packet_received() const { return first_packet_received_; }
179
180 virtual ~MockRtpReceiverObserver() {}
181
182 private:
183 bool first_packet_received_ = false;
184 cricket::MediaType expected_media_type_;
185};
186
187// Helper class that wraps a peer connection, observes it, and can accept
188// signaling messages from another wrapper.
189//
190// Uses a fake network, fake A/V capture, and optionally fake
191// encoders/decoders, though they aren't used by default since they don't
192// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700193// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800194// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700195class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800196 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700197 public:
198 // Different factory methods for convenience.
199 // TODO(deadbeef): Could use the pattern of:
200 //
201 // PeerConnectionWrapper =
202 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
203 //
204 // To reduce some code duplication.
205 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
206 const std::string& debug_name,
207 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
208 rtc::Thread* network_thread,
209 rtc::Thread* worker_thread) {
210 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700211 webrtc::PeerConnectionDependencies dependencies(nullptr);
212 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200213 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800214 worker_thread, nullptr,
215 /*media_transport_factory=*/nullptr)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700216 delete client;
217 return nullptr;
218 }
219 return client;
220 }
221
deadbeef2f425aa2017-04-14 10:41:32 -0700222 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
223 return peer_connection_factory_.get();
224 }
225
deadbeef1dcb1642017-03-29 21:08:16 -0700226 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
227
228 // If a signaling message receiver is set (via ConnectFakeSignaling), this
229 // will set the whole offer/answer exchange in motion. Just need to wait for
230 // the signaling state to reach "stable".
231 void CreateAndSetAndSignalOffer() {
232 auto offer = CreateOffer();
233 ASSERT_NE(nullptr, offer);
234 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
235 }
236
237 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
238 // when a remote offer is received (via fake signaling) and an answer is
239 // generated. By default, uses default options.
240 void SetOfferAnswerOptions(
241 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
242 offer_answer_options_ = options;
243 }
244
245 // Set a callback to be invoked when SDP is received via the fake signaling
246 // channel, which provides an opportunity to munge (modify) the SDP. This is
247 // used to test SDP being applied that a PeerConnection would normally not
248 // generate, but a non-JSEP endpoint might.
249 void SetReceivedSdpMunger(
250 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100251 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700252 }
253
deadbeefc964d0b2017-04-03 10:03:35 -0700254 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700255 // generated.
256 void SetGeneratedSdpMunger(
257 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100258 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700259 }
260
Seth Hampson2f0d7022018-02-20 11:54:42 -0800261 // Set a callback to be invoked when a remote offer is received via the fake
262 // signaling channel. This provides an opportunity to change the
263 // PeerConnection state before an answer is created and sent to the caller.
264 void SetRemoteOfferHandler(std::function<void()> handler) {
265 remote_offer_handler_ = std::move(handler);
266 }
267
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800268 void SetRemoteAsyncResolver(rtc::MockAsyncResolver* resolver) {
269 remote_async_resolver_ = resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700270 }
271
Steve Antonede9ca52017-10-16 13:04:27 -0700272 // Every ICE connection state in order that has been seen by the observer.
273 std::vector<PeerConnectionInterface::IceConnectionState>
274 ice_connection_state_history() const {
275 return ice_connection_state_history_;
276 }
Steve Anton6f25b092017-10-23 09:39:20 -0700277 void clear_ice_connection_state_history() {
278 ice_connection_state_history_.clear();
279 }
Steve Antonede9ca52017-10-16 13:04:27 -0700280
Jonas Olsson635474e2018-10-18 15:58:17 +0200281 // Every PeerConnection state in order that has been seen by the observer.
282 std::vector<PeerConnectionInterface::PeerConnectionState>
283 peer_connection_state_history() const {
284 return peer_connection_state_history_;
285 }
286
Steve Antonede9ca52017-10-16 13:04:27 -0700287 // Every ICE gathering state in order that has been seen by the observer.
288 std::vector<PeerConnectionInterface::IceGatheringState>
289 ice_gathering_state_history() const {
290 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700291 }
292
Steve Anton15324772018-01-16 10:26:49 -0800293 void AddAudioVideoTracks() {
294 AddAudioTrack();
295 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700296 }
297
Steve Anton74255ff2018-01-24 18:32:57 -0800298 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
299 return AddTrack(CreateLocalAudioTrack());
300 }
deadbeef1dcb1642017-03-29 21:08:16 -0700301
Steve Anton74255ff2018-01-24 18:32:57 -0800302 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
303 return AddTrack(CreateLocalVideoTrack());
304 }
deadbeef1dcb1642017-03-29 21:08:16 -0700305
306 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200307 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700308 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200309 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700310 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200311 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700312 // TODO(perkj): Test audio source when it is implemented. Currently audio
313 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700314 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700315 source);
316 }
317
318 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200319 webrtc::FakePeriodicVideoSource::Config config;
320 config.timestamp_offset_ms = rtc::TimeMillis();
321 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700322 }
323
324 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200325 CreateLocalVideoTrackWithConfig(
326 webrtc::FakePeriodicVideoSource::Config config) {
327 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700328 }
329
330 rtc::scoped_refptr<webrtc::VideoTrackInterface>
331 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200332 webrtc::FakePeriodicVideoSource::Config config;
333 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200334 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200335 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700336 }
337
Steve Anton74255ff2018-01-24 18:32:57 -0800338 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
339 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800340 const std::vector<std::string>& stream_ids = {}) {
341 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800342 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800343 return result.MoveValue();
344 }
345
346 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
347 cricket::MediaType media_type) {
348 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
349 for (auto receiver : pc()->GetReceivers()) {
350 if (receiver->media_type() == media_type) {
351 receivers.push_back(receiver);
352 }
353 }
354 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700355 }
356
Seth Hampson2f0d7022018-02-20 11:54:42 -0800357 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
358 cricket::MediaType media_type) {
359 for (auto transceiver : pc()->GetTransceivers()) {
360 if (transceiver->receiver()->media_type() == media_type) {
361 return transceiver;
362 }
363 }
364 return nullptr;
365 }
366
deadbeef1dcb1642017-03-29 21:08:16 -0700367 bool SignalingStateStable() {
368 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
369 }
370
371 void CreateDataChannel() { CreateDataChannel(nullptr); }
372
373 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700374 CreateDataChannel(kDataChannelLabel, init);
375 }
376
377 void CreateDataChannel(const std::string& label,
378 const webrtc::DataChannelInit* init) {
379 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700380 ASSERT_TRUE(data_channel_.get() != nullptr);
381 data_observer_.reset(new MockDataChannelObserver(data_channel_));
382 }
383
384 DataChannelInterface* data_channel() { return data_channel_; }
385 const MockDataChannelObserver* data_observer() const {
386 return data_observer_.get();
387 }
388
389 int audio_frames_received() const {
390 return fake_audio_capture_module_->frames_received();
391 }
392
393 // Takes minimum of video frames received for each track.
394 //
395 // Can be used like:
396 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
397 //
398 // To ensure that all video tracks received at least a certain number of
399 // frames.
400 int min_video_frames_received_per_track() const {
401 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200402 if (fake_video_renderers_.empty()) {
403 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700404 }
deadbeef1dcb1642017-03-29 21:08:16 -0700405
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200406 for (const auto& pair : fake_video_renderers_) {
407 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700408 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200409 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700410 }
411
412 // Returns a MockStatsObserver in a state after stats gathering finished,
413 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700414 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700415 webrtc::MediaStreamTrackInterface* track) {
416 rtc::scoped_refptr<MockStatsObserver> observer(
417 new rtc::RefCountedObject<MockStatsObserver>());
418 EXPECT_TRUE(peer_connection_->GetStats(
419 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
420 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
421 return observer;
422 }
423
424 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700425 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
426 return OldGetStatsForTrack(nullptr);
427 }
428
429 // Synchronously gets stats and returns them. If it times out, fails the test
430 // and returns null.
431 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
432 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
433 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
434 peer_connection_->GetStats(callback);
435 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
436 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700437 }
438
439 int rendered_width() {
440 EXPECT_FALSE(fake_video_renderers_.empty());
441 return fake_video_renderers_.empty()
442 ? 0
443 : fake_video_renderers_.begin()->second->width();
444 }
445
446 int rendered_height() {
447 EXPECT_FALSE(fake_video_renderers_.empty());
448 return fake_video_renderers_.empty()
449 ? 0
450 : fake_video_renderers_.begin()->second->height();
451 }
452
453 double rendered_aspect_ratio() {
454 if (rendered_height() == 0) {
455 return 0.0;
456 }
457 return static_cast<double>(rendered_width()) / rendered_height();
458 }
459
460 webrtc::VideoRotation rendered_rotation() {
461 EXPECT_FALSE(fake_video_renderers_.empty());
462 return fake_video_renderers_.empty()
463 ? webrtc::kVideoRotation_0
464 : fake_video_renderers_.begin()->second->rotation();
465 }
466
467 int local_rendered_width() {
468 return local_video_renderer_ ? local_video_renderer_->width() : 0;
469 }
470
471 int local_rendered_height() {
472 return local_video_renderer_ ? local_video_renderer_->height() : 0;
473 }
474
475 double local_rendered_aspect_ratio() {
476 if (local_rendered_height() == 0) {
477 return 0.0;
478 }
479 return static_cast<double>(local_rendered_width()) /
480 local_rendered_height();
481 }
482
483 size_t number_of_remote_streams() {
484 if (!pc()) {
485 return 0;
486 }
487 return pc()->remote_streams()->count();
488 }
489
490 StreamCollectionInterface* remote_streams() const {
491 if (!pc()) {
492 ADD_FAILURE();
493 return nullptr;
494 }
495 return pc()->remote_streams();
496 }
497
498 StreamCollectionInterface* local_streams() {
499 if (!pc()) {
500 ADD_FAILURE();
501 return nullptr;
502 }
503 return pc()->local_streams();
504 }
505
506 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
507 return pc()->signaling_state();
508 }
509
510 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
511 return pc()->ice_connection_state();
512 }
513
514 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
515 return pc()->ice_gathering_state();
516 }
517
518 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
519 // GetReceivers. They're updated automatically when a remote offer/answer
520 // from the fake signaling channel is applied, or when
521 // ResetRtpReceiverObservers below is called.
522 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
523 rtp_receiver_observers() {
524 return rtp_receiver_observers_;
525 }
526
527 void ResetRtpReceiverObservers() {
528 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100529 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
530 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700531 std::unique_ptr<MockRtpReceiverObserver> observer(
532 new MockRtpReceiverObserver(receiver->media_type()));
533 receiver->SetObserver(observer.get());
534 rtp_receiver_observers_.push_back(std::move(observer));
535 }
536 }
537
Steve Antonede9ca52017-10-16 13:04:27 -0700538 rtc::FakeNetworkManager* network() const {
539 return fake_network_manager_.get();
540 }
541 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
542
Qingsi Wang7685e862018-06-11 20:15:46 -0700543 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
544 return event_log_factory_;
545 }
546
deadbeef1dcb1642017-03-29 21:08:16 -0700547 private:
548 explicit PeerConnectionWrapper(const std::string& debug_name)
549 : debug_name_(debug_name) {}
550
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800551 bool Init(
552 const PeerConnectionFactory::Options* options,
553 const PeerConnectionInterface::RTCConfiguration* config,
554 webrtc::PeerConnectionDependencies dependencies,
555 rtc::Thread* network_thread,
556 rtc::Thread* worker_thread,
557 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
558 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700559 // There's an error in this test code if Init ends up being called twice.
560 RTC_DCHECK(!peer_connection_);
561 RTC_DCHECK(!peer_connection_factory_);
562
563 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700564 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700565
566 std::unique_ptr<cricket::PortAllocator> port_allocator(
567 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700568 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700569 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
570 if (!fake_audio_capture_module_) {
571 return false;
572 }
deadbeef1dcb1642017-03-29 21:08:16 -0700573 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700574
575 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
576 pc_factory_dependencies.network_thread = network_thread;
577 pc_factory_dependencies.worker_thread = worker_thread;
578 pc_factory_dependencies.signaling_thread = signaling_thread;
579 pc_factory_dependencies.media_engine =
580 cricket::WebRtcMediaEngineFactory::Create(
581 rtc::scoped_refptr<webrtc::AudioDeviceModule>(
582 fake_audio_capture_module_),
583 webrtc::CreateBuiltinAudioEncoderFactory(),
584 webrtc::CreateBuiltinAudioDecoderFactory(),
585 webrtc::CreateBuiltinVideoEncoderFactory(),
Qingsi Wang59844ce2018-11-01 04:45:53 +0000586 webrtc::CreateBuiltinVideoDecoderFactory(), nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -0700587 webrtc::AudioProcessingBuilder().Create());
588 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
589 if (event_log_factory) {
590 event_log_factory_ = event_log_factory.get();
591 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
592 } else {
593 pc_factory_dependencies.event_log_factory =
594 webrtc::CreateRtcEventLogFactory();
595 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800596 if (media_transport_factory) {
597 pc_factory_dependencies.media_transport_factory =
598 std::move(media_transport_factory);
599 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700600 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
601 std::move(pc_factory_dependencies));
602
deadbeef1dcb1642017-03-29 21:08:16 -0700603 if (!peer_connection_factory_) {
604 return false;
605 }
606 if (options) {
607 peer_connection_factory_->SetOptions(*options);
608 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800609 if (config) {
610 sdp_semantics_ = config->sdp_semantics;
611 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700612
613 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200614 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700615 return peer_connection_.get() != nullptr;
616 }
617
618 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700619 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700620 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700621 PeerConnectionInterface::RTCConfiguration modified_config;
622 // If |config| is null, this will result in a default configuration being
623 // used.
624 if (config) {
625 modified_config = *config;
626 }
627 // Disable resolution adaptation; we don't want it interfering with the
628 // test results.
629 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
630 // ratios and not specific resolutions, is this even necessary?
631 modified_config.set_cpu_adaptation(false);
632
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700633 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700634 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700635 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700636 }
637
638 void set_signaling_message_receiver(
639 SignalingMessageReceiver* signaling_message_receiver) {
640 signaling_message_receiver_ = signaling_message_receiver;
641 }
642
643 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
644
Steve Antonede9ca52017-10-16 13:04:27 -0700645 void set_signal_ice_candidates(bool signal) {
646 signal_ice_candidates_ = signal;
647 }
648
deadbeef1dcb1642017-03-29 21:08:16 -0700649 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200650 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700651 // Set max frame rate to 10fps to reduce the risk of test flakiness.
652 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200653 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700654
Niels Möller5c7efe72018-05-11 10:34:46 +0200655 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200656 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
657 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700658 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200659 peer_connection_factory_->CreateVideoTrack(
660 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700661 if (!local_video_renderer_) {
662 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
663 }
664 return track;
665 }
666
667 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100668 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800669 std::unique_ptr<SessionDescriptionInterface> desc =
670 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700671 if (received_sdp_munger_) {
672 received_sdp_munger_(desc->description());
673 }
674
675 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
676 // Setting a remote description may have changed the number of receivers,
677 // so reset the receiver observers.
678 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800679 if (remote_offer_handler_) {
680 remote_offer_handler_();
681 }
deadbeef1dcb1642017-03-29 21:08:16 -0700682 auto answer = CreateAnswer();
683 ASSERT_NE(nullptr, answer);
684 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
685 }
686
687 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100688 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800689 std::unique_ptr<SessionDescriptionInterface> desc =
690 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700691 if (received_sdp_munger_) {
692 received_sdp_munger_(desc->description());
693 }
694
695 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
696 // Set the RtpReceiverObserver after receivers are created.
697 ResetRtpReceiverObservers();
698 }
699
700 // Returns null on failure.
701 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
702 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
703 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
704 pc()->CreateOffer(observer, offer_answer_options_);
705 return WaitForDescriptionFromObserver(observer);
706 }
707
708 // Returns null on failure.
709 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
710 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
711 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
712 pc()->CreateAnswer(observer, offer_answer_options_);
713 return WaitForDescriptionFromObserver(observer);
714 }
715
716 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100717 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700718 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
719 if (!observer->result()) {
720 return nullptr;
721 }
722 auto description = observer->MoveDescription();
723 if (generated_sdp_munger_) {
724 generated_sdp_munger_(description->description());
725 }
726 return description;
727 }
728
729 // Setting the local description and sending the SDP message over the fake
730 // signaling channel are combined into the same method because the SDP
731 // message needs to be sent as soon as SetLocalDescription finishes, without
732 // waiting for the observer to be called. This ensures that ICE candidates
733 // don't outrace the description.
734 bool SetLocalDescriptionAndSendSdpMessage(
735 std::unique_ptr<SessionDescriptionInterface> desc) {
736 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
737 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800739 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700740 std::string sdp;
741 EXPECT_TRUE(desc->ToString(&sdp));
742 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800743 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
744 RemoveUnusedVideoRenderers();
745 }
deadbeef1dcb1642017-03-29 21:08:16 -0700746 // As mentioned above, we need to send the message immediately after
747 // SetLocalDescription.
748 SendSdpMessage(type, sdp);
749 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
750 return true;
751 }
752
753 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
754 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
755 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100756 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700757 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800758 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
759 RemoveUnusedVideoRenderers();
760 }
deadbeef1dcb1642017-03-29 21:08:16 -0700761 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
762 return observer->result();
763 }
764
Seth Hampson2f0d7022018-02-20 11:54:42 -0800765 // This is a work around to remove unused fake_video_renderers from
766 // transceivers that have either stopped or are no longer receiving.
767 void RemoveUnusedVideoRenderers() {
768 auto transceivers = pc()->GetTransceivers();
769 for (auto& transceiver : transceivers) {
770 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
771 continue;
772 }
773 // Remove fake video renderers from any stopped transceivers.
774 if (transceiver->stopped()) {
775 auto it =
776 fake_video_renderers_.find(transceiver->receiver()->track()->id());
777 if (it != fake_video_renderers_.end()) {
778 fake_video_renderers_.erase(it);
779 }
780 }
781 // Remove fake video renderers from any transceivers that are no longer
782 // receiving.
783 if ((transceiver->current_direction() &&
784 !webrtc::RtpTransceiverDirectionHasRecv(
785 *transceiver->current_direction()))) {
786 auto it =
787 fake_video_renderers_.find(transceiver->receiver()->track()->id());
788 if (it != fake_video_renderers_.end()) {
789 fake_video_renderers_.erase(it);
790 }
791 }
792 }
793 }
794
deadbeef1dcb1642017-03-29 21:08:16 -0700795 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
796 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800797 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700798 if (signaling_delay_ms_ == 0) {
799 RelaySdpMessageIfReceiverExists(type, msg);
800 } else {
801 invoker_.AsyncInvokeDelayed<void>(
802 RTC_FROM_HERE, rtc::Thread::Current(),
803 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
804 this, type, msg),
805 signaling_delay_ms_);
806 }
807 }
808
Steve Antona3a92c22017-12-07 10:27:41 -0800809 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700810 if (signaling_message_receiver_) {
811 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
812 }
813 }
814
815 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
816 // default).
817 void SendIceMessage(const std::string& sdp_mid,
818 int sdp_mline_index,
819 const std::string& msg) {
820 if (signaling_delay_ms_ == 0) {
821 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
822 } else {
823 invoker_.AsyncInvokeDelayed<void>(
824 RTC_FROM_HERE, rtc::Thread::Current(),
825 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
826 this, sdp_mid, sdp_mline_index, msg),
827 signaling_delay_ms_);
828 }
829 }
830
831 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
832 int sdp_mline_index,
833 const std::string& msg) {
834 if (signaling_message_receiver_) {
835 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
836 msg);
837 }
838 }
839
840 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800841 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
842 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700843 HandleIncomingOffer(msg);
844 } else {
845 HandleIncomingAnswer(msg);
846 }
847 }
848
849 void ReceiveIceMessage(const std::string& sdp_mid,
850 int sdp_mline_index,
851 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100852 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700853 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
854 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
855 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
856 }
857
858 // PeerConnectionObserver callbacks.
859 void OnSignalingChange(
860 webrtc::PeerConnectionInterface::SignalingState new_state) override {
861 EXPECT_EQ(pc()->signaling_state(), new_state);
862 }
Steve Anton15324772018-01-16 10:26:49 -0800863 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
864 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
865 streams) override {
866 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
867 rtc::scoped_refptr<VideoTrackInterface> video_track(
868 static_cast<VideoTrackInterface*>(receiver->track().get()));
869 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700870 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800871 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200872 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700873 }
874 }
Steve Anton15324772018-01-16 10:26:49 -0800875 void OnRemoveTrack(
876 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
877 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
878 auto it = fake_video_renderers_.find(receiver->track()->id());
879 RTC_DCHECK(it != fake_video_renderers_.end());
880 fake_video_renderers_.erase(it);
881 }
882 }
deadbeef1dcb1642017-03-29 21:08:16 -0700883 void OnRenegotiationNeeded() override {}
884 void OnIceConnectionChange(
885 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
886 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700887 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700888 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200889 void OnConnectionChange(
890 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
891 peer_connection_state_history_.push_back(new_state);
892 }
893
deadbeef1dcb1642017-03-29 21:08:16 -0700894 void OnIceGatheringChange(
895 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700896 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700897 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700898 }
899 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100900 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700901
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800902 if (remote_async_resolver_) {
903 const auto& local_candidate = candidate->candidate();
904 const auto& mdns_responder = network()->GetMdnsResponderForTesting();
905 if (local_candidate.address().IsUnresolvedIP()) {
906 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
907 rtc::SocketAddress resolved_addr(local_candidate.address());
908 const auto resolved_ip = mdns_responder->GetMappedAddressForName(
909 local_candidate.address().hostname());
910 RTC_DCHECK(!resolved_ip.IsNil());
911 resolved_addr.SetResolvedIP(resolved_ip);
912 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
913 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
914 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700915 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700916 }
917
deadbeef1dcb1642017-03-29 21:08:16 -0700918 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800919 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700920 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700921 // Remote party may be deleted.
922 return;
923 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800924 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
deadbeef1dcb1642017-03-29 21:08:16 -0700925 }
926 void OnDataChannel(
927 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100928 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700929 data_channel_ = data_channel;
930 data_observer_.reset(new MockDataChannelObserver(data_channel));
931 }
932
deadbeef1dcb1642017-03-29 21:08:16 -0700933 std::string debug_name_;
934
935 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
936
937 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
938 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
939 peer_connection_factory_;
940
Steve Antonede9ca52017-10-16 13:04:27 -0700941 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700942 // Needed to keep track of number of frames sent.
943 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
944 // Needed to keep track of number of frames received.
945 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
946 fake_video_renderers_;
947 // Needed to ensure frames aren't received for removed tracks.
948 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
949 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -0700950
951 // For remote peer communication.
952 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
953 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -0700954 bool signal_ice_candidates_ = true;
deadbeef1dcb1642017-03-29 21:08:16 -0700955
Niels Möller5c7efe72018-05-11 10:34:46 +0200956 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -0700957 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +0200958 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
959 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -0700960 // |local_video_renderer_| attached to the first created local video track.
961 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
962
Seth Hampson2f0d7022018-02-20 11:54:42 -0800963 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -0700964 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
965 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
966 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -0800967 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800968 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -0700969 rtc::scoped_refptr<DataChannelInterface> data_channel_;
970 std::unique_ptr<MockDataChannelObserver> data_observer_;
971
972 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
973
Steve Antonede9ca52017-10-16 13:04:27 -0700974 std::vector<PeerConnectionInterface::IceConnectionState>
975 ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +0200976 std::vector<PeerConnectionInterface::PeerConnectionState>
977 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -0700978 std::vector<PeerConnectionInterface::IceGatheringState>
979 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700980
Qingsi Wang7685e862018-06-11 20:15:46 -0700981 webrtc::FakeRtcEventLogFactory* event_log_factory_;
982
deadbeef1dcb1642017-03-29 21:08:16 -0700983 rtc::AsyncInvoker invoker_;
984
Seth Hampson2f0d7022018-02-20 11:54:42 -0800985 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -0700986};
987
Elad Alon99c3fe52017-10-13 16:29:40 +0200988class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
989 public:
990 virtual ~MockRtcEventLogOutput() = default;
991 MOCK_CONST_METHOD0(IsActive, bool());
992 MOCK_METHOD1(Write, bool(const std::string&));
993};
994
Seth Hampson2f0d7022018-02-20 11:54:42 -0800995// This helper object is used for both specifying how many audio/video frames
996// are expected to be received for a caller/callee. It provides helper functions
997// to specify these expectations. The object initially starts in a state of no
998// expectations.
999class MediaExpectations {
1000 public:
1001 enum ExpectFrames {
1002 kExpectSomeFrames,
1003 kExpectNoFrames,
1004 kNoExpectation,
1005 };
1006
1007 void ExpectBidirectionalAudioAndVideo() {
1008 ExpectBidirectionalAudio();
1009 ExpectBidirectionalVideo();
1010 }
1011
1012 void ExpectBidirectionalAudio() {
1013 CallerExpectsSomeAudio();
1014 CalleeExpectsSomeAudio();
1015 }
1016
1017 void ExpectNoAudio() {
1018 CallerExpectsNoAudio();
1019 CalleeExpectsNoAudio();
1020 }
1021
1022 void ExpectBidirectionalVideo() {
1023 CallerExpectsSomeVideo();
1024 CalleeExpectsSomeVideo();
1025 }
1026
1027 void ExpectNoVideo() {
1028 CallerExpectsNoVideo();
1029 CalleeExpectsNoVideo();
1030 }
1031
1032 void CallerExpectsSomeAudioAndVideo() {
1033 CallerExpectsSomeAudio();
1034 CallerExpectsSomeVideo();
1035 }
1036
1037 void CalleeExpectsSomeAudioAndVideo() {
1038 CalleeExpectsSomeAudio();
1039 CalleeExpectsSomeVideo();
1040 }
1041
1042 // Caller's audio functions.
1043 void CallerExpectsSomeAudio(
1044 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1045 caller_audio_expectation_ = kExpectSomeFrames;
1046 caller_audio_frames_expected_ = expected_audio_frames;
1047 }
1048
1049 void CallerExpectsNoAudio() {
1050 caller_audio_expectation_ = kExpectNoFrames;
1051 caller_audio_frames_expected_ = 0;
1052 }
1053
1054 // Caller's video functions.
1055 void CallerExpectsSomeVideo(
1056 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1057 caller_video_expectation_ = kExpectSomeFrames;
1058 caller_video_frames_expected_ = expected_video_frames;
1059 }
1060
1061 void CallerExpectsNoVideo() {
1062 caller_video_expectation_ = kExpectNoFrames;
1063 caller_video_frames_expected_ = 0;
1064 }
1065
1066 // Callee's audio functions.
1067 void CalleeExpectsSomeAudio(
1068 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1069 callee_audio_expectation_ = kExpectSomeFrames;
1070 callee_audio_frames_expected_ = expected_audio_frames;
1071 }
1072
1073 void CalleeExpectsNoAudio() {
1074 callee_audio_expectation_ = kExpectNoFrames;
1075 callee_audio_frames_expected_ = 0;
1076 }
1077
1078 // Callee's video functions.
1079 void CalleeExpectsSomeVideo(
1080 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1081 callee_video_expectation_ = kExpectSomeFrames;
1082 callee_video_frames_expected_ = expected_video_frames;
1083 }
1084
1085 void CalleeExpectsNoVideo() {
1086 callee_video_expectation_ = kExpectNoFrames;
1087 callee_video_frames_expected_ = 0;
1088 }
1089
1090 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1091 ExpectFrames caller_video_expectation_ = kNoExpectation;
1092 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1093 ExpectFrames callee_video_expectation_ = kNoExpectation;
1094 int caller_audio_frames_expected_ = 0;
1095 int caller_video_frames_expected_ = 0;
1096 int callee_audio_frames_expected_ = 0;
1097 int callee_video_frames_expected_ = 0;
1098};
1099
deadbeef1dcb1642017-03-29 21:08:16 -07001100// Tests two PeerConnections connecting to each other end-to-end, using a
1101// virtual network, fake A/V capture and fake encoder/decoders. The
1102// PeerConnections share the threads/socket servers, but use separate versions
1103// of everything else (including "PeerConnectionFactory"s).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001104class PeerConnectionIntegrationBaseTest : public testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001105 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001106 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1107 : sdp_semantics_(sdp_semantics),
1108 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001109 fss_(new rtc::FirewallSocketServer(ss_.get())),
1110 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001111 worker_thread_(rtc::Thread::Create()),
1112 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001113 network_thread_->SetName("PCNetworkThread", this);
1114 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001115 RTC_CHECK(network_thread_->Start());
1116 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001117 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001118 }
1119
Seth Hampson2f0d7022018-02-20 11:54:42 -08001120 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001121 // The PeerConnections should deleted before the TurnCustomizers.
1122 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1123 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1124 // that the TurnCustomizer outlives the life of the PeerConnection or else
1125 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001126 if (caller_) {
1127 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001128 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001129 }
1130 if (callee_) {
1131 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001132 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001133 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001134
1135 // If turn servers were created for the test they need to be destroyed on
1136 // the network thread.
1137 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1138 turn_servers_.clear();
1139 turn_customizers_.clear();
1140 });
deadbeef1dcb1642017-03-29 21:08:16 -07001141 }
1142
1143 bool SignalingStateStable() {
1144 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1145 }
1146
deadbeef71452802017-05-07 17:21:01 -07001147 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001148 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1149 // are connected. This is an important distinction. Once we have separate
1150 // ICE and DTLS state, this check needs to use the DTLS state.
1151 return (callee()->ice_connection_state() ==
1152 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1153 callee()->ice_connection_state() ==
1154 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1155 (caller()->ice_connection_state() ==
1156 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1157 caller()->ice_connection_state() ==
1158 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001159 }
1160
Qingsi Wang7685e862018-06-11 20:15:46 -07001161 // When |event_log_factory| is null, the default implementation of the event
1162 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001163 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1164 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001165 const PeerConnectionFactory::Options* options,
1166 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001167 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001168 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1169 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001170 RTCConfiguration modified_config;
1171 if (config) {
1172 modified_config = *config;
1173 }
Steve Anton3acffc32018-04-12 17:21:03 -07001174 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001175 if (!dependencies.cert_generator) {
1176 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001177 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001178 }
1179 std::unique_ptr<PeerConnectionWrapper> client(
1180 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001181
Niels Möllerf06f9232018-08-07 12:32:18 +02001182 if (!client->Init(options, &modified_config, std::move(dependencies),
1183 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001184 std::move(event_log_factory),
1185 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001186 return nullptr;
1187 }
1188 return client;
1189 }
1190
Qingsi Wang7685e862018-06-11 20:15:46 -07001191 std::unique_ptr<PeerConnectionWrapper>
1192 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1193 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001194 const PeerConnectionFactory::Options* options,
1195 const RTCConfiguration* config,
1196 webrtc::PeerConnectionDependencies dependencies) {
1197 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1198 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001199 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001200 std::move(dependencies),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001201 std::move(event_log_factory),
1202 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001203 }
1204
deadbeef1dcb1642017-03-29 21:08:16 -07001205 bool CreatePeerConnectionWrappers() {
1206 return CreatePeerConnectionWrappersWithConfig(
1207 PeerConnectionInterface::RTCConfiguration(),
1208 PeerConnectionInterface::RTCConfiguration());
1209 }
1210
Steve Anton3acffc32018-04-12 17:21:03 -07001211 bool CreatePeerConnectionWrappersWithSdpSemantics(
1212 SdpSemantics caller_semantics,
1213 SdpSemantics callee_semantics) {
1214 // Can't specify the sdp_semantics in the passed-in configuration since it
1215 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1216 // stored in sdp_semantics_. So get around this by modifying the instance
1217 // variable before calling CreatePeerConnectionWrapper for the caller and
1218 // callee PeerConnections.
1219 SdpSemantics original_semantics = sdp_semantics_;
1220 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001221 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001222 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001223 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001224 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001225 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001226 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001227 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001228 sdp_semantics_ = original_semantics;
1229 return caller_ && callee_;
1230 }
1231
deadbeef1dcb1642017-03-29 21:08:16 -07001232 bool CreatePeerConnectionWrappersWithConfig(
1233 const PeerConnectionInterface::RTCConfiguration& caller_config,
1234 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001235 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001236 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001237 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1238 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001239 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001240 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001241 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1242 /*media_transport_factory=*/nullptr);
1243 return caller_ && callee_;
1244 }
1245
1246 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1247 const PeerConnectionInterface::RTCConfiguration& caller_config,
1248 const PeerConnectionInterface::RTCConfiguration& callee_config,
1249 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1250 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
1251 caller_ =
1252 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1253 webrtc::PeerConnectionDependencies(nullptr),
1254 nullptr, std::move(caller_factory));
1255 callee_ =
1256 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1257 webrtc::PeerConnectionDependencies(nullptr),
1258 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001259 return caller_ && callee_;
1260 }
1261
1262 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1263 const PeerConnectionInterface::RTCConfiguration& caller_config,
1264 webrtc::PeerConnectionDependencies caller_dependencies,
1265 const PeerConnectionInterface::RTCConfiguration& callee_config,
1266 webrtc::PeerConnectionDependencies callee_dependencies) {
1267 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001268 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001269 std::move(caller_dependencies), nullptr,
1270 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001271 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001272 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001273 std::move(callee_dependencies), nullptr,
1274 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001275 return caller_ && callee_;
1276 }
1277
1278 bool CreatePeerConnectionWrappersWithOptions(
1279 const PeerConnectionFactory::Options& caller_options,
1280 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001281 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001282 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001283 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1284 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001285 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001286 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001287 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1288 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001289 return caller_ && callee_;
1290 }
1291
1292 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1293 PeerConnectionInterface::RTCConfiguration default_config;
1294 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001295 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001296 webrtc::PeerConnectionDependencies(nullptr));
1297 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001298 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001299 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001300 return caller_ && callee_;
1301 }
1302
Seth Hampson2f0d7022018-02-20 11:54:42 -08001303 std::unique_ptr<PeerConnectionWrapper>
1304 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001305 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1306 new FakeRTCCertificateGenerator());
1307 cert_generator->use_alternate_key();
1308
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001309 webrtc::PeerConnectionDependencies dependencies(nullptr);
1310 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001311 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001312 std::move(dependencies), nullptr,
1313 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001314 }
1315
Seth Hampsonaed71642018-06-11 07:41:32 -07001316 cricket::TestTurnServer* CreateTurnServer(
1317 rtc::SocketAddress internal_address,
1318 rtc::SocketAddress external_address,
1319 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1320 const std::string& common_name = "test turn server") {
1321 rtc::Thread* thread = network_thread();
1322 std::unique_ptr<cricket::TestTurnServer> turn_server =
1323 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1324 RTC_FROM_HERE,
1325 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001326 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001327 thread, internal_address, external_address, type,
1328 /*ignore_bad_certs=*/true, common_name);
1329 });
1330 turn_servers_.push_back(std::move(turn_server));
1331 // Interactions with the turn server should be done on the network thread.
1332 return turn_servers_.back().get();
1333 }
1334
1335 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1336 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1337 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1338 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001339 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001340 turn_customizers_.push_back(std::move(turn_customizer));
1341 // Interactions with the turn customizer should be done on the network
1342 // thread.
1343 return turn_customizers_.back().get();
1344 }
1345
1346 // Checks that the function counters for a TestTurnCustomizer are greater than
1347 // 0.
1348 void ExpectTurnCustomizerCountersIncremented(
1349 cricket::TestTurnCustomizer* turn_customizer) {
1350 unsigned int allow_channel_data_counter =
1351 network_thread()->Invoke<unsigned int>(
1352 RTC_FROM_HERE, [turn_customizer] {
1353 return turn_customizer->allow_channel_data_cnt_;
1354 });
1355 EXPECT_GT(allow_channel_data_counter, 0u);
1356 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1357 RTC_FROM_HERE,
1358 [turn_customizer] { return turn_customizer->modify_cnt_; });
1359 EXPECT_GT(modify_counter, 0u);
1360 }
1361
deadbeef1dcb1642017-03-29 21:08:16 -07001362 // Once called, SDP blobs and ICE candidates will be automatically signaled
1363 // between PeerConnections.
1364 void ConnectFakeSignaling() {
1365 caller_->set_signaling_message_receiver(callee_.get());
1366 callee_->set_signaling_message_receiver(caller_.get());
1367 }
1368
Steve Antonede9ca52017-10-16 13:04:27 -07001369 // Once called, SDP blobs will be automatically signaled between
1370 // PeerConnections. Note that ICE candidates will not be signaled unless they
1371 // are in the exchanged SDP blobs.
1372 void ConnectFakeSignalingForSdpOnly() {
1373 ConnectFakeSignaling();
1374 SetSignalIceCandidates(false);
1375 }
1376
deadbeef1dcb1642017-03-29 21:08:16 -07001377 void SetSignalingDelayMs(int delay_ms) {
1378 caller_->set_signaling_delay_ms(delay_ms);
1379 callee_->set_signaling_delay_ms(delay_ms);
1380 }
1381
Steve Antonede9ca52017-10-16 13:04:27 -07001382 void SetSignalIceCandidates(bool signal) {
1383 caller_->set_signal_ice_candidates(signal);
1384 callee_->set_signal_ice_candidates(signal);
1385 }
1386
deadbeef1dcb1642017-03-29 21:08:16 -07001387 // Messages may get lost on the unreliable DataChannel, so we send multiple
1388 // times to avoid test flakiness.
1389 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1390 const std::string& data,
1391 int retries) {
1392 for (int i = 0; i < retries; ++i) {
1393 dc->Send(DataBuffer(data));
1394 }
1395 }
1396
1397 rtc::Thread* network_thread() { return network_thread_.get(); }
1398
1399 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1400
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001401 webrtc::MediaTransportPair* loopback_media_transports() {
1402 return &loopback_media_transports_;
1403 }
1404
deadbeef1dcb1642017-03-29 21:08:16 -07001405 PeerConnectionWrapper* caller() { return caller_.get(); }
1406
1407 // Set the |caller_| to the |wrapper| passed in and return the
1408 // original |caller_|.
1409 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1410 PeerConnectionWrapper* wrapper) {
1411 PeerConnectionWrapper* old = caller_.release();
1412 caller_.reset(wrapper);
1413 return old;
1414 }
1415
1416 PeerConnectionWrapper* callee() { return callee_.get(); }
1417
1418 // Set the |callee_| to the |wrapper| passed in and return the
1419 // original |callee_|.
1420 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1421 PeerConnectionWrapper* wrapper) {
1422 PeerConnectionWrapper* old = callee_.release();
1423 callee_.reset(wrapper);
1424 return old;
1425 }
1426
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001427 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1428 network_thread()->Invoke<void>(
1429 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1430 caller()->port_allocator(), caller_flags));
1431 network_thread()->Invoke<void>(
1432 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1433 callee()->port_allocator(), callee_flags));
1434 }
1435
Steve Antonede9ca52017-10-16 13:04:27 -07001436 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1437
Seth Hampson2f0d7022018-02-20 11:54:42 -08001438 // Expects the provided number of new frames to be received within
1439 // kMaxWaitForFramesMs. The new expected frames are specified in
1440 // |media_expectations|. Returns false if any of the expectations were
1441 // not met.
1442 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1443 // First initialize the expected frame counts based upon the current
1444 // frame count.
1445 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1446 if (media_expectations.caller_audio_expectation_ ==
1447 MediaExpectations::kExpectSomeFrames) {
1448 total_caller_audio_frames_expected +=
1449 media_expectations.caller_audio_frames_expected_;
1450 }
1451 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001452 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001453 if (media_expectations.caller_video_expectation_ ==
1454 MediaExpectations::kExpectSomeFrames) {
1455 total_caller_video_frames_expected +=
1456 media_expectations.caller_video_frames_expected_;
1457 }
1458 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1459 if (media_expectations.callee_audio_expectation_ ==
1460 MediaExpectations::kExpectSomeFrames) {
1461 total_callee_audio_frames_expected +=
1462 media_expectations.callee_audio_frames_expected_;
1463 }
1464 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001465 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001466 if (media_expectations.callee_video_expectation_ ==
1467 MediaExpectations::kExpectSomeFrames) {
1468 total_callee_video_frames_expected +=
1469 media_expectations.callee_video_frames_expected_;
1470 }
deadbeef1dcb1642017-03-29 21:08:16 -07001471
Seth Hampson2f0d7022018-02-20 11:54:42 -08001472 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001473 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001474 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001475 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001476 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001477 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001478 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001479 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001480 total_callee_video_frames_expected,
1481 kMaxWaitForFramesMs);
1482 bool expectations_correct =
1483 caller()->audio_frames_received() >=
1484 total_caller_audio_frames_expected &&
1485 caller()->min_video_frames_received_per_track() >=
1486 total_caller_video_frames_expected &&
1487 callee()->audio_frames_received() >=
1488 total_callee_audio_frames_expected &&
1489 callee()->min_video_frames_received_per_track() >=
1490 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001491
Seth Hampson2f0d7022018-02-20 11:54:42 -08001492 // After the combined wait, print out a more detailed message upon
1493 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001494 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001495 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001496 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001497 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001498 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001499 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001500 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001501 total_callee_video_frames_expected);
1502
1503 // We want to make sure nothing unexpected was received.
1504 if (media_expectations.caller_audio_expectation_ ==
1505 MediaExpectations::kExpectNoFrames) {
1506 EXPECT_EQ(caller()->audio_frames_received(),
1507 total_caller_audio_frames_expected);
1508 if (caller()->audio_frames_received() !=
1509 total_caller_audio_frames_expected) {
1510 expectations_correct = false;
1511 }
1512 }
1513 if (media_expectations.caller_video_expectation_ ==
1514 MediaExpectations::kExpectNoFrames) {
1515 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1516 total_caller_video_frames_expected);
1517 if (caller()->min_video_frames_received_per_track() !=
1518 total_caller_video_frames_expected) {
1519 expectations_correct = false;
1520 }
1521 }
1522 if (media_expectations.callee_audio_expectation_ ==
1523 MediaExpectations::kExpectNoFrames) {
1524 EXPECT_EQ(callee()->audio_frames_received(),
1525 total_callee_audio_frames_expected);
1526 if (callee()->audio_frames_received() !=
1527 total_callee_audio_frames_expected) {
1528 expectations_correct = false;
1529 }
1530 }
1531 if (media_expectations.callee_video_expectation_ ==
1532 MediaExpectations::kExpectNoFrames) {
1533 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1534 total_callee_video_frames_expected);
1535 if (callee()->min_video_frames_received_per_track() !=
1536 total_callee_video_frames_expected) {
1537 expectations_correct = false;
1538 }
1539 }
1540 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001541 }
1542
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001543 void TestNegotiatedCipherSuite(
1544 const PeerConnectionFactory::Options& caller_options,
1545 const PeerConnectionFactory::Options& callee_options,
1546 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001547 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1548 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001549 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001550 caller()->AddAudioVideoTracks();
1551 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001552 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001553 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001554 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001555 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001556 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00001557 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001558 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1559 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001560 }
1561
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001562 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1563 bool remote_gcm_enabled,
1564 int expected_cipher_suite) {
1565 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001566 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1567 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001568 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001569 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1570 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001571 TestNegotiatedCipherSuite(caller_options, callee_options,
1572 expected_cipher_suite);
1573 }
1574
Seth Hampson2f0d7022018-02-20 11:54:42 -08001575 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001576 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001577
deadbeef1dcb1642017-03-29 21:08:16 -07001578 private:
1579 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001580 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001581 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001582 // |network_thread_| and |worker_thread_| are used by both
1583 // |caller_| and |callee_| so they must be destroyed
1584 // later.
1585 std::unique_ptr<rtc::Thread> network_thread_;
1586 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001587 // The turn servers and turn customizers should be accessed & deleted on the
1588 // network thread to avoid a race with the socket read/write that occurs
1589 // on the network thread.
1590 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1591 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001592 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001593 std::unique_ptr<PeerConnectionWrapper> caller_;
1594 std::unique_ptr<PeerConnectionWrapper> callee_;
1595};
1596
Seth Hampson2f0d7022018-02-20 11:54:42 -08001597class PeerConnectionIntegrationTest
1598 : public PeerConnectionIntegrationBaseTest,
1599 public ::testing::WithParamInterface<SdpSemantics> {
1600 protected:
1601 PeerConnectionIntegrationTest()
1602 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1603};
1604
1605class PeerConnectionIntegrationTestPlanB
1606 : public PeerConnectionIntegrationBaseTest {
1607 protected:
1608 PeerConnectionIntegrationTestPlanB()
1609 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1610};
1611
1612class PeerConnectionIntegrationTestUnifiedPlan
1613 : public PeerConnectionIntegrationBaseTest {
1614 protected:
1615 PeerConnectionIntegrationTestUnifiedPlan()
1616 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1617};
1618
deadbeef1dcb1642017-03-29 21:08:16 -07001619// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1620// includes testing that the callback is invoked if an observer is connected
1621// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001622TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001623 RtpReceiverObserverOnFirstPacketReceived) {
1624 ASSERT_TRUE(CreatePeerConnectionWrappers());
1625 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001626 caller()->AddAudioVideoTracks();
1627 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001628 // Start offer/answer exchange and wait for it to complete.
1629 caller()->CreateAndSetAndSignalOffer();
1630 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1631 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001632 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1633 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001634 // Wait for all "first packet received" callbacks to be fired.
1635 EXPECT_TRUE_WAIT(
1636 std::all_of(caller()->rtp_receiver_observers().begin(),
1637 caller()->rtp_receiver_observers().end(),
1638 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1639 return o->first_packet_received();
1640 }),
1641 kMaxWaitForFramesMs);
1642 EXPECT_TRUE_WAIT(
1643 std::all_of(callee()->rtp_receiver_observers().begin(),
1644 callee()->rtp_receiver_observers().end(),
1645 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1646 return o->first_packet_received();
1647 }),
1648 kMaxWaitForFramesMs);
1649 // If new observers are set after the first packet was already received, the
1650 // callback should still be invoked.
1651 caller()->ResetRtpReceiverObservers();
1652 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001653 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1654 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001655 EXPECT_TRUE(
1656 std::all_of(caller()->rtp_receiver_observers().begin(),
1657 caller()->rtp_receiver_observers().end(),
1658 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1659 return o->first_packet_received();
1660 }));
1661 EXPECT_TRUE(
1662 std::all_of(callee()->rtp_receiver_observers().begin(),
1663 callee()->rtp_receiver_observers().end(),
1664 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1665 return o->first_packet_received();
1666 }));
1667}
1668
1669class DummyDtmfObserver : public DtmfSenderObserverInterface {
1670 public:
1671 DummyDtmfObserver() : completed_(false) {}
1672
1673 // Implements DtmfSenderObserverInterface.
1674 void OnToneChange(const std::string& tone) override {
1675 tones_.push_back(tone);
1676 if (tone.empty()) {
1677 completed_ = true;
1678 }
1679 }
1680
1681 const std::vector<std::string>& tones() const { return tones_; }
1682 bool completed() const { return completed_; }
1683
1684 private:
1685 bool completed_;
1686 std::vector<std::string> tones_;
1687};
1688
1689// Assumes |sender| already has an audio track added and the offer/answer
1690// exchange is done.
1691void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1692 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001693 // We should be able to get a DTMF sender from the local sender.
1694 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1695 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1696 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001697 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001698 dtmf_sender->RegisterObserver(&observer);
1699
1700 // Test the DtmfSender object just created.
1701 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1702 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1703
1704 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1705 std::vector<std::string> tones = {"1", "a", ""};
1706 EXPECT_EQ(tones, observer.tones());
1707 dtmf_sender->UnregisterObserver();
1708 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1709}
1710
1711// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1712// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001713TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001714 ASSERT_TRUE(CreatePeerConnectionWrappers());
1715 ConnectFakeSignaling();
1716 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001717 caller()->AddAudioTrack();
1718 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001719 caller()->CreateAndSetAndSignalOffer();
1720 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001721 // DTLS must finish before the DTMF sender can be used reliably.
1722 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001723 TestDtmfFromSenderToReceiver(caller(), callee());
1724 TestDtmfFromSenderToReceiver(callee(), caller());
1725}
1726
1727// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1728// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001729TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001730 ASSERT_TRUE(CreatePeerConnectionWrappers());
1731 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001732
deadbeef1dcb1642017-03-29 21:08:16 -07001733 // Do normal offer/answer and wait for some frames to be received in each
1734 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001735 caller()->AddAudioVideoTracks();
1736 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001737 caller()->CreateAndSetAndSignalOffer();
1738 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001739 MediaExpectations media_expectations;
1740 media_expectations.ExpectBidirectionalAudioAndVideo();
1741 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001742 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1743 webrtc::kEnumCounterKeyProtocolDtls));
1744 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1745 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001746}
1747
1748// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001749TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001750 PeerConnectionInterface::RTCConfiguration sdes_config;
1751 sdes_config.enable_dtls_srtp.emplace(false);
1752 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1753 ConnectFakeSignaling();
1754
1755 // Do normal offer/answer and wait for some frames to be received in each
1756 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001757 caller()->AddAudioVideoTracks();
1758 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001759 caller()->CreateAndSetAndSignalOffer();
1760 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001761 MediaExpectations media_expectations;
1762 media_expectations.ExpectBidirectionalAudioAndVideo();
1763 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001764 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1765 webrtc::kEnumCounterKeyProtocolSdes));
1766 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1767 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001768}
1769
Steve Anton8c0f7a72017-10-03 10:03:10 -07001770// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1771// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001772TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001773 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1774 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1775 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1776 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1777 return pc->GetRemoteAudioSSLCertificate();
1778 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001779 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1780 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1781 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1782 return pc->GetRemoteAudioSSLCertChain();
1783 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001784
1785 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1786 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1787
1788 // Configure each side with a known certificate so they can be compared later.
1789 PeerConnectionInterface::RTCConfiguration caller_config;
1790 caller_config.enable_dtls_srtp.emplace(true);
1791 caller_config.certificates.push_back(caller_cert);
1792 PeerConnectionInterface::RTCConfiguration callee_config;
1793 callee_config.enable_dtls_srtp.emplace(true);
1794 callee_config.certificates.push_back(callee_cert);
1795 ASSERT_TRUE(
1796 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1797 ConnectFakeSignaling();
1798
1799 // When first initialized, there should not be a remote SSL certificate (and
1800 // calling this method should not crash).
1801 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1802 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001803 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1804 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001805
Steve Anton15324772018-01-16 10:26:49 -08001806 caller()->AddAudioTrack();
1807 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001808 caller()->CreateAndSetAndSignalOffer();
1809 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1810 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1811
1812 // Once DTLS has been connected, each side should return the other's SSL
1813 // certificate when calling GetRemoteAudioSSLCertificate.
1814
1815 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1816 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001817 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001818 caller_remote_cert->ToPEMString());
1819
1820 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1821 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001822 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001823 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001824
1825 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1826 ASSERT_TRUE(caller_remote_cert_chain);
1827 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1828 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001829 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001830 remote_cert->ToPEMString());
1831
1832 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1833 ASSERT_TRUE(callee_remote_cert_chain);
1834 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1835 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001836 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001837 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001838}
1839
deadbeef1dcb1642017-03-29 21:08:16 -07001840// This test sets up a call between two parties with a source resolution of
1841// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001842TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001843 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1844 ASSERT_TRUE(CreatePeerConnectionWrappers());
1845 ConnectFakeSignaling();
1846
Niels Möller5c7efe72018-05-11 10:34:46 +02001847 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1848 webrtc::FakePeriodicVideoSource::Config config;
1849 config.width = 1280;
1850 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001851 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001852 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1853 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001854
1855 // Do normal offer/answer and wait for at least one frame to be received in
1856 // each direction.
1857 caller()->CreateAndSetAndSignalOffer();
1858 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1859 callee()->min_video_frames_received_per_track() > 0,
1860 kMaxWaitForFramesMs);
1861
1862 // Check rendered aspect ratio.
1863 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1864 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1865 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1866 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1867}
1868
1869// This test sets up an one-way call, with media only from caller to
1870// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001871TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001872 ASSERT_TRUE(CreatePeerConnectionWrappers());
1873 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001874 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001875 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001876 MediaExpectations media_expectations;
1877 media_expectations.CalleeExpectsSomeAudioAndVideo();
1878 media_expectations.CallerExpectsNoAudio();
1879 media_expectations.CallerExpectsNoVideo();
1880 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001881}
1882
1883// This test sets up a audio call initially, with the callee rejecting video
1884// initially. Then later the callee decides to upgrade to audio/video, and
1885// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001886TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001887 ASSERT_TRUE(CreatePeerConnectionWrappers());
1888 ConnectFakeSignaling();
1889 // Initially, offer an audio/video stream from the caller, but refuse to
1890 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001891 caller()->AddAudioVideoTracks();
1892 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001893 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1894 PeerConnectionInterface::RTCOfferAnswerOptions options;
1895 options.offer_to_receive_video = 0;
1896 callee()->SetOfferAnswerOptions(options);
1897 } else {
1898 callee()->SetRemoteOfferHandler([this] {
1899 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1900 });
1901 }
deadbeef1dcb1642017-03-29 21:08:16 -07001902 // Do offer/answer and make sure audio is still received end-to-end.
1903 caller()->CreateAndSetAndSignalOffer();
1904 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001905 {
1906 MediaExpectations media_expectations;
1907 media_expectations.ExpectBidirectionalAudio();
1908 media_expectations.ExpectNoVideo();
1909 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1910 }
deadbeef1dcb1642017-03-29 21:08:16 -07001911 // Sanity check that the callee's description has a rejected video section.
1912 ASSERT_NE(nullptr, callee()->pc()->local_description());
1913 const ContentInfo* callee_video_content =
1914 GetFirstVideoContent(callee()->pc()->local_description()->description());
1915 ASSERT_NE(nullptr, callee_video_content);
1916 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001917
deadbeef1dcb1642017-03-29 21:08:16 -07001918 // Now negotiate with video and ensure negotiation succeeds, with video
1919 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001920 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001921 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1922 PeerConnectionInterface::RTCOfferAnswerOptions options;
1923 options.offer_to_receive_video = 1;
1924 callee()->SetOfferAnswerOptions(options);
1925 } else {
1926 callee()->SetRemoteOfferHandler(nullptr);
1927 caller()->SetRemoteOfferHandler([this] {
1928 // The caller creates a new transceiver to receive video on when receiving
1929 // the offer, but by default it is send only.
1930 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001931 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08001932 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
1933 transceivers[2]->receiver()->media_type());
1934 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
1935 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
1936 });
1937 }
deadbeef1dcb1642017-03-29 21:08:16 -07001938 callee()->CreateAndSetAndSignalOffer();
1939 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001940 {
1941 // Expect additional audio frames to be received after the upgrade.
1942 MediaExpectations media_expectations;
1943 media_expectations.ExpectBidirectionalAudioAndVideo();
1944 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1945 }
deadbeef1dcb1642017-03-29 21:08:16 -07001946}
1947
deadbeef4389b4d2017-09-07 09:07:36 -07001948// Simpler than the above test; just add an audio track to an established
1949// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001950TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07001951 ASSERT_TRUE(CreatePeerConnectionWrappers());
1952 ConnectFakeSignaling();
1953 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08001954 caller()->AddVideoTrack();
1955 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001956 caller()->CreateAndSetAndSignalOffer();
1957 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1958 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08001959 caller()->AddAudioTrack();
1960 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07001961 caller()->CreateAndSetAndSignalOffer();
1962 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1963 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001964 MediaExpectations media_expectations;
1965 media_expectations.ExpectBidirectionalAudioAndVideo();
1966 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07001967}
1968
deadbeef1dcb1642017-03-29 21:08:16 -07001969// This test sets up a call that's transferred to a new caller with a different
1970// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001971TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07001972 ASSERT_TRUE(CreatePeerConnectionWrappers());
1973 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001974 caller()->AddAudioVideoTracks();
1975 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001976 caller()->CreateAndSetAndSignalOffer();
1977 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1978
1979 // Keep the original peer around which will still send packets to the
1980 // receiving client. These SRTP packets will be dropped.
1981 std::unique_ptr<PeerConnectionWrapper> original_peer(
1982 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08001983 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07001984 // TODO(deadbeef): Why do we call Close here? That goes against the comment
1985 // directly above.
1986 original_peer->pc()->Close();
1987
1988 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001989 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001990 caller()->CreateAndSetAndSignalOffer();
1991 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1992 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001993 MediaExpectations media_expectations;
1994 media_expectations.ExpectBidirectionalAudioAndVideo();
1995 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001996}
1997
1998// This test sets up a call that's transferred to a new callee with a different
1999// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002000TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002001 ASSERT_TRUE(CreatePeerConnectionWrappers());
2002 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002003 caller()->AddAudioVideoTracks();
2004 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002005 caller()->CreateAndSetAndSignalOffer();
2006 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2007
2008 // Keep the original peer around which will still send packets to the
2009 // receiving client. These SRTP packets will be dropped.
2010 std::unique_ptr<PeerConnectionWrapper> original_peer(
2011 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002012 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002013 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2014 // directly above.
2015 original_peer->pc()->Close();
2016
2017 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002018 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002019 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2020 caller()->CreateAndSetAndSignalOffer();
2021 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2022 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002023 MediaExpectations media_expectations;
2024 media_expectations.ExpectBidirectionalAudioAndVideo();
2025 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002026}
2027
2028// This test sets up a non-bundled call and negotiates bundling at the same
2029// time as starting an ICE restart. When bundling is in effect in the restart,
2030// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002031TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002032 ASSERT_TRUE(CreatePeerConnectionWrappers());
2033 ConnectFakeSignaling();
2034
Steve Anton15324772018-01-16 10:26:49 -08002035 caller()->AddAudioVideoTracks();
2036 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002037 // Remove the bundle group from the SDP received by the callee.
2038 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2039 desc->RemoveGroupByName("BUNDLE");
2040 });
2041 caller()->CreateAndSetAndSignalOffer();
2042 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002043 {
2044 MediaExpectations media_expectations;
2045 media_expectations.ExpectBidirectionalAudioAndVideo();
2046 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2047 }
deadbeef1dcb1642017-03-29 21:08:16 -07002048 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2049 callee()->SetReceivedSdpMunger(nullptr);
2050 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2051 caller()->CreateAndSetAndSignalOffer();
2052 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2053
2054 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002055 {
2056 MediaExpectations media_expectations;
2057 media_expectations.ExpectBidirectionalAudioAndVideo();
2058 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2059 }
deadbeef1dcb1642017-03-29 21:08:16 -07002060}
2061
2062// Test CVO (Coordination of Video Orientation). If a video source is rotated
2063// and both peers support the CVO RTP header extension, the actual video frames
2064// don't need to be encoded in different resolutions, since the rotation is
2065// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002066TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002067 ASSERT_TRUE(CreatePeerConnectionWrappers());
2068 ConnectFakeSignaling();
2069 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002070 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002071 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002072 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002073 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2074
2075 // Wait for video frames to be received by both sides.
2076 caller()->CreateAndSetAndSignalOffer();
2077 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2078 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2079 callee()->min_video_frames_received_per_track() > 0,
2080 kMaxWaitForFramesMs);
2081
2082 // Ensure that the aspect ratio is unmodified.
2083 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2084 // not just assumed.
2085 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2086 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2087 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2088 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2089 // Ensure that the CVO bits were surfaced to the renderer.
2090 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2091 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2092}
2093
2094// Test that when the CVO extension isn't supported, video is rotated the
2095// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002096TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002097 ASSERT_TRUE(CreatePeerConnectionWrappers());
2098 ConnectFakeSignaling();
2099 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002100 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002101 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002102 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002103 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2104
2105 // Remove the CVO extension from the offered SDP.
2106 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2107 cricket::VideoContentDescription* video =
2108 GetFirstVideoContentDescription(desc);
2109 video->ClearRtpHeaderExtensions();
2110 });
2111 // Wait for video frames to be received by both sides.
2112 caller()->CreateAndSetAndSignalOffer();
2113 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2114 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2115 callee()->min_video_frames_received_per_track() > 0,
2116 kMaxWaitForFramesMs);
2117
2118 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2119 // rotation.
2120 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2121 // not just assumed.
2122 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2123 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2124 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2125 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2126 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2127 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2128 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2129}
2130
deadbeef1dcb1642017-03-29 21:08:16 -07002131// Test that if the answerer rejects the audio m= section, no audio is sent or
2132// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002133TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002134 ASSERT_TRUE(CreatePeerConnectionWrappers());
2135 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002136 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002137 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2138 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2139 // it will reject the audio m= section completely.
2140 PeerConnectionInterface::RTCOfferAnswerOptions options;
2141 options.offer_to_receive_audio = 0;
2142 callee()->SetOfferAnswerOptions(options);
2143 } else {
2144 // Stopping the audio RtpTransceiver will cause the media section to be
2145 // rejected in the answer.
2146 callee()->SetRemoteOfferHandler([this] {
2147 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2148 });
2149 }
Steve Anton15324772018-01-16 10:26:49 -08002150 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002151 // Do offer/answer and wait for successful end-to-end video frames.
2152 caller()->CreateAndSetAndSignalOffer();
2153 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002154 MediaExpectations media_expectations;
2155 media_expectations.ExpectBidirectionalVideo();
2156 media_expectations.ExpectNoAudio();
2157 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2158
deadbeef1dcb1642017-03-29 21:08:16 -07002159 // Sanity check that the callee's description has a rejected audio section.
2160 ASSERT_NE(nullptr, callee()->pc()->local_description());
2161 const ContentInfo* callee_audio_content =
2162 GetFirstAudioContent(callee()->pc()->local_description()->description());
2163 ASSERT_NE(nullptr, callee_audio_content);
2164 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002165 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2166 // The caller's transceiver should have stopped after receiving the answer.
2167 EXPECT_TRUE(caller()
2168 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2169 ->stopped());
2170 }
deadbeef1dcb1642017-03-29 21:08:16 -07002171}
2172
2173// Test that if the answerer rejects the video m= section, no video is sent or
2174// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002175TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002176 ASSERT_TRUE(CreatePeerConnectionWrappers());
2177 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002178 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002179 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2180 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2181 // it will reject the video m= section completely.
2182 PeerConnectionInterface::RTCOfferAnswerOptions options;
2183 options.offer_to_receive_video = 0;
2184 callee()->SetOfferAnswerOptions(options);
2185 } else {
2186 // Stopping the video RtpTransceiver will cause the media section to be
2187 // rejected in the answer.
2188 callee()->SetRemoteOfferHandler([this] {
2189 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2190 });
2191 }
Steve Anton15324772018-01-16 10:26:49 -08002192 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002193 // Do offer/answer and wait for successful end-to-end audio frames.
2194 caller()->CreateAndSetAndSignalOffer();
2195 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002196 MediaExpectations media_expectations;
2197 media_expectations.ExpectBidirectionalAudio();
2198 media_expectations.ExpectNoVideo();
2199 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2200
deadbeef1dcb1642017-03-29 21:08:16 -07002201 // Sanity check that the callee's description has a rejected video section.
2202 ASSERT_NE(nullptr, callee()->pc()->local_description());
2203 const ContentInfo* callee_video_content =
2204 GetFirstVideoContent(callee()->pc()->local_description()->description());
2205 ASSERT_NE(nullptr, callee_video_content);
2206 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002207 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2208 // The caller's transceiver should have stopped after receiving the answer.
2209 EXPECT_TRUE(caller()
2210 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2211 ->stopped());
2212 }
deadbeef1dcb1642017-03-29 21:08:16 -07002213}
2214
2215// Test that if the answerer rejects both audio and video m= sections, nothing
2216// bad happens.
2217// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2218// test anything but the fact that negotiation succeeds, which doesn't mean
2219// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002220TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002221 ASSERT_TRUE(CreatePeerConnectionWrappers());
2222 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002223 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002224 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2225 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2226 // will reject both audio and video m= sections.
2227 PeerConnectionInterface::RTCOfferAnswerOptions options;
2228 options.offer_to_receive_audio = 0;
2229 options.offer_to_receive_video = 0;
2230 callee()->SetOfferAnswerOptions(options);
2231 } else {
2232 callee()->SetRemoteOfferHandler([this] {
2233 // Stopping all transceivers will cause all media sections to be rejected.
2234 for (auto transceiver : callee()->pc()->GetTransceivers()) {
2235 transceiver->Stop();
2236 }
2237 });
2238 }
deadbeef1dcb1642017-03-29 21:08:16 -07002239 // Do offer/answer and wait for stable signaling state.
2240 caller()->CreateAndSetAndSignalOffer();
2241 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002242
deadbeef1dcb1642017-03-29 21:08:16 -07002243 // Sanity check that the callee's description has rejected m= sections.
2244 ASSERT_NE(nullptr, callee()->pc()->local_description());
2245 const ContentInfo* callee_audio_content =
2246 GetFirstAudioContent(callee()->pc()->local_description()->description());
2247 ASSERT_NE(nullptr, callee_audio_content);
2248 EXPECT_TRUE(callee_audio_content->rejected);
2249 const ContentInfo* callee_video_content =
2250 GetFirstVideoContent(callee()->pc()->local_description()->description());
2251 ASSERT_NE(nullptr, callee_video_content);
2252 EXPECT_TRUE(callee_video_content->rejected);
2253}
2254
2255// This test sets up an audio and video call between two parties. After the
2256// call runs for a while, the caller sends an updated offer with video being
2257// rejected. Once the re-negotiation is done, the video flow should stop and
2258// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002259TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002260 ASSERT_TRUE(CreatePeerConnectionWrappers());
2261 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002262 caller()->AddAudioVideoTracks();
2263 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002264 caller()->CreateAndSetAndSignalOffer();
2265 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002266 {
2267 MediaExpectations media_expectations;
2268 media_expectations.ExpectBidirectionalAudioAndVideo();
2269 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2270 }
deadbeef1dcb1642017-03-29 21:08:16 -07002271 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002272 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2273 caller()->SetGeneratedSdpMunger(
2274 [](cricket::SessionDescription* description) {
2275 for (cricket::ContentInfo& content : description->contents()) {
2276 if (cricket::IsVideoContent(&content)) {
2277 content.rejected = true;
2278 }
2279 }
2280 });
2281 } else {
2282 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2283 }
deadbeef1dcb1642017-03-29 21:08:16 -07002284 caller()->CreateAndSetAndSignalOffer();
2285 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2286
2287 // Sanity check that the caller's description has a rejected video section.
2288 ASSERT_NE(nullptr, caller()->pc()->local_description());
2289 const ContentInfo* caller_video_content =
2290 GetFirstVideoContent(caller()->pc()->local_description()->description());
2291 ASSERT_NE(nullptr, caller_video_content);
2292 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002293 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002294 {
2295 MediaExpectations media_expectations;
2296 media_expectations.ExpectBidirectionalAudio();
2297 media_expectations.ExpectNoVideo();
2298 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2299 }
deadbeef1dcb1642017-03-29 21:08:16 -07002300}
2301
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002302// Do one offer/answer with audio, another that disables it (rejecting the m=
2303// section), and another that re-enables it. Regression test for:
2304// bugs.webrtc.org/6023
2305TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2306 ASSERT_TRUE(CreatePeerConnectionWrappers());
2307 ConnectFakeSignaling();
2308
2309 // Add audio track, do normal offer/answer.
2310 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2311 caller()->CreateLocalAudioTrack();
2312 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2313 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2314 caller()->CreateAndSetAndSignalOffer();
2315 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2316
2317 // Remove audio track, and set offer_to_receive_audio to false to cause the
2318 // m= section to be completely disabled, not just "recvonly".
2319 caller()->pc()->RemoveTrack(sender);
2320 PeerConnectionInterface::RTCOfferAnswerOptions options;
2321 options.offer_to_receive_audio = 0;
2322 caller()->SetOfferAnswerOptions(options);
2323 caller()->CreateAndSetAndSignalOffer();
2324 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2325
2326 // Add the audio track again, expecting negotiation to succeed and frames to
2327 // flow.
2328 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2329 options.offer_to_receive_audio = 1;
2330 caller()->SetOfferAnswerOptions(options);
2331 caller()->CreateAndSetAndSignalOffer();
2332 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2333
2334 MediaExpectations media_expectations;
2335 media_expectations.CalleeExpectsSomeAudio();
2336 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2337}
2338
deadbeef1dcb1642017-03-29 21:08:16 -07002339// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2340// is needed to support legacy endpoints.
2341// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2342// add a test for an end-to-end test without MID signaling either (basically,
2343// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002344TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002345 ASSERT_TRUE(CreatePeerConnectionWrappers());
2346 ConnectFakeSignaling();
2347 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002348 caller()->AddAudioVideoTracks();
2349 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002350 // Remove SSRCs and MSIDs from the received offer SDP.
2351 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002352 caller()->CreateAndSetAndSignalOffer();
2353 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002354 MediaExpectations media_expectations;
2355 media_expectations.ExpectBidirectionalAudioAndVideo();
2356 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002357}
2358
Seth Hampson5897a6e2018-04-03 11:16:33 -07002359// Basic end-to-end test, without SSRC signaling. This means that the track
2360// was created properly and frames are delivered when the MSIDs are communicated
2361// with a=msid lines and no a=ssrc lines.
2362TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2363 EndToEndCallWithoutSsrcSignaling) {
2364 const char kStreamId[] = "streamId";
2365 ASSERT_TRUE(CreatePeerConnectionWrappers());
2366 ConnectFakeSignaling();
2367 // Add just audio tracks.
2368 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2369 callee()->AddAudioTrack();
2370
2371 // Remove SSRCs from the received offer SDP.
2372 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2373 caller()->CreateAndSetAndSignalOffer();
2374 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2375 MediaExpectations media_expectations;
2376 media_expectations.ExpectBidirectionalAudio();
2377 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2378}
2379
Steve Antondf527fd2018-04-27 15:52:03 -07002380// Tests that video flows between multiple video tracks when SSRCs are not
2381// signaled. This exercises the MID RTP header extension which is needed to
2382// demux the incoming video tracks.
2383TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2384 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2385 ASSERT_TRUE(CreatePeerConnectionWrappers());
2386 ConnectFakeSignaling();
2387 caller()->AddVideoTrack();
2388 caller()->AddVideoTrack();
2389 callee()->AddVideoTrack();
2390 callee()->AddVideoTrack();
2391
2392 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2393 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2394 caller()->CreateAndSetAndSignalOffer();
2395 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2396 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2397 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2398
2399 // Expect video to be received in both directions on both tracks.
2400 MediaExpectations media_expectations;
2401 media_expectations.ExpectBidirectionalVideo();
2402 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2403}
2404
Henrik Boström5b147782018-12-04 11:25:05 +01002405TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2406 ASSERT_TRUE(CreatePeerConnectionWrappers());
2407 ConnectFakeSignaling();
2408 caller()->AddAudioTrack();
2409 caller()->AddVideoTrack();
2410 caller()->CreateAndSetAndSignalOffer();
2411 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2412 auto callee_receivers = callee()->pc()->GetReceivers();
2413 ASSERT_EQ(2u, callee_receivers.size());
2414 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2415 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2416}
2417
2418TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2419 ASSERT_TRUE(CreatePeerConnectionWrappers());
2420 ConnectFakeSignaling();
2421 caller()->AddAudioTrack();
2422 caller()->AddVideoTrack();
2423 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2424 caller()->CreateAndSetAndSignalOffer();
2425 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2426 auto callee_receivers = callee()->pc()->GetReceivers();
2427 ASSERT_EQ(2u, callee_receivers.size());
2428 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2429 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2430 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2431 callee_receivers[1]->stream_ids()[0]);
2432 EXPECT_EQ(callee_receivers[0]->streams()[0],
2433 callee_receivers[1]->streams()[0]);
2434}
2435
deadbeef1dcb1642017-03-29 21:08:16 -07002436// Test that if two video tracks are sent (from caller to callee, in this test),
2437// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002438TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002439 ASSERT_TRUE(CreatePeerConnectionWrappers());
2440 ConnectFakeSignaling();
2441 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002442 caller()->AddAudioVideoTracks();
2443 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002444 caller()->CreateAndSetAndSignalOffer();
2445 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002446 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002447
2448 MediaExpectations media_expectations;
2449 media_expectations.CalleeExpectsSomeAudioAndVideo();
2450 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002451}
2452
2453static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2454 bool first = true;
2455 for (cricket::ContentInfo& content : desc->contents()) {
2456 if (first) {
2457 first = false;
2458 continue;
2459 }
2460 content.bundle_only = true;
2461 }
2462 first = true;
2463 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2464 if (first) {
2465 first = false;
2466 continue;
2467 }
2468 transport.description.ice_ufrag.clear();
2469 transport.description.ice_pwd.clear();
2470 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2471 transport.description.identity_fingerprint.reset(nullptr);
2472 }
2473}
2474
2475// Test that if applying a true "max bundle" offer, which uses ports of 0,
2476// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2477// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2478// successfully and media flows.
2479// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2480// TODO(deadbeef): Won't need this test once we start generating actual
2481// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002482TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002483 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2484 ASSERT_TRUE(CreatePeerConnectionWrappers());
2485 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002486 caller()->AddAudioVideoTracks();
2487 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002488 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2489 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2490 // but the first m= section.
2491 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2492 caller()->CreateAndSetAndSignalOffer();
2493 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002494 MediaExpectations media_expectations;
2495 media_expectations.ExpectBidirectionalAudioAndVideo();
2496 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002497}
2498
2499// Test that we can receive the audio output level from a remote audio track.
2500// TODO(deadbeef): Use a fake audio source and verify that the output level is
2501// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002502TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002503 ASSERT_TRUE(CreatePeerConnectionWrappers());
2504 ConnectFakeSignaling();
2505 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002506 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002507 caller()->CreateAndSetAndSignalOffer();
2508 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2509
2510 // Get the audio output level stats. Note that the level is not available
2511 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002512 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002513 kMaxWaitForFramesMs);
2514}
2515
2516// Test that an audio input level is reported.
2517// TODO(deadbeef): Use a fake audio source and verify that the input level is
2518// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002519TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002520 ASSERT_TRUE(CreatePeerConnectionWrappers());
2521 ConnectFakeSignaling();
2522 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002523 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002524 caller()->CreateAndSetAndSignalOffer();
2525 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2526
2527 // Get the audio input level stats. The level should be available very
2528 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002529 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002530 kMaxWaitForStatsMs);
2531}
2532
2533// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002534TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002535 ASSERT_TRUE(CreatePeerConnectionWrappers());
2536 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002537 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002538 // Do offer/answer, wait for the callee to receive some frames.
2539 caller()->CreateAndSetAndSignalOffer();
2540 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002541
2542 MediaExpectations media_expectations;
2543 media_expectations.CalleeExpectsSomeAudioAndVideo();
2544 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002545
2546 // Get a handle to the remote tracks created, so they can be used as GetStats
2547 // filters.
Steve Anton15324772018-01-16 10:26:49 -08002548 for (auto receiver : callee()->pc()->GetReceivers()) {
2549 // We received frames, so we definitely should have nonzero "received bytes"
2550 // stats at this point.
2551 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2552 0);
2553 }
deadbeef1dcb1642017-03-29 21:08:16 -07002554}
2555
2556// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002557TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002558 ASSERT_TRUE(CreatePeerConnectionWrappers());
2559 ConnectFakeSignaling();
2560 auto audio_track = caller()->CreateLocalAudioTrack();
2561 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002562 caller()->AddTrack(audio_track);
2563 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002564 // Do offer/answer, wait for the callee to receive some frames.
2565 caller()->CreateAndSetAndSignalOffer();
2566 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002567 MediaExpectations media_expectations;
2568 media_expectations.CalleeExpectsSomeAudioAndVideo();
2569 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002570
2571 // The callee received frames, so we definitely should have nonzero "sent
2572 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002573 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2574 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2575}
2576
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002577// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002578TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002579 ASSERT_TRUE(CreatePeerConnectionWrappers());
2580 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002581 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002582
Steve Anton15324772018-01-16 10:26:49 -08002583 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002584
2585 // Do offer/answer, wait for the callee to receive some frames.
2586 caller()->CreateAndSetAndSignalOffer();
2587 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2588
2589 // Get the remote audio track created on the receiver, so they can be used as
2590 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002591 auto receivers = callee()->pc()->GetReceivers();
2592 ASSERT_EQ(1u, receivers.size());
2593 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002594
2595 // Get the audio output level stats. Note that the level is not available
2596 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002597 EXPECT_TRUE_WAIT(
2598 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2599 0,
2600 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002601}
2602
Steve Antona41959e2018-11-28 11:15:33 -08002603// Test that the track ID is associated with all local and remote SSRC stats
2604// using the old GetStats() and more than 1 audio and more than 1 video track.
2605// This is a regression test for crbug.com/906988
2606TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2607 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2608 ASSERT_TRUE(CreatePeerConnectionWrappers());
2609 ConnectFakeSignaling();
2610 auto audio_sender_1 = caller()->AddAudioTrack();
2611 auto video_sender_1 = caller()->AddVideoTrack();
2612 auto audio_sender_2 = caller()->AddAudioTrack();
2613 auto video_sender_2 = caller()->AddVideoTrack();
2614 caller()->CreateAndSetAndSignalOffer();
2615 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2616
2617 MediaExpectations media_expectations;
2618 media_expectations.CalleeExpectsSomeAudioAndVideo();
2619 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2620
2621 std::vector<std::string> track_ids = {
2622 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2623 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2624
2625 auto caller_stats = caller()->OldGetStats();
2626 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2627 auto callee_stats = callee()->OldGetStats();
2628 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2629}
2630
Steve Antonffa6ce42018-11-30 09:26:08 -08002631// Test that the new GetStats() returns stats for all outgoing/incoming streams
2632// with the correct track IDs if there are more than one audio and more than one
2633// video senders/receivers.
2634TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2635 ASSERT_TRUE(CreatePeerConnectionWrappers());
2636 ConnectFakeSignaling();
2637 auto audio_sender_1 = caller()->AddAudioTrack();
2638 auto video_sender_1 = caller()->AddVideoTrack();
2639 auto audio_sender_2 = caller()->AddAudioTrack();
2640 auto video_sender_2 = caller()->AddVideoTrack();
2641 caller()->CreateAndSetAndSignalOffer();
2642 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2643
2644 MediaExpectations media_expectations;
2645 media_expectations.CalleeExpectsSomeAudioAndVideo();
2646 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2647
2648 std::vector<std::string> track_ids = {
2649 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2650 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2651
2652 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2653 caller()->NewGetStats();
2654 ASSERT_TRUE(caller_report);
2655 auto outbound_stream_stats =
2656 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2657 ASSERT_EQ(4u, outbound_stream_stats.size());
2658 std::vector<std::string> outbound_track_ids;
2659 for (const auto& stat : outbound_stream_stats) {
2660 ASSERT_TRUE(stat->bytes_sent.is_defined());
2661 EXPECT_LT(0u, *stat->bytes_sent);
2662 ASSERT_TRUE(stat->track_id.is_defined());
2663 const auto* track_stat =
2664 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2665 ASSERT_TRUE(track_stat);
2666 outbound_track_ids.push_back(*track_stat->track_identifier);
2667 }
2668 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2669
2670 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2671 callee()->NewGetStats();
2672 ASSERT_TRUE(callee_report);
2673 auto inbound_stream_stats =
2674 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2675 ASSERT_EQ(4u, inbound_stream_stats.size());
2676 std::vector<std::string> inbound_track_ids;
2677 for (const auto& stat : inbound_stream_stats) {
2678 ASSERT_TRUE(stat->bytes_received.is_defined());
2679 EXPECT_LT(0u, *stat->bytes_received);
2680 ASSERT_TRUE(stat->track_id.is_defined());
2681 const auto* track_stat =
2682 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2683 ASSERT_TRUE(track_stat);
2684 inbound_track_ids.push_back(*track_stat->track_identifier);
2685 }
2686 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2687}
2688
2689// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002690// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2691// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002692TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002693 GetStatsForUnsignaledStreamWithNewStatsApi) {
2694 ASSERT_TRUE(CreatePeerConnectionWrappers());
2695 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002696 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002697 // Remove SSRCs and MSIDs from the received offer SDP.
2698 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2699 caller()->CreateAndSetAndSignalOffer();
2700 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002701 MediaExpectations media_expectations;
2702 media_expectations.CalleeExpectsSomeAudio(1);
2703 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002704
2705 // We received a frame, so we should have nonzero "bytes received" stats for
2706 // the unsignaled stream, if stats are working for it.
2707 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2708 callee()->NewGetStats();
2709 ASSERT_NE(nullptr, report);
2710 auto inbound_stream_stats =
2711 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2712 ASSERT_EQ(1U, inbound_stream_stats.size());
2713 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2714 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002715 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2716}
2717
Taylor Brandstettera4653442018-06-19 09:44:26 -07002718// Same as above but for the legacy stats implementation.
2719TEST_P(PeerConnectionIntegrationTest,
2720 GetStatsForUnsignaledStreamWithOldStatsApi) {
2721 ASSERT_TRUE(CreatePeerConnectionWrappers());
2722 ConnectFakeSignaling();
2723 caller()->AddAudioTrack();
2724 // Remove SSRCs and MSIDs from the received offer SDP.
2725 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2726 caller()->CreateAndSetAndSignalOffer();
2727 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2728
2729 // Note that, since the old stats implementation associates SSRCs with tracks
2730 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2731 // associated track ID. So we can't use the track "selector" argument.
2732 //
2733 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2734 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002735 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002736 kDefaultTimeout);
2737}
2738
zhihuangf8164932017-05-19 13:09:47 -07002739// Test that we can successfully get the media related stats (audio level
2740// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002741TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002742 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2743 ASSERT_TRUE(CreatePeerConnectionWrappers());
2744 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002745 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002746 // Remove SSRCs and MSIDs from the received offer SDP.
2747 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2748 caller()->CreateAndSetAndSignalOffer();
2749 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002750 MediaExpectations media_expectations;
2751 media_expectations.CalleeExpectsSomeAudio(1);
2752 media_expectations.CalleeExpectsSomeVideo(1);
2753 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002754
2755 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2756 callee()->NewGetStats();
2757 ASSERT_NE(nullptr, report);
2758
2759 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2760 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2761 ASSERT_GE(audio_index, 0);
2762 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002763}
2764
deadbeef4e2deab2017-09-20 13:56:21 -07002765// Helper for test below.
2766void ModifySsrcs(cricket::SessionDescription* desc) {
2767 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002768 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002769 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002770 for (uint32_t& ssrc : stream.ssrcs) {
2771 ssrc = rtc::CreateRandomId();
2772 }
2773 }
2774 }
2775}
2776
2777// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2778// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2779// This should result in two "RTCInboundRTPStreamStats", but only one
2780// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2781// being reset to 0 once the SSRC change occurs.
2782//
2783// Regression test for this bug:
2784// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2785//
2786// The bug causes the track stats to only represent one of the two streams:
2787// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2788// that the track stat counters would reset to 0 when the new stream is
2789// received, and a 50% chance that they'll stop updating (while
2790// "concealed_samples" continues increasing, due to silence being generated for
2791// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002792TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002793 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002794 ASSERT_TRUE(CreatePeerConnectionWrappers());
2795 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002796 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002797 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2798 // that doesn't signal SSRCs (from the callee's perspective).
2799 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2800 caller()->CreateAndSetAndSignalOffer();
2801 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2802 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002803 {
2804 MediaExpectations media_expectations;
2805 media_expectations.CalleeExpectsSomeAudio(50);
2806 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2807 }
deadbeef4e2deab2017-09-20 13:56:21 -07002808 // Some audio frames were received, so we should have nonzero "samples
2809 // received" for the track.
2810 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2811 callee()->NewGetStats();
2812 ASSERT_NE(nullptr, report);
2813 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2814 ASSERT_EQ(1U, track_stats.size());
2815 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2816 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2817 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2818
2819 // Create a new offer and munge it to cause the caller to use a new SSRC.
2820 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2821 caller()->CreateAndSetAndSignalOffer();
2822 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2823 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2824 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002825 {
2826 MediaExpectations media_expectations;
2827 media_expectations.CalleeExpectsSomeAudio(25);
2828 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2829 }
deadbeef4e2deab2017-09-20 13:56:21 -07002830
2831 report = callee()->NewGetStats();
2832 ASSERT_NE(nullptr, report);
2833 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2834 ASSERT_EQ(1U, track_stats.size());
2835 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2836 // The "total samples received" stat should only be greater than it was
2837 // before.
2838 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2839 // Right now, the new SSRC will cause the counters to reset to 0.
2840 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2841
2842 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002843 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002844 // good sign that we're seeing stats from the old stream that's no longer
2845 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002846 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002847 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2848 EXPECT_LT(*track_stats[0]->concealed_samples,
2849 *track_stats[0]->total_samples_received *
2850 kAcceptableConcealedSamplesPercentage);
2851
2852 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2853 // sanity check that the SSRC really changed.
2854 // TODO(deadbeef): This isn't working right now, because we're not returning
2855 // *any* stats for the inactive stream. Uncomment when the bug is completely
2856 // fixed.
2857 // auto inbound_stream_stats =
2858 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2859 // ASSERT_EQ(2U, inbound_stream_stats.size());
2860}
2861
deadbeef1dcb1642017-03-29 21:08:16 -07002862// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002863TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002864 PeerConnectionFactory::Options dtls_10_options;
2865 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2866 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2867 dtls_10_options));
2868 ConnectFakeSignaling();
2869 // Do normal offer/answer and wait for some frames to be received in each
2870 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002871 caller()->AddAudioVideoTracks();
2872 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002873 caller()->CreateAndSetAndSignalOffer();
2874 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002875 MediaExpectations media_expectations;
2876 media_expectations.ExpectBidirectionalAudioAndVideo();
2877 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002878}
2879
2880// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002881TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002882 PeerConnectionFactory::Options dtls_10_options;
2883 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2884 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2885 dtls_10_options));
2886 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002887 caller()->AddAudioVideoTracks();
2888 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002889 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002890 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002891 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002892 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002893 kDefaultTimeout);
2894 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002895 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002896 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002897 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002898 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2899 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002900}
2901
2902// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002903TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002904 PeerConnectionFactory::Options dtls_12_options;
2905 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2906 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2907 dtls_12_options));
2908 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002909 caller()->AddAudioVideoTracks();
2910 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002911 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002912 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002913 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002914 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002915 kDefaultTimeout);
2916 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002917 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002918 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002919 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002920 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2921 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002922}
2923
2924// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2925// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002926TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002927 PeerConnectionFactory::Options caller_options;
2928 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2929 PeerConnectionFactory::Options callee_options;
2930 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2931 ASSERT_TRUE(
2932 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2933 ConnectFakeSignaling();
2934 // Do normal offer/answer and wait for some frames to be received in each
2935 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002936 caller()->AddAudioVideoTracks();
2937 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002938 caller()->CreateAndSetAndSignalOffer();
2939 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002940 MediaExpectations media_expectations;
2941 media_expectations.ExpectBidirectionalAudioAndVideo();
2942 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002943}
2944
2945// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2946// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002947TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07002948 PeerConnectionFactory::Options caller_options;
2949 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2950 PeerConnectionFactory::Options callee_options;
2951 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2952 ASSERT_TRUE(
2953 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2954 ConnectFakeSignaling();
2955 // Do normal offer/answer and wait for some frames to be received in each
2956 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002957 caller()->AddAudioVideoTracks();
2958 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002959 caller()->CreateAndSetAndSignalOffer();
2960 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002961 MediaExpectations media_expectations;
2962 media_expectations.ExpectBidirectionalAudioAndVideo();
2963 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002964}
2965
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002966// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
2967// works as expected; the cipher should only be used if enabled by both sides.
2968TEST_P(PeerConnectionIntegrationTest,
2969 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
2970 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002971 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002972 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002973 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
2974 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002975 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2976 TestNegotiatedCipherSuite(caller_options, callee_options,
2977 expected_cipher_suite);
2978}
2979
2980TEST_P(PeerConnectionIntegrationTest,
2981 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
2982 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002983 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
2984 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002985 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002986 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002987 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
2988 TestNegotiatedCipherSuite(caller_options, callee_options,
2989 expected_cipher_suite);
2990}
2991
2992TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
2993 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002994 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002995 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07002996 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07002997 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
2998 TestNegotiatedCipherSuite(caller_options, callee_options,
2999 expected_cipher_suite);
3000}
3001
deadbeef1dcb1642017-03-29 21:08:16 -07003002// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003003TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003004 bool local_gcm_enabled = false;
3005 bool remote_gcm_enabled = false;
3006 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3007 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3008 expected_cipher_suite);
3009}
3010
3011// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003012TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003013 bool local_gcm_enabled = true;
3014 bool remote_gcm_enabled = true;
3015 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3016 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3017 expected_cipher_suite);
3018}
3019
3020// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003021TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003022 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
3023 bool local_gcm_enabled = true;
3024 bool remote_gcm_enabled = false;
3025 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3026 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3027 expected_cipher_suite);
3028}
3029
3030// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003031TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003032 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
3033 bool local_gcm_enabled = false;
3034 bool remote_gcm_enabled = true;
3035 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3036 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3037 expected_cipher_suite);
3038}
3039
deadbeef7914b8c2017-04-21 03:23:33 -07003040// Verify that media can be transmitted end-to-end when GCM crypto suites are
3041// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3042// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3043// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003044TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003045 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003046 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07003047 ASSERT_TRUE(
3048 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3049 ConnectFakeSignaling();
3050 // Do normal offer/answer and wait for some frames to be received in each
3051 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003052 caller()->AddAudioVideoTracks();
3053 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003054 caller()->CreateAndSetAndSignalOffer();
3055 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003056 MediaExpectations media_expectations;
3057 media_expectations.ExpectBidirectionalAudioAndVideo();
3058 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003059}
3060
deadbeef1dcb1642017-03-29 21:08:16 -07003061// This test sets up a call between two parties with audio, video and an RTP
3062// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003063TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003064 PeerConnectionInterface::RTCConfiguration rtc_config;
3065 rtc_config.enable_rtp_data_channel = true;
3066 rtc_config.enable_dtls_srtp = false;
3067 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003068 ConnectFakeSignaling();
3069 // Expect that data channel created on caller side will show up for callee as
3070 // well.
3071 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003072 caller()->AddAudioVideoTracks();
3073 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003074 caller()->CreateAndSetAndSignalOffer();
3075 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3076 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003077 MediaExpectations media_expectations;
3078 media_expectations.ExpectBidirectionalAudioAndVideo();
3079 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003080 ASSERT_NE(nullptr, caller()->data_channel());
3081 ASSERT_NE(nullptr, callee()->data_channel());
3082 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3083 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3084
3085 // Ensure data can be sent in both directions.
3086 std::string data = "hello world";
3087 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3088 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3089 kDefaultTimeout);
3090 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3091 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3092 kDefaultTimeout);
3093}
3094
3095// Ensure that an RTP data channel is signaled as closed for the caller when
3096// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003097TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003098 RtpDataChannelSignaledClosedInCalleeOffer) {
3099 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003100 PeerConnectionInterface::RTCConfiguration rtc_config;
3101 rtc_config.enable_rtp_data_channel = true;
3102 rtc_config.enable_dtls_srtp = false;
3103 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003104 ConnectFakeSignaling();
3105 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003106 caller()->AddAudioVideoTracks();
3107 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003108 caller()->CreateAndSetAndSignalOffer();
3109 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3110 ASSERT_NE(nullptr, caller()->data_channel());
3111 ASSERT_NE(nullptr, callee()->data_channel());
3112 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3113 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3114
3115 // Close the data channel on the callee, and do an updated offer/answer.
3116 callee()->data_channel()->Close();
3117 callee()->CreateAndSetAndSignalOffer();
3118 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3119 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3120 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3121}
3122
3123// Tests that data is buffered in an RTP data channel until an observer is
3124// registered for it.
3125//
3126// NOTE: RTP data channels can receive data before the underlying
3127// transport has detected that a channel is writable and thus data can be
3128// received before the data channel state changes to open. That is hard to test
3129// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003130TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003131 DataBufferedUntilRtpDataChannelObserverRegistered) {
3132 // Use fake clock and simulated network delay so that we predictably can wait
3133 // until an SCTP message has been delivered without "sleep()"ing.
3134 rtc::ScopedFakeClock fake_clock;
3135 // Some things use a time of "0" as a special value, so we need to start out
3136 // the fake clock at a nonzero time.
3137 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003138 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003139 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3140 virtual_socket_server()->UpdateDelayDistribution();
3141
Niels Möllerf06f9232018-08-07 12:32:18 +02003142 PeerConnectionInterface::RTCConfiguration rtc_config;
3143 rtc_config.enable_rtp_data_channel = true;
3144 rtc_config.enable_dtls_srtp = false;
3145 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003146 ConnectFakeSignaling();
3147 caller()->CreateDataChannel();
3148 caller()->CreateAndSetAndSignalOffer();
3149 ASSERT_TRUE(caller()->data_channel() != nullptr);
3150 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3151 kDefaultTimeout, fake_clock);
3152 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3153 kDefaultTimeout, fake_clock);
3154 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3155 callee()->data_channel()->state(), kDefaultTimeout,
3156 fake_clock);
3157
3158 // Unregister the observer which is normally automatically registered.
3159 callee()->data_channel()->UnregisterObserver();
3160 // Send data and advance fake clock until it should have been received.
3161 std::string data = "hello world";
3162 caller()->data_channel()->Send(DataBuffer(data));
3163 SIMULATED_WAIT(false, 50, fake_clock);
3164
3165 // Attach data channel and expect data to be received immediately. Note that
3166 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3167 // further, but data can be received even if the callback is asynchronous.
3168 MockDataChannelObserver new_observer(callee()->data_channel());
3169 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3170 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003171 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3172 // If this is not done a DCHECK can be hit in ports.cc, because a large
3173 // negative number is calculated for the rtt due to the global clock changing.
3174 caller()->pc()->Close();
3175 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07003176}
3177
3178// This test sets up a call between two parties with audio, video and but only
3179// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003180TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003181 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3182 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003183 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003184 rtc_config_1.enable_dtls_srtp = false;
3185 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3186 rtc_config_2.enable_dtls_srtp = false;
3187 rtc_config_2.enable_dtls_srtp = false;
3188 ASSERT_TRUE(
3189 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003190 ConnectFakeSignaling();
3191 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003192 caller()->AddAudioVideoTracks();
3193 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003194 caller()->CreateAndSetAndSignalOffer();
3195 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3196 // The caller should still have a data channel, but it should be closed, and
3197 // one should ever have been created for the callee.
3198 EXPECT_TRUE(caller()->data_channel() != nullptr);
3199 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3200 EXPECT_EQ(nullptr, callee()->data_channel());
3201}
3202
3203// This test sets up a call between two parties with audio, and video. When
3204// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003205TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003206 PeerConnectionInterface::RTCConfiguration rtc_config;
3207 rtc_config.enable_rtp_data_channel = true;
3208 rtc_config.enable_dtls_srtp = false;
3209 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003210 ConnectFakeSignaling();
3211 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003212 caller()->AddAudioVideoTracks();
3213 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003214 caller()->CreateAndSetAndSignalOffer();
3215 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3216 // Create data channel and do new offer and answer.
3217 caller()->CreateDataChannel();
3218 caller()->CreateAndSetAndSignalOffer();
3219 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3220 ASSERT_NE(nullptr, caller()->data_channel());
3221 ASSERT_NE(nullptr, callee()->data_channel());
3222 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3223 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3224 // Ensure data can be sent in both directions.
3225 std::string data = "hello world";
3226 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3227 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3228 kDefaultTimeout);
3229 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3230 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3231 kDefaultTimeout);
3232}
3233
3234#ifdef HAVE_SCTP
3235
3236// This test sets up a call between two parties with audio, video and an SCTP
3237// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003238TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003239 ASSERT_TRUE(CreatePeerConnectionWrappers());
3240 ConnectFakeSignaling();
3241 // Expect that data channel created on caller side will show up for callee as
3242 // well.
3243 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003244 caller()->AddAudioVideoTracks();
3245 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003246 caller()->CreateAndSetAndSignalOffer();
3247 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3248 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003249 MediaExpectations media_expectations;
3250 media_expectations.ExpectBidirectionalAudioAndVideo();
3251 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003252 // Caller data channel should already exist (it created one). Callee data
3253 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3254 ASSERT_NE(nullptr, caller()->data_channel());
3255 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3256 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3257 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3258
3259 // Ensure data can be sent in both directions.
3260 std::string data = "hello world";
3261 caller()->data_channel()->Send(DataBuffer(data));
3262 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3263 kDefaultTimeout);
3264 callee()->data_channel()->Send(DataBuffer(data));
3265 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3266 kDefaultTimeout);
3267}
3268
3269// Ensure that when the callee closes an SCTP data channel, the closing
3270// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003271TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003272 // Same procedure as above test.
3273 ASSERT_TRUE(CreatePeerConnectionWrappers());
3274 ConnectFakeSignaling();
3275 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003276 caller()->AddAudioVideoTracks();
3277 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003278 caller()->CreateAndSetAndSignalOffer();
3279 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3280 ASSERT_NE(nullptr, caller()->data_channel());
3281 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3282 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3283 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3284
3285 // Close the data channel on the callee side, and wait for it to reach the
3286 // "closed" state on both sides.
3287 callee()->data_channel()->Close();
3288 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3289 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3290}
3291
Seth Hampson2f0d7022018-02-20 11:54:42 -08003292TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003293 ASSERT_TRUE(CreatePeerConnectionWrappers());
3294 ConnectFakeSignaling();
3295 webrtc::DataChannelInit init;
3296 init.id = 53;
3297 init.maxRetransmits = 52;
3298 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003299 caller()->AddAudioVideoTracks();
3300 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003301 caller()->CreateAndSetAndSignalOffer();
3302 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003303 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3304 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Steve Antonda6c0952017-10-23 11:41:54 -07003305 EXPECT_EQ(init.id, callee()->data_channel()->id());
3306 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3307 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3308 EXPECT_FALSE(callee()->data_channel()->negotiated());
3309}
3310
deadbeef1dcb1642017-03-29 21:08:16 -07003311// Test usrsctp's ability to process unordered data stream, where data actually
3312// arrives out of order using simulated delays. Previously there have been some
3313// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003314TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003315 // Introduce random network delays.
3316 // Otherwise it's not a true "unordered" test.
3317 virtual_socket_server()->set_delay_mean(20);
3318 virtual_socket_server()->set_delay_stddev(5);
3319 virtual_socket_server()->UpdateDelayDistribution();
3320 // Normal procedure, but with unordered data channel config.
3321 ASSERT_TRUE(CreatePeerConnectionWrappers());
3322 ConnectFakeSignaling();
3323 webrtc::DataChannelInit init;
3324 init.ordered = false;
3325 caller()->CreateDataChannel(&init);
3326 caller()->CreateAndSetAndSignalOffer();
3327 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3328 ASSERT_NE(nullptr, caller()->data_channel());
3329 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3330 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3331 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3332
3333 static constexpr int kNumMessages = 100;
3334 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3335 static constexpr size_t kMaxMessageSize = 4096;
3336 // Create and send random messages.
3337 std::vector<std::string> sent_messages;
3338 for (int i = 0; i < kNumMessages; ++i) {
3339 size_t length =
3340 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3341 std::string message;
3342 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3343 caller()->data_channel()->Send(DataBuffer(message));
3344 callee()->data_channel()->Send(DataBuffer(message));
3345 sent_messages.push_back(message);
3346 }
3347
3348 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003349 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003350 caller()->data_observer()->received_message_count(),
3351 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003352 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003353 callee()->data_observer()->received_message_count(),
3354 kDefaultTimeout);
3355
3356 // Sort and compare to make sure none of the messages were corrupted.
3357 std::vector<std::string> caller_received_messages =
3358 caller()->data_observer()->messages();
3359 std::vector<std::string> callee_received_messages =
3360 callee()->data_observer()->messages();
3361 std::sort(sent_messages.begin(), sent_messages.end());
3362 std::sort(caller_received_messages.begin(), caller_received_messages.end());
3363 std::sort(callee_received_messages.begin(), callee_received_messages.end());
3364 EXPECT_EQ(sent_messages, caller_received_messages);
3365 EXPECT_EQ(sent_messages, callee_received_messages);
3366}
3367
3368// This test sets up a call between two parties with audio, and video. When
3369// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003370TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003371 ASSERT_TRUE(CreatePeerConnectionWrappers());
3372 ConnectFakeSignaling();
3373 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003374 caller()->AddAudioVideoTracks();
3375 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003376 caller()->CreateAndSetAndSignalOffer();
3377 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3378 // Create data channel and do new offer and answer.
3379 caller()->CreateDataChannel();
3380 caller()->CreateAndSetAndSignalOffer();
3381 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3382 // Caller data channel should already exist (it created one). Callee data
3383 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3384 ASSERT_NE(nullptr, caller()->data_channel());
3385 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3386 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3387 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3388 // Ensure data can be sent in both directions.
3389 std::string data = "hello world";
3390 caller()->data_channel()->Send(DataBuffer(data));
3391 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3392 kDefaultTimeout);
3393 callee()->data_channel()->Send(DataBuffer(data));
3394 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3395 kDefaultTimeout);
3396}
3397
deadbeef7914b8c2017-04-21 03:23:33 -07003398// Set up a connection initially just using SCTP data channels, later upgrading
3399// to audio/video, ensuring frames are received end-to-end. Effectively the
3400// inverse of the test above.
3401// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003402TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003403 ASSERT_TRUE(CreatePeerConnectionWrappers());
3404 ConnectFakeSignaling();
3405 // Do initial offer/answer with just data channel.
3406 caller()->CreateDataChannel();
3407 caller()->CreateAndSetAndSignalOffer();
3408 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3409 // Wait until data can be sent over the data channel.
3410 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3411 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3412 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3413
3414 // Do subsequent offer/answer with two-way audio and video. Audio and video
3415 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003416 caller()->AddAudioVideoTracks();
3417 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003418 caller()->CreateAndSetAndSignalOffer();
3419 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003420 MediaExpectations media_expectations;
3421 media_expectations.ExpectBidirectionalAudioAndVideo();
3422 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003423}
3424
deadbeef8b7e9ad2017-05-25 09:38:55 -07003425static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
deadbeef8b7e9ad2017-05-25 09:38:55 -07003426 cricket::DataContentDescription* dcd_offer =
Steve Antonb1c1de12017-12-21 15:14:30 -08003427 GetFirstDataContentDescription(desc);
3428 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003429 dcd_offer->set_use_sctpmap(false);
3430 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3431}
3432
3433// Test that the data channel works when a spec-compliant SCTP m= section is
3434// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3435// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003436TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003437 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3438 ASSERT_TRUE(CreatePeerConnectionWrappers());
3439 ConnectFakeSignaling();
3440 caller()->CreateDataChannel();
3441 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3442 caller()->CreateAndSetAndSignalOffer();
3443 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3444 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3445 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3446 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3447
3448 // Ensure data can be sent in both directions.
3449 std::string data = "hello world";
3450 caller()->data_channel()->Send(DataBuffer(data));
3451 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3452 kDefaultTimeout);
3453 callee()->data_channel()->Send(DataBuffer(data));
3454 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3455 kDefaultTimeout);
3456}
3457
deadbeef1dcb1642017-03-29 21:08:16 -07003458#endif // HAVE_SCTP
3459
Bjorn Mellema2eb0a72018-11-09 10:13:51 -08003460// This test sets up a call between two parties with a media transport data
3461// channel.
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003462TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelEndToEnd) {
3463 PeerConnectionInterface::RTCConfiguration rtc_config;
3464 rtc_config.use_media_transport_for_data_channels = true;
3465 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3466 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3467 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3468 loopback_media_transports()->second_factory()));
3469 ConnectFakeSignaling();
3470
3471 // Expect that data channel created on caller side will show up for callee as
3472 // well.
3473 caller()->CreateDataChannel();
3474 caller()->CreateAndSetAndSignalOffer();
3475 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3476
3477 // Ensure that the media transport is ready.
3478 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3479 loopback_media_transports()->FlushAsyncInvokes();
3480
3481 // Caller data channel should already exist (it created one). Callee data
3482 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3483 ASSERT_NE(nullptr, caller()->data_channel());
3484 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3485 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3486 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3487
3488 // Ensure data can be sent in both directions.
3489 std::string data = "hello world";
3490 caller()->data_channel()->Send(DataBuffer(data));
3491 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3492 kDefaultTimeout);
3493 callee()->data_channel()->Send(DataBuffer(data));
3494 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3495 kDefaultTimeout);
3496}
3497
3498// Ensure that when the callee closes a media transport data channel, the
3499// closing procedure results in the data channel being closed for the caller
3500// as well.
3501TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelCalleeCloses) {
3502 PeerConnectionInterface::RTCConfiguration rtc_config;
3503 rtc_config.use_media_transport_for_data_channels = true;
3504 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3505 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3506 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3507 loopback_media_transports()->second_factory()));
3508 ConnectFakeSignaling();
3509
3510 // Create a data channel on the caller and signal it to the callee.
3511 caller()->CreateDataChannel();
3512 caller()->CreateAndSetAndSignalOffer();
3513 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3514
3515 // Ensure that the media transport is ready.
3516 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3517 loopback_media_transports()->FlushAsyncInvokes();
3518
3519 // Data channels exist and open on both ends of the connection.
3520 ASSERT_NE(nullptr, caller()->data_channel());
3521 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3522 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3523 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3524
3525 // Close the data channel on the callee side, and wait for it to reach the
3526 // "closed" state on both sides.
3527 callee()->data_channel()->Close();
3528 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3529 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3530}
3531
3532TEST_P(PeerConnectionIntegrationTest,
3533 MediaTransportDataChannelConfigSentToOtherSide) {
3534 PeerConnectionInterface::RTCConfiguration rtc_config;
3535 rtc_config.use_media_transport_for_data_channels = true;
3536 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3537 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3538 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3539 loopback_media_transports()->second_factory()));
3540 ConnectFakeSignaling();
3541
3542 // Create a data channel with a non-default configuration and signal it to the
3543 // callee.
3544 webrtc::DataChannelInit init;
3545 init.id = 53;
3546 init.maxRetransmits = 52;
3547 caller()->CreateDataChannel("data-channel", &init);
3548 caller()->CreateAndSetAndSignalOffer();
3549 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3550
3551 // Ensure that the media transport is ready.
3552 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3553 loopback_media_transports()->FlushAsyncInvokes();
3554
3555 // Ensure that the data channel exists on the callee with the correct
3556 // configuration.
3557 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3558 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3559 EXPECT_EQ(init.id, callee()->data_channel()->id());
3560 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3561 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3562 EXPECT_FALSE(callee()->data_channel()->negotiated());
3563}
3564
Niels Möllerc68d2822018-11-20 14:52:05 +01003565TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalAudio) {
3566 PeerConnectionInterface::RTCConfiguration rtc_config;
3567 rtc_config.use_media_transport = true;
3568 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3569 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3570 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3571 loopback_media_transports()->second_factory()));
3572 ConnectFakeSignaling();
3573
3574 caller()->AddAudioTrack();
3575 callee()->AddAudioTrack();
3576 // Start offer/answer exchange and wait for it to complete.
3577 caller()->CreateAndSetAndSignalOffer();
3578 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3579
3580 // Ensure that the media transport is ready.
3581 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3582 loopback_media_transports()->FlushAsyncInvokes();
3583
3584 MediaExpectations media_expectations;
3585 media_expectations.ExpectBidirectionalAudio();
3586 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3587
3588 webrtc::MediaTransportPair::Stats first_stats =
3589 loopback_media_transports()->FirstStats();
3590 webrtc::MediaTransportPair::Stats second_stats =
3591 loopback_media_transports()->SecondStats();
3592
3593 EXPECT_GT(first_stats.received_audio_frames, 0);
3594 EXPECT_GE(second_stats.sent_audio_frames, first_stats.received_audio_frames);
3595
3596 EXPECT_GT(second_stats.received_audio_frames, 0);
3597 EXPECT_GE(first_stats.sent_audio_frames, second_stats.received_audio_frames);
3598}
3599
deadbeef1dcb1642017-03-29 21:08:16 -07003600// Test that the ICE connection and gathering states eventually reach
3601// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003602TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003603 ASSERT_TRUE(CreatePeerConnectionWrappers());
3604 ConnectFakeSignaling();
3605 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003606 caller()->AddAudioVideoTracks();
3607 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003608 caller()->CreateAndSetAndSignalOffer();
3609 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3610 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3611 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3612 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3613 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3614 // After the best candidate pair is selected and all candidates are signaled,
3615 // the ICE connection state should reach "complete".
3616 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3617 // answerer/"callee" by default) only reaches "connected". When this is
3618 // fixed, this test should be updated.
3619 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3620 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00003621 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3622 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003623}
3624
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003625constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
3626 cricket::PORTALLOCATOR_DISABLE_RELAY |
3627 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003628
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003629// Use a mock resolver to resolve the hostname back to the original IP on both
3630// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003631TEST_P(PeerConnectionIntegrationTest,
3632 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003633 auto caller_resolver_factory =
3634 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3635 auto callee_resolver_factory =
3636 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3637 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
3638 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003639
3640 // This also verifies that the injected AsyncResolverFactory is used by
3641 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003642 EXPECT_CALL(*caller_resolver_factory, Create())
3643 .WillOnce(Return(&caller_async_resolver));
3644 webrtc::PeerConnectionDependencies caller_deps(nullptr);
3645 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
3646
3647 EXPECT_CALL(*callee_resolver_factory, Create())
3648 .WillOnce(Return(&callee_async_resolver));
3649 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3650 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
3651
3652 PeerConnectionInterface::RTCConfiguration config;
3653 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3654 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3655
3656 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3657 config, std::move(caller_deps), config, std::move(callee_deps)));
3658
3659 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
3660 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
3661
3662 // Enable hostname candidates with mDNS names.
3663 caller()->network()->CreateMdnsResponder(network_thread());
3664 callee()->network()->CreateMdnsResponder(network_thread());
3665
3666 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003667
3668 ConnectFakeSignaling();
3669 caller()->AddAudioVideoTracks();
3670 callee()->AddAudioVideoTracks();
3671 caller()->CreateAndSetAndSignalOffer();
3672 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3673 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3674 caller()->ice_connection_state(), kDefaultTimeout);
3675 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3676 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08003677
3678 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3679 "WebRTC.PeerConnection.CandidatePairType_UDP",
3680 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003681}
3682
Steve Antonede9ca52017-10-16 13:04:27 -07003683// Test that firewalling the ICE connection causes the clients to identify the
3684// disconnected state and then removing the firewall causes them to reconnect.
3685class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003686 : public PeerConnectionIntegrationBaseTest,
3687 public ::testing::WithParamInterface<
3688 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003689 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003690 PeerConnectionIntegrationIceStatesTest()
3691 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3692 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003693 }
3694
3695 void StartStunServer(const SocketAddress& server_address) {
3696 stun_server_.reset(
3697 cricket::TestStunServer::Create(network_thread(), server_address));
3698 }
3699
3700 bool TestIPv6() {
3701 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3702 }
3703
3704 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003705 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
3706 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07003707 }
3708
3709 std::vector<SocketAddress> CallerAddresses() {
3710 std::vector<SocketAddress> addresses;
3711 addresses.push_back(SocketAddress("1.1.1.1", 0));
3712 if (TestIPv6()) {
3713 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3714 }
3715 return addresses;
3716 }
3717
3718 std::vector<SocketAddress> CalleeAddresses() {
3719 std::vector<SocketAddress> addresses;
3720 addresses.push_back(SocketAddress("2.2.2.2", 0));
3721 if (TestIPv6()) {
3722 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3723 }
3724 return addresses;
3725 }
3726
3727 void SetUpNetworkInterfaces() {
3728 // Remove the default interfaces added by the test infrastructure.
3729 caller()->network()->RemoveInterface(kDefaultLocalAddress);
3730 callee()->network()->RemoveInterface(kDefaultLocalAddress);
3731
3732 // Add network addresses for test.
3733 for (const auto& caller_address : CallerAddresses()) {
3734 caller()->network()->AddInterface(caller_address);
3735 }
3736 for (const auto& callee_address : CalleeAddresses()) {
3737 callee()->network()->AddInterface(callee_address);
3738 }
3739 }
3740
3741 private:
3742 uint32_t port_allocator_flags_;
3743 std::unique_ptr<cricket::TestStunServer> stun_server_;
3744};
3745
3746// Tests that the PeerConnection goes through all the ICE gathering/connection
3747// states over the duration of the call. This includes Disconnected and Failed
3748// states, induced by putting a firewall between the peers and waiting for them
3749// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003750TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
3751 // TODO(bugs.webrtc.org/8295): When using a ScopedFakeClock, this test will
3752 // sometimes hit a DCHECK in platform_thread.cc about the PacerThread being
3753 // too busy. For now, revert to running without a fake clock.
Steve Antonede9ca52017-10-16 13:04:27 -07003754
3755 const SocketAddress kStunServerAddress =
3756 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3757 StartStunServer(kStunServerAddress);
3758
3759 PeerConnectionInterface::RTCConfiguration config;
3760 PeerConnectionInterface::IceServer ice_stun_server;
3761 ice_stun_server.urls.push_back(
3762 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
3763 kStunServerAddress.PortAsString());
3764 config.servers.push_back(ice_stun_server);
3765
3766 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3767 ConnectFakeSignaling();
3768 SetPortAllocatorFlags();
3769 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003770 caller()->AddAudioVideoTracks();
3771 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003772
3773 // Initial state before anything happens.
3774 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
3775 caller()->ice_gathering_state());
3776 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3777 caller()->ice_connection_state());
3778
3779 // Start the call by creating the offer, setting it as the local description,
3780 // then sending it to the peer who will respond with an answer. This happens
3781 // asynchronously so that we can watch the states as it runs in the
3782 // background.
3783 caller()->CreateAndSetAndSignalOffer();
3784
Steve Anton83119dd2017-11-10 16:19:52 -08003785 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3786 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003787
3788 // Verify that the observer was notified of the intermediate transitions.
3789 EXPECT_THAT(caller()->ice_connection_state_history(),
3790 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3791 PeerConnectionInterface::kIceConnectionConnected,
3792 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02003793 // After the ice transport transitions from checking to connected we revert
3794 // back to new as the standard requires, as at that point the DTLS transport
3795 // is in the "new" state while no transports are "connecting", "checking",
3796 // "failed" or disconnected. This is pretty unintuitive, and we might want to
3797 // amend the spec to handle this case more gracefully.
3798 EXPECT_THAT(
3799 caller()->peer_connection_state_history(),
3800 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02003801 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07003802 EXPECT_THAT(caller()->ice_gathering_state_history(),
3803 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
3804 PeerConnectionInterface::kIceGatheringComplete));
3805
3806 // Block connections to/from the caller and wait for ICE to become
3807 // disconnected.
3808 for (const auto& caller_address : CallerAddresses()) {
3809 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3810 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003811 RTC_LOG(LS_INFO) << "Firewall rules applied";
Steve Anton83119dd2017-11-10 16:19:52 -08003812 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
3813 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003814
3815 // Let ICE re-establish by removing the firewall rules.
3816 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01003817 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Steve Anton83119dd2017-11-10 16:19:52 -08003818 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
3819 caller()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003820
3821 // According to RFC7675, if there is no response within 30 seconds then the
3822 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08003823 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07003824 constexpr int kConsentTimeout = 30000;
3825 for (const auto& caller_address : CallerAddresses()) {
3826 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
3827 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003828 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Steve Anton83119dd2017-11-10 16:19:52 -08003829 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionFailed,
3830 caller()->ice_connection_state(), kConsentTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07003831}
3832
3833// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
3834// and that the statistics in the metric observers are updated correctly.
3835TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
3836 ASSERT_TRUE(CreatePeerConnectionWrappers());
3837 ConnectFakeSignaling();
3838 SetPortAllocatorFlags();
3839 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003840 caller()->AddAudioVideoTracks();
3841 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003842 caller()->CreateAndSetAndSignalOffer();
3843
3844 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3845
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003846 // TODO(bugs.webrtc.org/9456): Fix it.
3847 const int num_best_ipv4 = webrtc::metrics::NumEvents(
3848 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
3849 const int num_best_ipv6 = webrtc::metrics::NumEvents(
3850 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003851 if (TestIPv6()) {
3852 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
3853 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003854 EXPECT_EQ(0, num_best_ipv4);
3855 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003856 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003857 EXPECT_EQ(1, num_best_ipv4);
3858 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07003859 }
3860
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003861 EXPECT_EQ(0, webrtc::metrics::NumEvents(
3862 "WebRTC.PeerConnection.CandidatePairType_UDP",
3863 webrtc::kIceCandidatePairHostHost));
3864 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3865 "WebRTC.PeerConnection.CandidatePairType_UDP",
3866 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07003867}
3868
3869constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
3870 cricket::PORTALLOCATOR_DISABLE_STUN |
3871 cricket::PORTALLOCATOR_DISABLE_RELAY;
3872constexpr uint32_t kFlagsIPv6NoStun =
3873 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
3874 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
3875constexpr uint32_t kFlagsIPv4Stun =
3876 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
3877
Seth Hampson2f0d7022018-02-20 11:54:42 -08003878INSTANTIATE_TEST_CASE_P(
3879 PeerConnectionIntegrationTest,
3880 PeerConnectionIntegrationIceStatesTest,
3881 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
3882 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
3883 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
3884 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07003885
deadbeef1dcb1642017-03-29 21:08:16 -07003886// This test sets up a call between two parties with audio and video.
3887// During the call, the caller restarts ICE and the test verifies that
3888// new ICE candidates are generated and audio and video still can flow, and the
3889// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003890TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07003891 ASSERT_TRUE(CreatePeerConnectionWrappers());
3892 ConnectFakeSignaling();
3893 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08003894 caller()->AddAudioVideoTracks();
3895 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003896 caller()->CreateAndSetAndSignalOffer();
3897 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3898 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3899 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00003900 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3901 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07003902
3903 // To verify that the ICE restart actually occurs, get
3904 // ufrag/password/candidates before and after restart.
3905 // Create an SDP string of the first audio candidate for both clients.
3906 const webrtc::IceCandidateCollection* audio_candidates_caller =
3907 caller()->pc()->local_description()->candidates(0);
3908 const webrtc::IceCandidateCollection* audio_candidates_callee =
3909 callee()->pc()->local_description()->candidates(0);
3910 ASSERT_GT(audio_candidates_caller->count(), 0u);
3911 ASSERT_GT(audio_candidates_callee->count(), 0u);
3912 std::string caller_candidate_pre_restart;
3913 ASSERT_TRUE(
3914 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
3915 std::string callee_candidate_pre_restart;
3916 ASSERT_TRUE(
3917 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
3918 const cricket::SessionDescription* desc =
3919 caller()->pc()->local_description()->description();
3920 std::string caller_ufrag_pre_restart =
3921 desc->transport_infos()[0].description.ice_ufrag;
3922 desc = callee()->pc()->local_description()->description();
3923 std::string callee_ufrag_pre_restart =
3924 desc->transport_infos()[0].description.ice_ufrag;
3925
3926 // Have the caller initiate an ICE restart.
3927 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
3928 caller()->CreateAndSetAndSignalOffer();
3929 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3930 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3931 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00003932 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07003933 callee()->ice_connection_state(), kMaxWaitForFramesMs);
3934
3935 // Grab the ufrags/candidates again.
3936 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
3937 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
3938 ASSERT_GT(audio_candidates_caller->count(), 0u);
3939 ASSERT_GT(audio_candidates_callee->count(), 0u);
3940 std::string caller_candidate_post_restart;
3941 ASSERT_TRUE(
3942 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
3943 std::string callee_candidate_post_restart;
3944 ASSERT_TRUE(
3945 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
3946 desc = caller()->pc()->local_description()->description();
3947 std::string caller_ufrag_post_restart =
3948 desc->transport_infos()[0].description.ice_ufrag;
3949 desc = callee()->pc()->local_description()->description();
3950 std::string callee_ufrag_post_restart =
3951 desc->transport_infos()[0].description.ice_ufrag;
3952 // Sanity check that an ICE restart was actually negotiated in SDP.
3953 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
3954 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
3955 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
3956 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
3957
3958 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003959 MediaExpectations media_expectations;
3960 media_expectations.ExpectBidirectionalAudioAndVideo();
3961 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003962}
3963
3964// Verify that audio/video can be received end-to-end when ICE renomination is
3965// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003966TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07003967 PeerConnectionInterface::RTCConfiguration config;
3968 config.enable_ice_renomination = true;
3969 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3970 ConnectFakeSignaling();
3971 // Do normal offer/answer and wait for some frames to be received in each
3972 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003973 caller()->AddAudioVideoTracks();
3974 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003975 caller()->CreateAndSetAndSignalOffer();
3976 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3977 // Sanity check that ICE renomination was actually negotiated.
3978 const cricket::SessionDescription* desc =
3979 caller()->pc()->local_description()->description();
3980 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003981 ASSERT_NE(
3982 info.description.transport_options.end(),
3983 std::find(info.description.transport_options.begin(),
3984 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003985 }
3986 desc = callee()->pc()->local_description()->description();
3987 for (const cricket::TransportInfo& info : desc->transport_infos()) {
deadbeef30952b42017-04-21 02:41:29 -07003988 ASSERT_NE(
3989 info.description.transport_options.end(),
3990 std::find(info.description.transport_options.begin(),
3991 info.description.transport_options.end(), "renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07003992 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08003993 MediaExpectations media_expectations;
3994 media_expectations.ExpectBidirectionalAudioAndVideo();
3995 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003996}
3997
Steve Anton6f25b092017-10-23 09:39:20 -07003998// With a max bundle policy and RTCP muxing, adding a new media description to
3999// the connection should not affect ICE at all because the new media will use
4000// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004001TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004002 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004003 PeerConnectionInterface::RTCConfiguration config;
4004 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4005 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4006 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4007 config, PeerConnectionInterface::RTCConfiguration()));
4008 ConnectFakeSignaling();
4009
Steve Anton15324772018-01-16 10:26:49 -08004010 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004011 caller()->CreateAndSetAndSignalOffer();
4012 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004013 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4014 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004015
4016 caller()->clear_ice_connection_state_history();
4017
Steve Anton15324772018-01-16 10:26:49 -08004018 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004019 caller()->CreateAndSetAndSignalOffer();
4020 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4021
4022 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4023}
4024
deadbeef1dcb1642017-03-29 21:08:16 -07004025// This test sets up a call between two parties with audio and video. It then
4026// renegotiates setting the video m-line to "port 0", then later renegotiates
4027// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004028TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004029 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4030 ASSERT_TRUE(CreatePeerConnectionWrappers());
4031 ConnectFakeSignaling();
4032
4033 // Do initial negotiation, only sending media from the caller. Will result in
4034 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004035 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004036 caller()->CreateAndSetAndSignalOffer();
4037 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4038
4039 // Negotiate again, disabling the video "m=" section (the callee will set the
4040 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004041 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4042 PeerConnectionInterface::RTCOfferAnswerOptions options;
4043 options.offer_to_receive_video = 0;
4044 callee()->SetOfferAnswerOptions(options);
4045 } else {
4046 callee()->SetRemoteOfferHandler([this] {
4047 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4048 });
4049 }
deadbeef1dcb1642017-03-29 21:08:16 -07004050 caller()->CreateAndSetAndSignalOffer();
4051 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4052 // Sanity check that video "m=" section was actually rejected.
4053 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4054 callee()->pc()->local_description()->description());
4055 ASSERT_NE(nullptr, answer_video_content);
4056 ASSERT_TRUE(answer_video_content->rejected);
4057
4058 // Enable video and do negotiation again, making sure video is received
4059 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004060 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4061 PeerConnectionInterface::RTCOfferAnswerOptions options;
4062 options.offer_to_receive_video = 1;
4063 callee()->SetOfferAnswerOptions(options);
4064 } else {
4065 // The caller's transceiver is stopped, so we need to add another track.
4066 auto caller_transceiver =
4067 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4068 EXPECT_TRUE(caller_transceiver->stopped());
4069 caller()->AddVideoTrack();
4070 }
4071 callee()->AddVideoTrack();
4072 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004073 caller()->CreateAndSetAndSignalOffer();
4074 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004075
deadbeef1dcb1642017-03-29 21:08:16 -07004076 // Verify the caller receives frames from the newly added stream, and the
4077 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004078 MediaExpectations media_expectations;
4079 media_expectations.CalleeExpectsSomeAudio();
4080 media_expectations.ExpectBidirectionalVideo();
4081 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004082}
4083
deadbeef1dcb1642017-03-29 21:08:16 -07004084// This tests that if we negotiate after calling CreateSender but before we
4085// have a track, then set a track later, frames from the newly-set track are
4086// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004087TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004088 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4089 ASSERT_TRUE(CreatePeerConnectionWrappers());
4090 ConnectFakeSignaling();
4091 auto caller_audio_sender =
4092 caller()->pc()->CreateSender("audio", "caller_stream");
4093 auto caller_video_sender =
4094 caller()->pc()->CreateSender("video", "caller_stream");
4095 auto callee_audio_sender =
4096 callee()->pc()->CreateSender("audio", "callee_stream");
4097 auto callee_video_sender =
4098 callee()->pc()->CreateSender("video", "callee_stream");
4099 caller()->CreateAndSetAndSignalOffer();
4100 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4101 // Wait for ICE to complete, without any tracks being set.
4102 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4103 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4104 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4105 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4106 // Now set the tracks, and expect frames to immediately start flowing.
4107 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4108 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4109 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4110 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004111 MediaExpectations media_expectations;
4112 media_expectations.ExpectBidirectionalAudioAndVideo();
4113 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4114}
4115
4116// This tests that if we negotiate after calling AddTransceiver but before we
4117// have a track, then set a track later, frames from the newly-set tracks are
4118// received end-to-end.
4119TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4120 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4121 ASSERT_TRUE(CreatePeerConnectionWrappers());
4122 ConnectFakeSignaling();
4123 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4124 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4125 auto caller_audio_sender = audio_result.MoveValue()->sender();
4126 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4127 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4128 auto caller_video_sender = video_result.MoveValue()->sender();
4129 callee()->SetRemoteOfferHandler([this] {
4130 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4131 callee()->pc()->GetTransceivers()[0]->SetDirection(
4132 RtpTransceiverDirection::kSendRecv);
4133 callee()->pc()->GetTransceivers()[1]->SetDirection(
4134 RtpTransceiverDirection::kSendRecv);
4135 });
4136 caller()->CreateAndSetAndSignalOffer();
4137 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4138 // Wait for ICE to complete, without any tracks being set.
4139 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4140 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4141 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4142 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4143 // Now set the tracks, and expect frames to immediately start flowing.
4144 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4145 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4146 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4147 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4148 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4149 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4150 MediaExpectations media_expectations;
4151 media_expectations.ExpectBidirectionalAudioAndVideo();
4152 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004153}
4154
4155// This test verifies that a remote video track can be added via AddStream,
4156// and sent end-to-end. For this particular test, it's simply echoed back
4157// from the caller to the callee, rather than being forwarded to a third
4158// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004159TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004160 ASSERT_TRUE(CreatePeerConnectionWrappers());
4161 ConnectFakeSignaling();
4162 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004163 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004164 caller()->CreateAndSetAndSignalOffer();
4165 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004166 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004167
4168 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4169 // time).
4170 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4171 callee()->CreateAndSetAndSignalOffer();
4172 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4173
Seth Hampson2f0d7022018-02-20 11:54:42 -08004174 MediaExpectations media_expectations;
4175 media_expectations.ExpectBidirectionalVideo();
4176 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004177}
4178
4179// Test that we achieve the expected end-to-end connection time, using a
4180// fake clock and simulated latency on the media and signaling paths.
4181// We use a TURN<->TURN connection because this is usually the quickest to
4182// set up initially, especially when we're confident the connection will work
4183// and can start sending media before we get a STUN response.
4184//
4185// With various optimizations enabled, here are the network delays we expect to
4186// be on the critical path:
4187// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4188// signaling answer (with DTLS fingerprint).
4189// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4190// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4191// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004192TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004193 rtc::ScopedFakeClock fake_clock;
4194 // Some things use a time of "0" as a special value, so we need to start out
4195 // the fake clock at a nonzero time.
4196 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02004197 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07004198
4199 static constexpr int media_hop_delay_ms = 50;
4200 static constexpr int signaling_trip_delay_ms = 500;
4201 // For explanation of these values, see comment above.
4202 static constexpr int required_media_hops = 9;
4203 static constexpr int required_signaling_trips = 2;
4204 // For internal delays (such as posting an event asychronously).
4205 static constexpr int allowed_internal_delay_ms = 20;
4206 static constexpr int total_connection_time_ms =
4207 media_hop_delay_ms * required_media_hops +
4208 signaling_trip_delay_ms * required_signaling_trips +
4209 allowed_internal_delay_ms;
4210
4211 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4212 3478};
4213 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4214 0};
4215 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4216 3478};
4217 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4218 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004219 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4220 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004221
Seth Hampsonaed71642018-06-11 07:41:32 -07004222 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4223 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004224 // Bypass permission check on received packets so media can be sent before
4225 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004226 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4227 turn_server_1->set_enable_permission_checks(false);
4228 });
4229 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4230 turn_server_2->set_enable_permission_checks(false);
4231 });
deadbeef1dcb1642017-03-29 21:08:16 -07004232
4233 PeerConnectionInterface::RTCConfiguration client_1_config;
4234 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4235 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4236 ice_server_1.username = "test";
4237 ice_server_1.password = "test";
4238 client_1_config.servers.push_back(ice_server_1);
4239 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4240 client_1_config.presume_writable_when_fully_relayed = true;
4241
4242 PeerConnectionInterface::RTCConfiguration client_2_config;
4243 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4244 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4245 ice_server_2.username = "test";
4246 ice_server_2.password = "test";
4247 client_2_config.servers.push_back(ice_server_2);
4248 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4249 client_2_config.presume_writable_when_fully_relayed = true;
4250
4251 ASSERT_TRUE(
4252 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4253 // Set up the simulated delays.
4254 SetSignalingDelayMs(signaling_trip_delay_ms);
4255 ConnectFakeSignaling();
4256 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4257 virtual_socket_server()->UpdateDelayDistribution();
4258
4259 // Set "offer to receive audio/video" without adding any tracks, so we just
4260 // set up ICE/DTLS with no media.
4261 PeerConnectionInterface::RTCOfferAnswerOptions options;
4262 options.offer_to_receive_audio = 1;
4263 options.offer_to_receive_video = 1;
4264 caller()->SetOfferAnswerOptions(options);
4265 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004266 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4267 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004268 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4269 // If this is not done a DCHECK can be hit in ports.cc, because a large
4270 // negative number is calculated for the rtt due to the global clock changing.
4271 caller()->pc()->Close();
4272 callee()->pc()->Close();
deadbeef1dcb1642017-03-29 21:08:16 -07004273}
4274
Jonas Orelandbdcee282017-10-10 14:01:40 +02004275// Verify that a TurnCustomizer passed in through RTCConfiguration
4276// is actually used by the underlying TURN candidate pair.
4277// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004278TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004279 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4280 3478};
4281 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4282 0};
4283 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4284 3478};
4285 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4286 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004287 CreateTurnServer(turn_server_1_internal_address,
4288 turn_server_1_external_address);
4289 CreateTurnServer(turn_server_2_internal_address,
4290 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004291
4292 PeerConnectionInterface::RTCConfiguration client_1_config;
4293 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4294 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4295 ice_server_1.username = "test";
4296 ice_server_1.password = "test";
4297 client_1_config.servers.push_back(ice_server_1);
4298 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004299 auto* customizer1 = CreateTurnCustomizer();
4300 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004301
4302 PeerConnectionInterface::RTCConfiguration client_2_config;
4303 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4304 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4305 ice_server_2.username = "test";
4306 ice_server_2.password = "test";
4307 client_2_config.servers.push_back(ice_server_2);
4308 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004309 auto* customizer2 = CreateTurnCustomizer();
4310 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004311
4312 ASSERT_TRUE(
4313 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4314 ConnectFakeSignaling();
4315
4316 // Set "offer to receive audio/video" without adding any tracks, so we just
4317 // set up ICE/DTLS with no media.
4318 PeerConnectionInterface::RTCOfferAnswerOptions options;
4319 options.offer_to_receive_audio = 1;
4320 options.offer_to_receive_video = 1;
4321 caller()->SetOfferAnswerOptions(options);
4322 caller()->CreateAndSetAndSignalOffer();
4323 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4324
Seth Hampsonaed71642018-06-11 07:41:32 -07004325 ExpectTurnCustomizerCountersIncremented(customizer1);
4326 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004327}
4328
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004329// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4330// send media between the caller and the callee.
4331TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4332 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4333 3478};
4334 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4335
4336 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004337 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4338 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004339
4340 webrtc::PeerConnectionInterface::IceServer ice_server;
4341 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4342 ice_server.username = "test";
4343 ice_server.password = "test";
4344
4345 PeerConnectionInterface::RTCConfiguration client_1_config;
4346 client_1_config.servers.push_back(ice_server);
4347 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4348
4349 PeerConnectionInterface::RTCConfiguration client_2_config;
4350 client_2_config.servers.push_back(ice_server);
4351 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4352
4353 ASSERT_TRUE(
4354 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4355
4356 // Do normal offer/answer and wait for ICE to complete.
4357 ConnectFakeSignaling();
4358 caller()->AddAudioVideoTracks();
4359 callee()->AddAudioVideoTracks();
4360 caller()->CreateAndSetAndSignalOffer();
4361 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4362 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4363 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4364
4365 MediaExpectations media_expectations;
4366 media_expectations.ExpectBidirectionalAudioAndVideo();
4367 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4368}
4369
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004370// Verify that a SSLCertificateVerifier passed in through
4371// PeerConnectionDependencies is actually used by the underlying SSL
4372// implementation to determine whether a certificate presented by the TURN
4373// server is accepted by the client. Note that openssladapter_unittest.cc
4374// contains more detailed, lower-level tests.
4375TEST_P(PeerConnectionIntegrationTest,
4376 SSLCertificateVerifierUsedForTurnConnections) {
4377 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4378 3478};
4379 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4380
4381 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4382 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004383 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4384 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004385
4386 webrtc::PeerConnectionInterface::IceServer ice_server;
4387 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4388 ice_server.username = "test";
4389 ice_server.password = "test";
4390
4391 PeerConnectionInterface::RTCConfiguration client_1_config;
4392 client_1_config.servers.push_back(ice_server);
4393 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4394
4395 PeerConnectionInterface::RTCConfiguration client_2_config;
4396 client_2_config.servers.push_back(ice_server);
4397 // Setting the type to kRelay forces the connection to go through a TURN
4398 // server.
4399 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4400
4401 // Get a copy to the pointer so we can verify calls later.
4402 rtc::TestCertificateVerifier* client_1_cert_verifier =
4403 new rtc::TestCertificateVerifier();
4404 client_1_cert_verifier->verify_certificate_ = true;
4405 rtc::TestCertificateVerifier* client_2_cert_verifier =
4406 new rtc::TestCertificateVerifier();
4407 client_2_cert_verifier->verify_certificate_ = true;
4408
4409 // Create the dependencies with the test certificate verifier.
4410 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4411 client_1_deps.tls_cert_verifier =
4412 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4413 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4414 client_2_deps.tls_cert_verifier =
4415 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4416
4417 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4418 client_1_config, std::move(client_1_deps), client_2_config,
4419 std::move(client_2_deps)));
4420 ConnectFakeSignaling();
4421
4422 // Set "offer to receive audio/video" without adding any tracks, so we just
4423 // set up ICE/DTLS with no media.
4424 PeerConnectionInterface::RTCOfferAnswerOptions options;
4425 options.offer_to_receive_audio = 1;
4426 options.offer_to_receive_video = 1;
4427 caller()->SetOfferAnswerOptions(options);
4428 caller()->CreateAndSetAndSignalOffer();
4429 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4430
4431 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4432 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004433}
4434
4435TEST_P(PeerConnectionIntegrationTest,
4436 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4437 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4438 3478};
4439 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4440
4441 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4442 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004443 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4444 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004445
4446 webrtc::PeerConnectionInterface::IceServer ice_server;
4447 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4448 ice_server.username = "test";
4449 ice_server.password = "test";
4450
4451 PeerConnectionInterface::RTCConfiguration client_1_config;
4452 client_1_config.servers.push_back(ice_server);
4453 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4454
4455 PeerConnectionInterface::RTCConfiguration client_2_config;
4456 client_2_config.servers.push_back(ice_server);
4457 // Setting the type to kRelay forces the connection to go through a TURN
4458 // server.
4459 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4460
4461 // Get a copy to the pointer so we can verify calls later.
4462 rtc::TestCertificateVerifier* client_1_cert_verifier =
4463 new rtc::TestCertificateVerifier();
4464 client_1_cert_verifier->verify_certificate_ = false;
4465 rtc::TestCertificateVerifier* client_2_cert_verifier =
4466 new rtc::TestCertificateVerifier();
4467 client_2_cert_verifier->verify_certificate_ = false;
4468
4469 // Create the dependencies with the test certificate verifier.
4470 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4471 client_1_deps.tls_cert_verifier =
4472 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4473 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4474 client_2_deps.tls_cert_verifier =
4475 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4476
4477 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4478 client_1_config, std::move(client_1_deps), client_2_config,
4479 std::move(client_2_deps)));
4480 ConnectFakeSignaling();
4481
4482 // Set "offer to receive audio/video" without adding any tracks, so we just
4483 // set up ICE/DTLS with no media.
4484 PeerConnectionInterface::RTCOfferAnswerOptions options;
4485 options.offer_to_receive_audio = 1;
4486 options.offer_to_receive_video = 1;
4487 caller()->SetOfferAnswerOptions(options);
4488 caller()->CreateAndSetAndSignalOffer();
4489 bool wait_res = true;
4490 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4491 // properly, should be able to just wait for a state of "failed" instead of
4492 // waiting a fixed 10 seconds.
4493 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4494 ASSERT_FALSE(wait_res);
4495
4496 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4497 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004498}
4499
deadbeefc964d0b2017-04-03 10:03:35 -07004500// Test that audio and video flow end-to-end when codec names don't use the
4501// expected casing, given that they're supposed to be case insensitive. To test
4502// this, all but one codec is removed from each media description, and its
4503// casing is changed.
4504//
4505// In the past, this has regressed and caused crashes/black video, due to the
4506// fact that code at some layers was doing case-insensitive comparisons and
4507// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004508TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004509 ASSERT_TRUE(CreatePeerConnectionWrappers());
4510 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004511 caller()->AddAudioVideoTracks();
4512 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004513
4514 // Remove all but one audio/video codec (opus and VP8), and change the
4515 // casing of the caller's generated offer.
4516 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4517 cricket::AudioContentDescription* audio =
4518 GetFirstAudioContentDescription(description);
4519 ASSERT_NE(nullptr, audio);
4520 auto audio_codecs = audio->codecs();
4521 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4522 [](const cricket::AudioCodec& codec) {
4523 return codec.name != "opus";
4524 }),
4525 audio_codecs.end());
4526 ASSERT_EQ(1u, audio_codecs.size());
4527 audio_codecs[0].name = "OpUs";
4528 audio->set_codecs(audio_codecs);
4529
4530 cricket::VideoContentDescription* video =
4531 GetFirstVideoContentDescription(description);
4532 ASSERT_NE(nullptr, video);
4533 auto video_codecs = video->codecs();
4534 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4535 [](const cricket::VideoCodec& codec) {
4536 return codec.name != "VP8";
4537 }),
4538 video_codecs.end());
4539 ASSERT_EQ(1u, video_codecs.size());
4540 video_codecs[0].name = "vP8";
4541 video->set_codecs(video_codecs);
4542 });
4543
4544 caller()->CreateAndSetAndSignalOffer();
4545 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4546
4547 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004548 MediaExpectations media_expectations;
4549 media_expectations.ExpectBidirectionalAudioAndVideo();
4550 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004551}
4552
Jonas Oreland49ac5952018-09-26 16:04:32 +02004553TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004554 ASSERT_TRUE(CreatePeerConnectionWrappers());
4555 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004556 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004557 caller()->CreateAndSetAndSignalOffer();
4558 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004559 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004560 MediaExpectations media_expectations;
4561 media_expectations.CalleeExpectsSomeAudio(1);
4562 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004563 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004564 auto receiver = callee()->pc()->GetReceivers()[0];
4565 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004566 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004567 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4568 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004569 sources[0].source_id());
4570 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4571}
4572
4573TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4574 ASSERT_TRUE(CreatePeerConnectionWrappers());
4575 ConnectFakeSignaling();
4576 caller()->AddVideoTrack();
4577 caller()->CreateAndSetAndSignalOffer();
4578 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4579 // Wait for one video frame to be received by the callee.
4580 MediaExpectations media_expectations;
4581 media_expectations.CalleeExpectsSomeVideo(1);
4582 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4583 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4584 auto receiver = callee()->pc()->GetReceivers()[0];
4585 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4586 auto sources = receiver->GetSources();
4587 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4588 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4589 sources[0].source_id());
4590 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004591}
4592
deadbeef2f425aa2017-04-14 10:41:32 -07004593// Test that if a track is removed and added again with a different stream ID,
4594// the new stream ID is successfully communicated in SDP and media continues to
4595// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004596// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4597// it will not reuse a transceiver that has already been sending. After creating
4598// a new transceiver it tries to create an offer with two senders of the same
4599// track ids and it fails.
4600TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004601 ASSERT_TRUE(CreatePeerConnectionWrappers());
4602 ConnectFakeSignaling();
4603
deadbeef2f425aa2017-04-14 10:41:32 -07004604 // Add track using stream 1, do offer/answer.
4605 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4606 caller()->CreateLocalAudioTrack();
4607 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004608 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004609 caller()->CreateAndSetAndSignalOffer();
4610 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004611 {
4612 MediaExpectations media_expectations;
4613 media_expectations.CalleeExpectsSomeAudio(1);
4614 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4615 }
deadbeef2f425aa2017-04-14 10:41:32 -07004616 // Remove the sender, and create a new one with the new stream.
4617 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004618 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004619 caller()->CreateAndSetAndSignalOffer();
4620 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4621 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004622 {
4623 MediaExpectations media_expectations;
4624 media_expectations.CalleeExpectsSomeAudio();
4625 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4626 }
deadbeef2f425aa2017-04-14 10:41:32 -07004627}
4628
Seth Hampson2f0d7022018-02-20 11:54:42 -08004629TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004630 ASSERT_TRUE(CreatePeerConnectionWrappers());
4631 ConnectFakeSignaling();
4632
Karl Wiberg918f50c2018-07-05 11:40:33 +02004633 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Elad Alon99c3fe52017-10-13 16:29:40 +02004634 ON_CALL(*output, IsActive()).WillByDefault(testing::Return(true));
4635 ON_CALL(*output, Write(::testing::_)).WillByDefault(testing::Return(true));
4636 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004637 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4638 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004639
Steve Anton15324772018-01-16 10:26:49 -08004640 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004641 caller()->CreateAndSetAndSignalOffer();
4642 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4643}
4644
Steve Antonede9ca52017-10-16 13:04:27 -07004645// Test that if candidates are only signaled by applying full session
4646// descriptions (instead of using AddIceCandidate), the peers can connect to
4647// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004648TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004649 ASSERT_TRUE(CreatePeerConnectionWrappers());
4650 // Each side will signal the session descriptions but not candidates.
4651 ConnectFakeSignalingForSdpOnly();
4652
4653 // Add audio video track and exchange the initial offer/answer with media
4654 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004655 caller()->AddAudioVideoTracks();
4656 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004657 caller()->CreateAndSetAndSignalOffer();
4658
4659 // Wait for all candidates to be gathered on both the caller and callee.
4660 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4661 caller()->ice_gathering_state(), kDefaultTimeout);
4662 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4663 callee()->ice_gathering_state(), kDefaultTimeout);
4664
4665 // The candidates will now be included in the session description, so
4666 // signaling them will start the ICE connection.
4667 caller()->CreateAndSetAndSignalOffer();
4668 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4669
4670 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004671 MediaExpectations media_expectations;
4672 media_expectations.ExpectBidirectionalAudioAndVideo();
4673 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004674}
4675
henrika5f6bf242017-11-01 11:06:56 +01004676// Test that SetAudioPlayout can be used to disable audio playout from the
4677// start, then later enable it. This may be useful, for example, if the caller
4678// needs to play a local ringtone until some event occurs, after which it
4679// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004680TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004681 ASSERT_TRUE(CreatePeerConnectionWrappers());
4682 ConnectFakeSignaling();
4683
4684 // Set up audio-only call where audio playout is disabled on caller's side.
4685 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004686 caller()->AddAudioTrack();
4687 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004688 caller()->CreateAndSetAndSignalOffer();
4689 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4690
4691 // Pump messages for a second.
4692 WAIT(false, 1000);
4693 // Since audio playout is disabled, the caller shouldn't have received
4694 // anything (at the playout level, at least).
4695 EXPECT_EQ(0, caller()->audio_frames_received());
4696 // As a sanity check, make sure the callee (for which playout isn't disabled)
4697 // did still see frames on its audio level.
4698 ASSERT_GT(callee()->audio_frames_received(), 0);
4699
4700 // Enable playout again, and ensure audio starts flowing.
4701 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004702 MediaExpectations media_expectations;
4703 media_expectations.ExpectBidirectionalAudio();
4704 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004705}
4706
4707double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
4708 auto report = pc->NewGetStats();
4709 auto track_stats_list =
4710 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
4711 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
4712 for (const auto* track_stats : track_stats_list) {
4713 if (track_stats->remote_source.is_defined() &&
4714 *track_stats->remote_source) {
4715 remote_track_stats = track_stats;
4716 break;
4717 }
4718 }
4719
4720 if (!remote_track_stats->total_audio_energy.is_defined()) {
4721 return 0.0;
4722 }
4723 return *remote_track_stats->total_audio_energy;
4724}
4725
4726// Test that if audio playout is disabled via the SetAudioPlayout() method, then
4727// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004728TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01004729 DisableAudioPlayoutStillGeneratesAudioStats) {
4730 ASSERT_TRUE(CreatePeerConnectionWrappers());
4731 ConnectFakeSignaling();
4732
4733 // Set up audio-only call where playout is disabled but audio-processing is
4734 // still active.
Steve Anton15324772018-01-16 10:26:49 -08004735 caller()->AddAudioTrack();
4736 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004737 caller()->pc()->SetAudioPlayout(false);
4738
4739 caller()->CreateAndSetAndSignalOffer();
4740 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4741
4742 // Wait for the callee to receive audio stats.
4743 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
4744}
4745
henrika4f167df2017-11-01 14:45:55 +01004746// Test that SetAudioRecording can be used to disable audio recording from the
4747// start, then later enable it. This may be useful, for example, if the caller
4748// wants to ensure that no audio resources are active before a certain state
4749// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004750TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01004751 ASSERT_TRUE(CreatePeerConnectionWrappers());
4752 ConnectFakeSignaling();
4753
4754 // Set up audio-only call where audio recording is disabled on caller's side.
4755 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08004756 caller()->AddAudioTrack();
4757 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01004758 caller()->CreateAndSetAndSignalOffer();
4759 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4760
4761 // Pump messages for a second.
4762 WAIT(false, 1000);
4763 // Since caller has disabled audio recording, the callee shouldn't have
4764 // received anything.
4765 EXPECT_EQ(0, callee()->audio_frames_received());
4766 // As a sanity check, make sure the caller did still see frames on its
4767 // audio level since audio recording is enabled on the calle side.
4768 ASSERT_GT(caller()->audio_frames_received(), 0);
4769
4770 // Enable audio recording again, and ensure audio starts flowing.
4771 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004772 MediaExpectations media_expectations;
4773 media_expectations.ExpectBidirectionalAudio();
4774 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01004775}
4776
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004777// Test that after closing PeerConnections, they stop sending any packets (ICE,
4778// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004779TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004780 // Set up audio/video/data, wait for some frames to be received.
4781 ASSERT_TRUE(CreatePeerConnectionWrappers());
4782 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004783 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004784#ifdef HAVE_SCTP
4785 caller()->CreateDataChannel();
4786#endif
4787 caller()->CreateAndSetAndSignalOffer();
4788 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004789 MediaExpectations media_expectations;
4790 media_expectations.CalleeExpectsSomeAudioAndVideo();
4791 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08004792 // Close PeerConnections.
4793 caller()->pc()->Close();
4794 callee()->pc()->Close();
4795 // Pump messages for a second, and ensure no new packets end up sent.
4796 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
4797 WAIT(false, 1000);
4798 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
4799 EXPECT_EQ(sent_packets_a, sent_packets_b);
4800}
4801
Steve Anton7eca0932018-03-30 15:18:41 -07004802// Test that transport stats are generated by the RTCStatsCollector for a
4803// connection that only involves data channels. This is a regression test for
4804// crbug.com/826972.
4805#ifdef HAVE_SCTP
4806TEST_P(PeerConnectionIntegrationTest,
4807 TransportStatsReportedForDataChannelOnlyConnection) {
4808 ASSERT_TRUE(CreatePeerConnectionWrappers());
4809 ConnectFakeSignaling();
4810 caller()->CreateDataChannel();
4811
4812 caller()->CreateAndSetAndSignalOffer();
4813 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4814 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
4815
4816 auto caller_report = caller()->NewGetStats();
4817 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
4818 auto callee_report = callee()->NewGetStats();
4819 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
4820}
4821#endif // HAVE_SCTP
4822
Qingsi Wang7685e862018-06-11 20:15:46 -07004823TEST_P(PeerConnectionIntegrationTest,
4824 IceEventsGeneratedAndLoggedInRtcEventLog) {
4825 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
4826 ConnectFakeSignaling();
4827 PeerConnectionInterface::RTCOfferAnswerOptions options;
4828 options.offer_to_receive_audio = 1;
4829 caller()->SetOfferAnswerOptions(options);
4830 caller()->CreateAndSetAndSignalOffer();
4831 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4832 ASSERT_NE(nullptr, caller()->event_log_factory());
4833 ASSERT_NE(nullptr, callee()->event_log_factory());
4834 webrtc::FakeRtcEventLog* caller_event_log =
4835 static_cast<webrtc::FakeRtcEventLog*>(
4836 caller()->event_log_factory()->last_log_created());
4837 webrtc::FakeRtcEventLog* callee_event_log =
4838 static_cast<webrtc::FakeRtcEventLog*>(
4839 callee()->event_log_factory()->last_log_created());
4840 ASSERT_NE(nullptr, caller_event_log);
4841 ASSERT_NE(nullptr, callee_event_log);
4842 int caller_ice_config_count = caller_event_log->GetEventCount(
4843 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4844 int caller_ice_event_count = caller_event_log->GetEventCount(
4845 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4846 int callee_ice_config_count = callee_event_log->GetEventCount(
4847 webrtc::RtcEvent::Type::IceCandidatePairConfig);
4848 int callee_ice_event_count = callee_event_log->GetEventCount(
4849 webrtc::RtcEvent::Type::IceCandidatePairEvent);
4850 EXPECT_LT(0, caller_ice_config_count);
4851 EXPECT_LT(0, caller_ice_event_count);
4852 EXPECT_LT(0, callee_ice_config_count);
4853 EXPECT_LT(0, callee_ice_event_count);
4854}
4855
Seth Hampson2f0d7022018-02-20 11:54:42 -08004856INSTANTIATE_TEST_CASE_P(PeerConnectionIntegrationTest,
4857 PeerConnectionIntegrationTest,
4858 Values(SdpSemantics::kPlanB,
4859 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08004860
Steve Anton74255ff2018-01-24 18:32:57 -08004861// Tests that verify interoperability between Plan B and Unified Plan
4862// PeerConnections.
4863class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004864 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08004865 public ::testing::WithParamInterface<
4866 std::tuple<SdpSemantics, SdpSemantics>> {
4867 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004868 // Setting the SdpSemantics for the base test to kDefault does not matter
4869 // because we specify not to use the test semantics when creating
4870 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08004871 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07004872 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08004873 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08004874 callee_semantics_(std::get<1>(GetParam())) {}
4875
4876 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07004877 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
4878 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08004879 }
4880
4881 const SdpSemantics caller_semantics_;
4882 const SdpSemantics callee_semantics_;
4883};
4884
4885TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
4886 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4887 ConnectFakeSignaling();
4888
4889 caller()->CreateAndSetAndSignalOffer();
4890 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4891}
4892
4893TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
4894 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4895 ConnectFakeSignaling();
4896 auto audio_sender = caller()->AddAudioTrack();
4897
4898 caller()->CreateAndSetAndSignalOffer();
4899 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4900
4901 // Verify that one audio receiver has been created on the remote and that it
4902 // has the same track ID as the sending track.
4903 auto receivers = callee()->pc()->GetReceivers();
4904 ASSERT_EQ(1u, receivers.size());
4905 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
4906 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
4907
Seth Hampson2f0d7022018-02-20 11:54:42 -08004908 MediaExpectations media_expectations;
4909 media_expectations.CalleeExpectsSomeAudio();
4910 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004911}
4912
4913TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
4914 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4915 ConnectFakeSignaling();
4916 auto video_sender = caller()->AddVideoTrack();
4917 auto audio_sender = caller()->AddAudioTrack();
4918
4919 caller()->CreateAndSetAndSignalOffer();
4920 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4921
4922 // Verify that one audio and one video receiver have been created on the
4923 // remote and that they have the same track IDs as the sending tracks.
4924 auto audio_receivers =
4925 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
4926 ASSERT_EQ(1u, audio_receivers.size());
4927 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
4928 auto video_receivers =
4929 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
4930 ASSERT_EQ(1u, video_receivers.size());
4931 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
4932
Seth Hampson2f0d7022018-02-20 11:54:42 -08004933 MediaExpectations media_expectations;
4934 media_expectations.CalleeExpectsSomeAudioAndVideo();
4935 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004936}
4937
4938TEST_P(PeerConnectionIntegrationInteropTest,
4939 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
4940 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4941 ConnectFakeSignaling();
4942 caller()->AddAudioVideoTracks();
4943 callee()->AddAudioVideoTracks();
4944
4945 caller()->CreateAndSetAndSignalOffer();
4946 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4947
Seth Hampson2f0d7022018-02-20 11:54:42 -08004948 MediaExpectations media_expectations;
4949 media_expectations.ExpectBidirectionalAudioAndVideo();
4950 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004951}
4952
4953TEST_P(PeerConnectionIntegrationInteropTest,
4954 ReverseRolesOneAudioLocalToOneVideoRemote) {
4955 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
4956 ConnectFakeSignaling();
4957 caller()->AddAudioTrack();
4958 callee()->AddVideoTrack();
4959
4960 caller()->CreateAndSetAndSignalOffer();
4961 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4962
4963 // Verify that only the audio track has been negotiated.
4964 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
4965 // Might also check that the callee's NegotiationNeeded flag is set.
4966
4967 // Reverse roles.
4968 callee()->CreateAndSetAndSignalOffer();
4969 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4970
Seth Hampson2f0d7022018-02-20 11:54:42 -08004971 MediaExpectations media_expectations;
4972 media_expectations.CallerExpectsSomeVideo();
4973 media_expectations.CalleeExpectsSomeAudio();
4974 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08004975}
4976
Steve Antonba42e992018-04-09 14:10:01 -07004977INSTANTIATE_TEST_CASE_P(
4978 PeerConnectionIntegrationTest,
4979 PeerConnectionIntegrationInteropTest,
4980 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4981 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
4982
4983// Test that if the Unified Plan side offers two video tracks then the Plan B
4984// side will only see the first one and ignore the second.
4985TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07004986 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
4987 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08004988 ConnectFakeSignaling();
4989 auto first_sender = caller()->AddVideoTrack();
4990 caller()->AddVideoTrack();
4991
4992 caller()->CreateAndSetAndSignalOffer();
4993 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4994
4995 // Verify that there is only one receiver and it corresponds to the first
4996 // added track.
4997 auto receivers = callee()->pc()->GetReceivers();
4998 ASSERT_EQ(1u, receivers.size());
4999 EXPECT_TRUE(receivers[0]->track()->enabled());
5000 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5001
Seth Hampson2f0d7022018-02-20 11:54:42 -08005002 MediaExpectations media_expectations;
5003 media_expectations.CalleeExpectsSomeVideo();
5004 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005005}
5006
deadbeef1dcb1642017-03-29 21:08:16 -07005007} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01005008} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07005009
5010#endif // if !defined(THREAD_SANITIZER)