blob: d184a92eaea206894ae4f0ba4f9070b29a944e6d [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
deadbeef1dcb1642017-03-29 21:08:16 -070017#include <functional>
18#include <list>
19#include <map>
20#include <memory>
21#include <utility>
22#include <vector>
23
Steve Anton64b626b2019-01-28 17:25:26 -080024#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080025#include "api/media_stream_interface.h"
26#include "api/peer_connection_interface.h"
27#include "api/peer_connection_proxy.h"
Danil Chapovalov9da25bd2019-06-20 10:19:42 +020028#include "api/rtc_event_log/rtc_event_log_factory.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "api/rtp_receiver_interface.h"
Danil Chapovalov9da25bd2019-06-20 10:19:42 +020030#include "api/task_queue/default_task_queue_factory.h"
Bjorn Mellem175aa2e2018-11-08 11:23:22 -080031#include "api/test/loopback_media_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "api/uma_metrics.h"
Anders Carlsson67537952018-05-03 11:28:29 +020033#include "api/video_codecs/sdp_video_format.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070034#include "call/call.h"
35#include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/engine/fake_webrtc_video_engine.h"
37#include "media/engine/webrtc_media_engine.h"
Danil Chapovalov9da25bd2019-06-20 10:19:42 +020038#include "media/engine/webrtc_media_engine_defaults.h"
Qingsi Wang25ec8882019-11-15 12:33:05 -080039#include "p2p/base/fake_ice_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "p2p/base/mock_async_resolver.h"
41#include "p2p/base/p2p_constants.h"
42#include "p2p/base/port_interface.h"
43#include "p2p/base/test_stun_server.h"
44#include "p2p/base/test_turn_customizer.h"
45#include "p2p/base/test_turn_server.h"
46#include "p2p/client/basic_port_allocator.h"
47#include "pc/dtmf_sender.h"
48#include "pc/local_audio_source.h"
49#include "pc/media_session.h"
50#include "pc/peer_connection.h"
51#include "pc/peer_connection_factory.h"
52#include "pc/rtp_media_utils.h"
53#include "pc/session_description.h"
54#include "pc/test/fake_audio_capture_module.h"
55#include "pc/test/fake_periodic_video_track_source.h"
56#include "pc/test/fake_rtc_certificate_generator.h"
57#include "pc/test/fake_video_track_renderer.h"
58#include "pc/test/mock_peer_connection_observers.h"
Jonas Olssonb75d9e92019-02-22 10:33:29 +010059#include "rtc_base/fake_clock.h"
Qingsi Wangecd30542019-05-22 14:34:56 -070060#include "rtc_base/fake_mdns_responder.h"
Steve Anton10542f22019-01-11 09:11:00 -080061#include "rtc_base/fake_network.h"
62#include "rtc_base/firewall_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020063#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020064#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080065#include "rtc_base/test_certificate_verifier.h"
66#include "rtc_base/time_utils.h"
67#include "rtc_base/virtual_socket_server.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020068#include "system_wrappers/include/metrics.h"
Qingsi Wangc129c352019-04-18 10:41:58 -070069#include "test/field_trial.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 Anton64b626b2019-01-28 17:25:26 -080080using ::testing::Contains;
Mirko Bonadeie46f5db2019-03-26 20:14:46 +010081using ::testing::DoAll;
Steve Antonede9ca52017-10-16 13:04:27 -070082using ::testing::ElementsAre;
Qingsi Wang1dac6d82018-12-12 15:28:47 -080083using ::testing::NiceMock;
Steve Anton64b626b2019-01-28 17:25:26 -080084using ::testing::Return;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070085using ::testing::SetArgPointee;
Steve Antonffa6ce42018-11-30 09:26:08 -080086using ::testing::UnorderedElementsAreArray;
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010087using ::testing::Values;
Steve Anton74255ff2018-01-24 18:32:57 -080088using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -070089
90static const int kDefaultTimeout = 10000;
91static const int kMaxWaitForStatsMs = 3000;
92static const int kMaxWaitForActivationMs = 5000;
93static const int kMaxWaitForFramesMs = 10000;
94// Default number of audio/video frames to wait for before considering a test
95// successful.
96static const int kDefaultExpectedAudioFrameCount = 3;
97static const int kDefaultExpectedVideoFrameCount = 3;
98
deadbeef1dcb1642017-03-29 21:08:16 -070099static const char kDataChannelLabel[] = "data_channel";
100
101// SRTP cipher name negotiated by the tests. This must be updated if the
102// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700103static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700104static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
105
Steve Antonede9ca52017-10-16 13:04:27 -0700106static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
107
deadbeef1dcb1642017-03-29 21:08:16 -0700108// Helper function for constructing offer/answer options to initiate an ICE
109// restart.
110PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
111 PeerConnectionInterface::RTCOfferAnswerOptions options;
112 options.ice_restart = true;
113 return options;
114}
115
deadbeefd8ad7882017-04-18 16:01:17 -0700116// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
117// attribute from received SDP, simulating a legacy endpoint.
118void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
119 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800120 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700121 }
122 desc->set_msid_supported(false);
Henrik Boström5b147782018-12-04 11:25:05 +0100123 desc->set_msid_signaling(0);
deadbeefd8ad7882017-04-18 16:01:17 -0700124}
125
Seth Hampson5897a6e2018-04-03 11:16:33 -0700126// Removes all stream information besides the stream ids, simulating an
127// endpoint that only signals a=msid lines to convey stream_ids.
128void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
129 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700130 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700131 std::vector<std::string> stream_ids;
132 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700133 const StreamParams& first_stream =
134 content.media_description()->streams()[0];
135 track_id = first_stream.id;
136 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700137 }
138 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700139 StreamParams new_stream;
140 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700141 new_stream.set_stream_ids(stream_ids);
142 content.media_description()->AddStream(new_stream);
143 }
144}
145
zhihuangf8164932017-05-19 13:09:47 -0700146int FindFirstMediaStatsIndexByKind(
147 const std::string& kind,
148 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
149 media_stats_vec) {
150 for (size_t i = 0; i < media_stats_vec.size(); i++) {
151 if (media_stats_vec[i]->kind.ValueToString() == kind) {
152 return i;
153 }
154 }
155 return -1;
156}
157
deadbeef1dcb1642017-03-29 21:08:16 -0700158class SignalingMessageReceiver {
159 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800160 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700161 virtual void ReceiveIceMessage(const std::string& sdp_mid,
162 int sdp_mline_index,
163 const std::string& msg) = 0;
164
165 protected:
166 SignalingMessageReceiver() {}
167 virtual ~SignalingMessageReceiver() {}
168};
169
170class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
171 public:
172 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
173 : expected_media_type_(media_type) {}
174
175 void OnFirstPacketReceived(cricket::MediaType media_type) override {
176 ASSERT_EQ(expected_media_type_, media_type);
177 first_packet_received_ = true;
178 }
179
180 bool first_packet_received() const { return first_packet_received_; }
181
182 virtual ~MockRtpReceiverObserver() {}
183
184 private:
185 bool first_packet_received_ = false;
186 cricket::MediaType expected_media_type_;
187};
188
189// Helper class that wraps a peer connection, observes it, and can accept
190// signaling messages from another wrapper.
191//
192// Uses a fake network, fake A/V capture, and optionally fake
193// encoders/decoders, though they aren't used by default since they don't
194// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700195// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800196// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700197class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800198 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700199 public:
200 // Different factory methods for convenience.
201 // TODO(deadbeef): Could use the pattern of:
202 //
203 // PeerConnectionWrapper =
204 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
205 //
206 // To reduce some code duplication.
207 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
208 const std::string& debug_name,
209 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
210 rtc::Thread* network_thread,
211 rtc::Thread* worker_thread) {
212 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700213 webrtc::PeerConnectionDependencies dependencies(nullptr);
214 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200215 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800216 worker_thread, nullptr,
Johannes Kron184ea662020-01-29 12:43:36 +0100217 /*media_transport_factory=*/nullptr,
218 /*reset_encoder_factory=*/false,
219 /*reset_decoder_factory=*/false)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700220 delete client;
221 return nullptr;
222 }
223 return client;
224 }
225
deadbeef2f425aa2017-04-14 10:41:32 -0700226 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
227 return peer_connection_factory_.get();
228 }
229
deadbeef1dcb1642017-03-29 21:08:16 -0700230 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
231
232 // If a signaling message receiver is set (via ConnectFakeSignaling), this
233 // will set the whole offer/answer exchange in motion. Just need to wait for
234 // the signaling state to reach "stable".
235 void CreateAndSetAndSignalOffer() {
Eldar Rello5ab79e62019-10-09 18:29:44 +0300236 auto offer = CreateOfferAndWait();
deadbeef1dcb1642017-03-29 21:08:16 -0700237 ASSERT_NE(nullptr, offer);
238 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
239 }
240
241 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
242 // when a remote offer is received (via fake signaling) and an answer is
243 // generated. By default, uses default options.
244 void SetOfferAnswerOptions(
245 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
246 offer_answer_options_ = options;
247 }
248
249 // Set a callback to be invoked when SDP is received via the fake signaling
250 // channel, which provides an opportunity to munge (modify) the SDP. This is
251 // used to test SDP being applied that a PeerConnection would normally not
252 // generate, but a non-JSEP endpoint might.
253 void SetReceivedSdpMunger(
254 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100255 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700256 }
257
deadbeefc964d0b2017-04-03 10:03:35 -0700258 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700259 // generated.
260 void SetGeneratedSdpMunger(
261 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100262 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700263 }
264
Seth Hampson2f0d7022018-02-20 11:54:42 -0800265 // Set a callback to be invoked when a remote offer is received via the fake
266 // signaling channel. This provides an opportunity to change the
267 // PeerConnection state before an answer is created and sent to the caller.
268 void SetRemoteOfferHandler(std::function<void()> handler) {
269 remote_offer_handler_ = std::move(handler);
270 }
271
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800272 void SetRemoteAsyncResolver(rtc::MockAsyncResolver* resolver) {
273 remote_async_resolver_ = resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700274 }
275
Steve Antonede9ca52017-10-16 13:04:27 -0700276 // Every ICE connection state in order that has been seen by the observer.
277 std::vector<PeerConnectionInterface::IceConnectionState>
278 ice_connection_state_history() const {
279 return ice_connection_state_history_;
280 }
Steve Anton6f25b092017-10-23 09:39:20 -0700281 void clear_ice_connection_state_history() {
282 ice_connection_state_history_.clear();
283 }
Steve Antonede9ca52017-10-16 13:04:27 -0700284
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100285 // Every standardized ICE connection state in order that has been seen by the
286 // observer.
287 std::vector<PeerConnectionInterface::IceConnectionState>
288 standardized_ice_connection_state_history() const {
289 return standardized_ice_connection_state_history_;
290 }
291
Jonas Olsson635474e2018-10-18 15:58:17 +0200292 // Every PeerConnection state in order that has been seen by the observer.
293 std::vector<PeerConnectionInterface::PeerConnectionState>
294 peer_connection_state_history() const {
295 return peer_connection_state_history_;
296 }
297
Steve Antonede9ca52017-10-16 13:04:27 -0700298 // Every ICE gathering state in order that has been seen by the observer.
299 std::vector<PeerConnectionInterface::IceGatheringState>
300 ice_gathering_state_history() const {
301 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700302 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700303 std::vector<cricket::CandidatePairChangeEvent>
304 ice_candidate_pair_change_history() const {
305 return ice_candidate_pair_change_history_;
306 }
deadbeef1dcb1642017-03-29 21:08:16 -0700307
Eldar Rello5ab79e62019-10-09 18:29:44 +0300308 // Every PeerConnection signaling state in order that has been seen by the
309 // observer.
310 std::vector<PeerConnectionInterface::SignalingState>
311 peer_connection_signaling_state_history() const {
312 return peer_connection_signaling_state_history_;
313 }
314
Steve Anton15324772018-01-16 10:26:49 -0800315 void AddAudioVideoTracks() {
316 AddAudioTrack();
317 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700318 }
319
Steve Anton74255ff2018-01-24 18:32:57 -0800320 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
321 return AddTrack(CreateLocalAudioTrack());
322 }
deadbeef1dcb1642017-03-29 21:08:16 -0700323
Steve Anton74255ff2018-01-24 18:32:57 -0800324 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
325 return AddTrack(CreateLocalVideoTrack());
326 }
deadbeef1dcb1642017-03-29 21:08:16 -0700327
328 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200329 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700330 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200331 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700332 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200333 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700334 // TODO(perkj): Test audio source when it is implemented. Currently audio
335 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700336 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700337 source);
338 }
339
340 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200341 webrtc::FakePeriodicVideoSource::Config config;
342 config.timestamp_offset_ms = rtc::TimeMillis();
343 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700344 }
345
346 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200347 CreateLocalVideoTrackWithConfig(
348 webrtc::FakePeriodicVideoSource::Config config) {
349 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700350 }
351
352 rtc::scoped_refptr<webrtc::VideoTrackInterface>
353 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200354 webrtc::FakePeriodicVideoSource::Config config;
355 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200356 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200357 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700358 }
359
Steve Anton74255ff2018-01-24 18:32:57 -0800360 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
361 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800362 const std::vector<std::string>& stream_ids = {}) {
363 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800364 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800365 return result.MoveValue();
366 }
367
368 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
369 cricket::MediaType media_type) {
370 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +0100371 for (const auto& receiver : pc()->GetReceivers()) {
Steve Anton74255ff2018-01-24 18:32:57 -0800372 if (receiver->media_type() == media_type) {
373 receivers.push_back(receiver);
374 }
375 }
376 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700377 }
378
Seth Hampson2f0d7022018-02-20 11:54:42 -0800379 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
380 cricket::MediaType media_type) {
381 for (auto transceiver : pc()->GetTransceivers()) {
382 if (transceiver->receiver()->media_type() == media_type) {
383 return transceiver;
384 }
385 }
386 return nullptr;
387 }
388
deadbeef1dcb1642017-03-29 21:08:16 -0700389 bool SignalingStateStable() {
390 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
391 }
392
393 void CreateDataChannel() { CreateDataChannel(nullptr); }
394
395 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700396 CreateDataChannel(kDataChannelLabel, init);
397 }
398
399 void CreateDataChannel(const std::string& label,
400 const webrtc::DataChannelInit* init) {
401 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700402 ASSERT_TRUE(data_channel_.get() != nullptr);
403 data_observer_.reset(new MockDataChannelObserver(data_channel_));
404 }
405
406 DataChannelInterface* data_channel() { return data_channel_; }
407 const MockDataChannelObserver* data_observer() const {
408 return data_observer_.get();
409 }
410
411 int audio_frames_received() const {
412 return fake_audio_capture_module_->frames_received();
413 }
414
415 // Takes minimum of video frames received for each track.
416 //
417 // Can be used like:
418 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
419 //
420 // To ensure that all video tracks received at least a certain number of
421 // frames.
422 int min_video_frames_received_per_track() const {
423 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200424 if (fake_video_renderers_.empty()) {
425 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700426 }
deadbeef1dcb1642017-03-29 21:08:16 -0700427
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200428 for (const auto& pair : fake_video_renderers_) {
429 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700430 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200431 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700432 }
433
434 // Returns a MockStatsObserver in a state after stats gathering finished,
435 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700436 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700437 webrtc::MediaStreamTrackInterface* track) {
438 rtc::scoped_refptr<MockStatsObserver> observer(
439 new rtc::RefCountedObject<MockStatsObserver>());
440 EXPECT_TRUE(peer_connection_->GetStats(
441 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
442 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
443 return observer;
444 }
445
446 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700447 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
448 return OldGetStatsForTrack(nullptr);
449 }
450
451 // Synchronously gets stats and returns them. If it times out, fails the test
452 // and returns null.
453 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
454 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
455 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
456 peer_connection_->GetStats(callback);
457 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
458 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700459 }
460
461 int rendered_width() {
462 EXPECT_FALSE(fake_video_renderers_.empty());
463 return fake_video_renderers_.empty()
464 ? 0
465 : fake_video_renderers_.begin()->second->width();
466 }
467
468 int rendered_height() {
469 EXPECT_FALSE(fake_video_renderers_.empty());
470 return fake_video_renderers_.empty()
471 ? 0
472 : fake_video_renderers_.begin()->second->height();
473 }
474
475 double rendered_aspect_ratio() {
476 if (rendered_height() == 0) {
477 return 0.0;
478 }
479 return static_cast<double>(rendered_width()) / rendered_height();
480 }
481
482 webrtc::VideoRotation rendered_rotation() {
483 EXPECT_FALSE(fake_video_renderers_.empty());
484 return fake_video_renderers_.empty()
485 ? webrtc::kVideoRotation_0
486 : fake_video_renderers_.begin()->second->rotation();
487 }
488
489 int local_rendered_width() {
490 return local_video_renderer_ ? local_video_renderer_->width() : 0;
491 }
492
493 int local_rendered_height() {
494 return local_video_renderer_ ? local_video_renderer_->height() : 0;
495 }
496
497 double local_rendered_aspect_ratio() {
498 if (local_rendered_height() == 0) {
499 return 0.0;
500 }
501 return static_cast<double>(local_rendered_width()) /
502 local_rendered_height();
503 }
504
505 size_t number_of_remote_streams() {
506 if (!pc()) {
507 return 0;
508 }
509 return pc()->remote_streams()->count();
510 }
511
512 StreamCollectionInterface* remote_streams() const {
513 if (!pc()) {
514 ADD_FAILURE();
515 return nullptr;
516 }
517 return pc()->remote_streams();
518 }
519
520 StreamCollectionInterface* local_streams() {
521 if (!pc()) {
522 ADD_FAILURE();
523 return nullptr;
524 }
525 return pc()->local_streams();
526 }
527
528 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
529 return pc()->signaling_state();
530 }
531
532 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
533 return pc()->ice_connection_state();
534 }
535
Jonas Olsson7a6739e2019-01-15 16:31:55 +0100536 webrtc::PeerConnectionInterface::IceConnectionState
537 standardized_ice_connection_state() {
538 return pc()->standardized_ice_connection_state();
539 }
540
deadbeef1dcb1642017-03-29 21:08:16 -0700541 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
542 return pc()->ice_gathering_state();
543 }
544
545 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
546 // GetReceivers. They're updated automatically when a remote offer/answer
547 // from the fake signaling channel is applied, or when
548 // ResetRtpReceiverObservers below is called.
549 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
550 rtp_receiver_observers() {
551 return rtp_receiver_observers_;
552 }
553
554 void ResetRtpReceiverObservers() {
555 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100556 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
557 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700558 std::unique_ptr<MockRtpReceiverObserver> observer(
559 new MockRtpReceiverObserver(receiver->media_type()));
560 receiver->SetObserver(observer.get());
561 rtp_receiver_observers_.push_back(std::move(observer));
562 }
563 }
564
Qingsi Wangecd30542019-05-22 14:34:56 -0700565 rtc::FakeNetworkManager* network_manager() const {
Steve Antonede9ca52017-10-16 13:04:27 -0700566 return fake_network_manager_.get();
567 }
568 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
569
Qingsi Wang7685e862018-06-11 20:15:46 -0700570 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
571 return event_log_factory_;
572 }
573
Qingsi Wangc129c352019-04-18 10:41:58 -0700574 const cricket::Candidate& last_candidate_gathered() const {
575 return last_candidate_gathered_;
576 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300577 const cricket::IceCandidateErrorEvent& error_event() const {
578 return error_event_;
579 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700580
Qingsi Wangecd30542019-05-22 14:34:56 -0700581 // Sets the mDNS responder for the owned fake network manager and keeps a
582 // reference to the responder.
583 void SetMdnsResponder(
584 std::unique_ptr<webrtc::FakeMdnsResponder> mdns_responder) {
585 RTC_DCHECK(mdns_responder != nullptr);
586 mdns_responder_ = mdns_responder.get();
587 network_manager()->set_mdns_responder(std::move(mdns_responder));
588 }
589
Eldar Rello5ab79e62019-10-09 18:29:44 +0300590 // Returns null on failure.
591 std::unique_ptr<SessionDescriptionInterface> CreateOfferAndWait() {
592 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
593 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
594 pc()->CreateOffer(observer, offer_answer_options_);
595 return WaitForDescriptionFromObserver(observer);
596 }
597
deadbeef1dcb1642017-03-29 21:08:16 -0700598 private:
599 explicit PeerConnectionWrapper(const std::string& debug_name)
600 : debug_name_(debug_name) {}
601
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800602 bool Init(
603 const PeerConnectionFactory::Options* options,
604 const PeerConnectionInterface::RTCConfiguration* config,
605 webrtc::PeerConnectionDependencies dependencies,
606 rtc::Thread* network_thread,
607 rtc::Thread* worker_thread,
608 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron184ea662020-01-29 12:43:36 +0100609 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory,
610 bool reset_encoder_factory,
611 bool reset_decoder_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700612 // There's an error in this test code if Init ends up being called twice.
613 RTC_DCHECK(!peer_connection_);
614 RTC_DCHECK(!peer_connection_factory_);
615
616 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700617 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700618
619 std::unique_ptr<cricket::PortAllocator> port_allocator(
620 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700621 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700622 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
623 if (!fake_audio_capture_module_) {
624 return false;
625 }
deadbeef1dcb1642017-03-29 21:08:16 -0700626 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700627
628 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
629 pc_factory_dependencies.network_thread = network_thread;
630 pc_factory_dependencies.worker_thread = worker_thread;
631 pc_factory_dependencies.signaling_thread = signaling_thread;
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200632 pc_factory_dependencies.task_queue_factory =
633 webrtc::CreateDefaultTaskQueueFactory();
634 cricket::MediaEngineDependencies media_deps;
635 media_deps.task_queue_factory =
636 pc_factory_dependencies.task_queue_factory.get();
637 media_deps.adm = fake_audio_capture_module_;
638 webrtc::SetMediaEngineDefaults(&media_deps);
Johannes Kron184ea662020-01-29 12:43:36 +0100639
640 if (reset_encoder_factory) {
641 media_deps.video_encoder_factory.reset();
642 }
643 if (reset_decoder_factory) {
644 media_deps.video_decoder_factory.reset();
645 }
646
Qingsi Wang7685e862018-06-11 20:15:46 -0700647 pc_factory_dependencies.media_engine =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200648 cricket::CreateMediaEngine(std::move(media_deps));
Qingsi Wang7685e862018-06-11 20:15:46 -0700649 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
650 if (event_log_factory) {
651 event_log_factory_ = event_log_factory.get();
652 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
653 } else {
654 pc_factory_dependencies.event_log_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200655 std::make_unique<webrtc::RtcEventLogFactory>(
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200656 pc_factory_dependencies.task_queue_factory.get());
Qingsi Wang7685e862018-06-11 20:15:46 -0700657 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800658 if (media_transport_factory) {
659 pc_factory_dependencies.media_transport_factory =
660 std::move(media_transport_factory);
661 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700662 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
663 std::move(pc_factory_dependencies));
664
deadbeef1dcb1642017-03-29 21:08:16 -0700665 if (!peer_connection_factory_) {
666 return false;
667 }
668 if (options) {
669 peer_connection_factory_->SetOptions(*options);
670 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800671 if (config) {
672 sdp_semantics_ = config->sdp_semantics;
673 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700674
675 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200676 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700677 return peer_connection_.get() != nullptr;
678 }
679
680 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700681 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700682 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700683 PeerConnectionInterface::RTCConfiguration modified_config;
684 // If |config| is null, this will result in a default configuration being
685 // used.
686 if (config) {
687 modified_config = *config;
688 }
689 // Disable resolution adaptation; we don't want it interfering with the
690 // test results.
691 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
692 // ratios and not specific resolutions, is this even necessary?
693 modified_config.set_cpu_adaptation(false);
694
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700695 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700696 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700697 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700698 }
699
700 void set_signaling_message_receiver(
701 SignalingMessageReceiver* signaling_message_receiver) {
702 signaling_message_receiver_ = signaling_message_receiver;
703 }
704
705 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
706
Steve Antonede9ca52017-10-16 13:04:27 -0700707 void set_signal_ice_candidates(bool signal) {
708 signal_ice_candidates_ = signal;
709 }
710
deadbeef1dcb1642017-03-29 21:08:16 -0700711 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200712 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700713 // Set max frame rate to 10fps to reduce the risk of test flakiness.
714 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200715 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700716
Niels Möller5c7efe72018-05-11 10:34:46 +0200717 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200718 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
719 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700720 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200721 peer_connection_factory_->CreateVideoTrack(
722 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700723 if (!local_video_renderer_) {
724 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
725 }
726 return track;
727 }
728
729 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100730 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800731 std::unique_ptr<SessionDescriptionInterface> desc =
732 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700733 if (received_sdp_munger_) {
734 received_sdp_munger_(desc->description());
735 }
736
737 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
738 // Setting a remote description may have changed the number of receivers,
739 // so reset the receiver observers.
740 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800741 if (remote_offer_handler_) {
742 remote_offer_handler_();
743 }
deadbeef1dcb1642017-03-29 21:08:16 -0700744 auto answer = CreateAnswer();
745 ASSERT_NE(nullptr, answer);
746 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
747 }
748
749 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100750 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800751 std::unique_ptr<SessionDescriptionInterface> desc =
752 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700753 if (received_sdp_munger_) {
754 received_sdp_munger_(desc->description());
755 }
756
757 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
758 // Set the RtpReceiverObserver after receivers are created.
759 ResetRtpReceiverObservers();
760 }
761
762 // Returns null on failure.
deadbeef1dcb1642017-03-29 21:08:16 -0700763 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
764 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
765 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
766 pc()->CreateAnswer(observer, offer_answer_options_);
767 return WaitForDescriptionFromObserver(observer);
768 }
769
770 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100771 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700772 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
773 if (!observer->result()) {
774 return nullptr;
775 }
776 auto description = observer->MoveDescription();
777 if (generated_sdp_munger_) {
778 generated_sdp_munger_(description->description());
779 }
780 return description;
781 }
782
783 // Setting the local description and sending the SDP message over the fake
784 // signaling channel are combined into the same method because the SDP
785 // message needs to be sent as soon as SetLocalDescription finishes, without
786 // waiting for the observer to be called. This ensures that ICE candidates
787 // don't outrace the description.
788 bool SetLocalDescriptionAndSendSdpMessage(
789 std::unique_ptr<SessionDescriptionInterface> desc) {
790 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
791 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100792 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800793 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700794 std::string sdp;
795 EXPECT_TRUE(desc->ToString(&sdp));
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700796 RTC_LOG(LS_INFO) << debug_name_ << ": local SDP contents=\n" << sdp;
deadbeef1dcb1642017-03-29 21:08:16 -0700797 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800798 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
799 RemoveUnusedVideoRenderers();
800 }
deadbeef1dcb1642017-03-29 21:08:16 -0700801 // As mentioned above, we need to send the message immediately after
802 // SetLocalDescription.
803 SendSdpMessage(type, sdp);
804 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
805 return true;
806 }
807
808 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
809 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
810 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100811 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700812 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800813 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
814 RemoveUnusedVideoRenderers();
815 }
deadbeef1dcb1642017-03-29 21:08:16 -0700816 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
817 return observer->result();
818 }
819
Seth Hampson2f0d7022018-02-20 11:54:42 -0800820 // This is a work around to remove unused fake_video_renderers from
821 // transceivers that have either stopped or are no longer receiving.
822 void RemoveUnusedVideoRenderers() {
823 auto transceivers = pc()->GetTransceivers();
824 for (auto& transceiver : transceivers) {
825 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
826 continue;
827 }
828 // Remove fake video renderers from any stopped transceivers.
829 if (transceiver->stopped()) {
830 auto it =
831 fake_video_renderers_.find(transceiver->receiver()->track()->id());
832 if (it != fake_video_renderers_.end()) {
833 fake_video_renderers_.erase(it);
834 }
835 }
836 // Remove fake video renderers from any transceivers that are no longer
837 // receiving.
838 if ((transceiver->current_direction() &&
839 !webrtc::RtpTransceiverDirectionHasRecv(
840 *transceiver->current_direction()))) {
841 auto it =
842 fake_video_renderers_.find(transceiver->receiver()->track()->id());
843 if (it != fake_video_renderers_.end()) {
844 fake_video_renderers_.erase(it);
845 }
846 }
847 }
848 }
849
deadbeef1dcb1642017-03-29 21:08:16 -0700850 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
851 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800852 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700853 if (signaling_delay_ms_ == 0) {
854 RelaySdpMessageIfReceiverExists(type, msg);
855 } else {
856 invoker_.AsyncInvokeDelayed<void>(
857 RTC_FROM_HERE, rtc::Thread::Current(),
858 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
859 this, type, msg),
860 signaling_delay_ms_);
861 }
862 }
863
Steve Antona3a92c22017-12-07 10:27:41 -0800864 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700865 if (signaling_message_receiver_) {
866 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
867 }
868 }
869
870 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
871 // default).
872 void SendIceMessage(const std::string& sdp_mid,
873 int sdp_mline_index,
874 const std::string& msg) {
875 if (signaling_delay_ms_ == 0) {
876 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
877 } else {
878 invoker_.AsyncInvokeDelayed<void>(
879 RTC_FROM_HERE, rtc::Thread::Current(),
880 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
881 this, sdp_mid, sdp_mline_index, msg),
882 signaling_delay_ms_);
883 }
884 }
885
886 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
887 int sdp_mline_index,
888 const std::string& msg) {
889 if (signaling_message_receiver_) {
890 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
891 msg);
892 }
893 }
894
895 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800896 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
897 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700898 HandleIncomingOffer(msg);
899 } else {
900 HandleIncomingAnswer(msg);
901 }
902 }
903
904 void ReceiveIceMessage(const std::string& sdp_mid,
905 int sdp_mline_index,
906 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100907 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700908 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
909 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
910 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
911 }
912
913 // PeerConnectionObserver callbacks.
914 void OnSignalingChange(
915 webrtc::PeerConnectionInterface::SignalingState new_state) override {
916 EXPECT_EQ(pc()->signaling_state(), new_state);
Eldar Rello5ab79e62019-10-09 18:29:44 +0300917 peer_connection_signaling_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700918 }
Steve Anton15324772018-01-16 10:26:49 -0800919 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
920 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
921 streams) override {
922 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
923 rtc::scoped_refptr<VideoTrackInterface> video_track(
924 static_cast<VideoTrackInterface*>(receiver->track().get()));
925 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700926 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800927 fake_video_renderers_[video_track->id()] =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200928 std::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700929 }
930 }
Steve Anton15324772018-01-16 10:26:49 -0800931 void OnRemoveTrack(
932 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
933 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
934 auto it = fake_video_renderers_.find(receiver->track()->id());
935 RTC_DCHECK(it != fake_video_renderers_.end());
936 fake_video_renderers_.erase(it);
937 }
938 }
deadbeef1dcb1642017-03-29 21:08:16 -0700939 void OnRenegotiationNeeded() override {}
940 void OnIceConnectionChange(
941 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
942 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700943 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700944 }
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100945 void OnStandardizedIceConnectionChange(
946 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
947 standardized_ice_connection_state_history_.push_back(new_state);
948 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200949 void OnConnectionChange(
950 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
951 peer_connection_state_history_.push_back(new_state);
952 }
953
deadbeef1dcb1642017-03-29 21:08:16 -0700954 void OnIceGatheringChange(
955 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700956 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700957 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700958 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700959
960 void OnIceSelectedCandidatePairChanged(
961 const cricket::CandidatePairChangeEvent& event) {
962 ice_candidate_pair_change_history_.push_back(event);
963 }
Alex Drake43faee02019-08-12 16:27:34 -0700964
deadbeef1dcb1642017-03-29 21:08:16 -0700965 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100966 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700967
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800968 if (remote_async_resolver_) {
969 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800970 if (local_candidate.address().IsUnresolvedIP()) {
971 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
972 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700973 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800974 local_candidate.address().hostname());
975 RTC_DCHECK(!resolved_ip.IsNil());
976 resolved_addr.SetResolvedIP(resolved_ip);
977 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
978 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
979 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700980 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700981 }
982
deadbeef1dcb1642017-03-29 21:08:16 -0700983 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800984 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700985 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700986 // Remote party may be deleted.
987 return;
988 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800989 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700990 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700991 }
Eldar Rello0095d372019-12-02 22:22:07 +0200992 void OnIceCandidateError(const std::string& address,
993 int port,
Eldar Relloda13ea22019-06-01 12:23:43 +0300994 const std::string& url,
995 int error_code,
996 const std::string& error_text) override {
Eldar Rello0095d372019-12-02 22:22:07 +0200997 error_event_ = cricket::IceCandidateErrorEvent(address, port, url,
Eldar Relloda13ea22019-06-01 12:23:43 +0300998 error_code, error_text);
999 }
deadbeef1dcb1642017-03-29 21:08:16 -07001000 void OnDataChannel(
1001 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001002 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -07001003 data_channel_ = data_channel;
1004 data_observer_.reset(new MockDataChannelObserver(data_channel));
1005 }
1006
deadbeef1dcb1642017-03-29 21:08:16 -07001007 std::string debug_name_;
1008
1009 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -07001010 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
1011 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001012
1013 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
1014 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
1015 peer_connection_factory_;
1016
Steve Antonede9ca52017-10-16 13:04:27 -07001017 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -07001018 // Needed to keep track of number of frames sent.
1019 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1020 // Needed to keep track of number of frames received.
1021 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1022 fake_video_renderers_;
1023 // Needed to ensure frames aren't received for removed tracks.
1024 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1025 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001026
1027 // For remote peer communication.
1028 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1029 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001030 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001031 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001032 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001033
Niels Möller5c7efe72018-05-11 10:34:46 +02001034 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001035 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001036 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1037 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001038 // |local_video_renderer_| attached to the first created local video track.
1039 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1040
Seth Hampson2f0d7022018-02-20 11:54:42 -08001041 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001042 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1043 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1044 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001045 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001046 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001047 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1048 std::unique_ptr<MockDataChannelObserver> data_observer_;
1049
1050 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1051
Steve Antonede9ca52017-10-16 13:04:27 -07001052 std::vector<PeerConnectionInterface::IceConnectionState>
1053 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001054 std::vector<PeerConnectionInterface::IceConnectionState>
1055 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001056 std::vector<PeerConnectionInterface::PeerConnectionState>
1057 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001058 std::vector<PeerConnectionInterface::IceGatheringState>
1059 ice_gathering_state_history_;
Alex Drake00c7ecf2019-08-06 10:54:47 -07001060 std::vector<cricket::CandidatePairChangeEvent>
1061 ice_candidate_pair_change_history_;
Eldar Rello5ab79e62019-10-09 18:29:44 +03001062 std::vector<PeerConnectionInterface::SignalingState>
1063 peer_connection_signaling_state_history_;
Qingsi Wang7685e862018-06-11 20:15:46 -07001064 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1065
deadbeef1dcb1642017-03-29 21:08:16 -07001066 rtc::AsyncInvoker invoker_;
1067
Seth Hampson2f0d7022018-02-20 11:54:42 -08001068 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001069};
1070
Elad Alon99c3fe52017-10-13 16:29:40 +02001071class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1072 public:
1073 virtual ~MockRtcEventLogOutput() = default;
1074 MOCK_CONST_METHOD0(IsActive, bool());
1075 MOCK_METHOD1(Write, bool(const std::string&));
1076};
1077
Seth Hampson2f0d7022018-02-20 11:54:42 -08001078// This helper object is used for both specifying how many audio/video frames
1079// are expected to be received for a caller/callee. It provides helper functions
1080// to specify these expectations. The object initially starts in a state of no
1081// expectations.
1082class MediaExpectations {
1083 public:
1084 enum ExpectFrames {
1085 kExpectSomeFrames,
1086 kExpectNoFrames,
1087 kNoExpectation,
1088 };
1089
1090 void ExpectBidirectionalAudioAndVideo() {
1091 ExpectBidirectionalAudio();
1092 ExpectBidirectionalVideo();
1093 }
1094
1095 void ExpectBidirectionalAudio() {
1096 CallerExpectsSomeAudio();
1097 CalleeExpectsSomeAudio();
1098 }
1099
1100 void ExpectNoAudio() {
1101 CallerExpectsNoAudio();
1102 CalleeExpectsNoAudio();
1103 }
1104
1105 void ExpectBidirectionalVideo() {
1106 CallerExpectsSomeVideo();
1107 CalleeExpectsSomeVideo();
1108 }
1109
1110 void ExpectNoVideo() {
1111 CallerExpectsNoVideo();
1112 CalleeExpectsNoVideo();
1113 }
1114
1115 void CallerExpectsSomeAudioAndVideo() {
1116 CallerExpectsSomeAudio();
1117 CallerExpectsSomeVideo();
1118 }
1119
1120 void CalleeExpectsSomeAudioAndVideo() {
1121 CalleeExpectsSomeAudio();
1122 CalleeExpectsSomeVideo();
1123 }
1124
1125 // Caller's audio functions.
1126 void CallerExpectsSomeAudio(
1127 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1128 caller_audio_expectation_ = kExpectSomeFrames;
1129 caller_audio_frames_expected_ = expected_audio_frames;
1130 }
1131
1132 void CallerExpectsNoAudio() {
1133 caller_audio_expectation_ = kExpectNoFrames;
1134 caller_audio_frames_expected_ = 0;
1135 }
1136
1137 // Caller's video functions.
1138 void CallerExpectsSomeVideo(
1139 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1140 caller_video_expectation_ = kExpectSomeFrames;
1141 caller_video_frames_expected_ = expected_video_frames;
1142 }
1143
1144 void CallerExpectsNoVideo() {
1145 caller_video_expectation_ = kExpectNoFrames;
1146 caller_video_frames_expected_ = 0;
1147 }
1148
1149 // Callee's audio functions.
1150 void CalleeExpectsSomeAudio(
1151 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1152 callee_audio_expectation_ = kExpectSomeFrames;
1153 callee_audio_frames_expected_ = expected_audio_frames;
1154 }
1155
1156 void CalleeExpectsNoAudio() {
1157 callee_audio_expectation_ = kExpectNoFrames;
1158 callee_audio_frames_expected_ = 0;
1159 }
1160
1161 // Callee's video functions.
1162 void CalleeExpectsSomeVideo(
1163 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1164 callee_video_expectation_ = kExpectSomeFrames;
1165 callee_video_frames_expected_ = expected_video_frames;
1166 }
1167
1168 void CalleeExpectsNoVideo() {
1169 callee_video_expectation_ = kExpectNoFrames;
1170 callee_video_frames_expected_ = 0;
1171 }
1172
1173 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1174 ExpectFrames caller_video_expectation_ = kNoExpectation;
1175 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1176 ExpectFrames callee_video_expectation_ = kNoExpectation;
1177 int caller_audio_frames_expected_ = 0;
1178 int caller_video_frames_expected_ = 0;
1179 int callee_audio_frames_expected_ = 0;
1180 int callee_video_frames_expected_ = 0;
1181};
1182
Qingsi Wang25ec8882019-11-15 12:33:05 -08001183class MockIceTransport : public webrtc::IceTransportInterface {
1184 public:
1185 MockIceTransport(const std::string& name, int component)
1186 : internal_(std::make_unique<cricket::FakeIceTransport>(
1187 name,
1188 component,
1189 nullptr /* network_thread */)) {}
1190 ~MockIceTransport() = default;
1191 cricket::IceTransportInternal* internal() { return internal_.get(); }
1192
1193 private:
1194 std::unique_ptr<cricket::FakeIceTransport> internal_;
1195};
1196
1197class MockIceTransportFactory : public IceTransportFactory {
1198 public:
1199 ~MockIceTransportFactory() override = default;
1200 rtc::scoped_refptr<IceTransportInterface> CreateIceTransport(
1201 const std::string& transport_name,
1202 int component,
1203 IceTransportInit init) {
1204 RecordIceTransportCreated();
1205 return new rtc::RefCountedObject<MockIceTransport>(transport_name,
1206 component);
1207 }
1208 MOCK_METHOD0(RecordIceTransportCreated, void());
1209};
1210
deadbeef1dcb1642017-03-29 21:08:16 -07001211// Tests two PeerConnections connecting to each other end-to-end, using a
1212// virtual network, fake A/V capture and fake encoder/decoders. The
1213// PeerConnections share the threads/socket servers, but use separate versions
1214// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001215class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001216 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001217 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1218 : sdp_semantics_(sdp_semantics),
1219 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001220 fss_(new rtc::FirewallSocketServer(ss_.get())),
1221 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001222 worker_thread_(rtc::Thread::Create()),
1223 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001224 network_thread_->SetName("PCNetworkThread", this);
1225 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001226 RTC_CHECK(network_thread_->Start());
1227 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001228 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001229 }
1230
Seth Hampson2f0d7022018-02-20 11:54:42 -08001231 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001232 // The PeerConnections should deleted before the TurnCustomizers.
1233 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1234 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1235 // that the TurnCustomizer outlives the life of the PeerConnection or else
1236 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001237 if (caller_) {
1238 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001239 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001240 }
1241 if (callee_) {
1242 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001243 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001244 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001245
1246 // If turn servers were created for the test they need to be destroyed on
1247 // the network thread.
1248 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1249 turn_servers_.clear();
1250 turn_customizers_.clear();
1251 });
deadbeef1dcb1642017-03-29 21:08:16 -07001252 }
1253
1254 bool SignalingStateStable() {
1255 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1256 }
1257
deadbeef71452802017-05-07 17:21:01 -07001258 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001259 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1260 // are connected. This is an important distinction. Once we have separate
1261 // ICE and DTLS state, this check needs to use the DTLS state.
1262 return (callee()->ice_connection_state() ==
1263 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1264 callee()->ice_connection_state() ==
1265 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1266 (caller()->ice_connection_state() ==
1267 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1268 caller()->ice_connection_state() ==
1269 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001270 }
1271
Qingsi Wang7685e862018-06-11 20:15:46 -07001272 // When |event_log_factory| is null, the default implementation of the event
1273 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001274 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1275 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001276 const PeerConnectionFactory::Options* options,
1277 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001278 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001279 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron184ea662020-01-29 12:43:36 +01001280 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory,
1281 bool reset_encoder_factory,
1282 bool reset_decoder_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001283 RTCConfiguration modified_config;
1284 if (config) {
1285 modified_config = *config;
1286 }
Steve Anton3acffc32018-04-12 17:21:03 -07001287 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001288 if (!dependencies.cert_generator) {
1289 dependencies.cert_generator =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001290 std::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001291 }
1292 std::unique_ptr<PeerConnectionWrapper> client(
1293 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001294
Niels Möllerf06f9232018-08-07 12:32:18 +02001295 if (!client->Init(options, &modified_config, std::move(dependencies),
1296 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001297 std::move(event_log_factory),
Johannes Kron184ea662020-01-29 12:43:36 +01001298 std::move(media_transport_factory), reset_encoder_factory,
1299 reset_decoder_factory)) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001300 return nullptr;
1301 }
1302 return client;
1303 }
1304
Qingsi Wang7685e862018-06-11 20:15:46 -07001305 std::unique_ptr<PeerConnectionWrapper>
1306 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1307 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001308 const PeerConnectionFactory::Options* options,
1309 const RTCConfiguration* config,
1310 webrtc::PeerConnectionDependencies dependencies) {
1311 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1312 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Johannes Kron184ea662020-01-29 12:43:36 +01001313 return CreatePeerConnectionWrapper(
1314 debug_name, options, config, std::move(dependencies),
1315 std::move(event_log_factory),
1316 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1317 /*reset_decoder_factory=*/false);
Qingsi Wang7685e862018-06-11 20:15:46 -07001318 }
1319
deadbeef1dcb1642017-03-29 21:08:16 -07001320 bool CreatePeerConnectionWrappers() {
1321 return CreatePeerConnectionWrappersWithConfig(
1322 PeerConnectionInterface::RTCConfiguration(),
1323 PeerConnectionInterface::RTCConfiguration());
1324 }
1325
Steve Anton3acffc32018-04-12 17:21:03 -07001326 bool CreatePeerConnectionWrappersWithSdpSemantics(
1327 SdpSemantics caller_semantics,
1328 SdpSemantics callee_semantics) {
1329 // Can't specify the sdp_semantics in the passed-in configuration since it
1330 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1331 // stored in sdp_semantics_. So get around this by modifying the instance
1332 // variable before calling CreatePeerConnectionWrapper for the caller and
1333 // callee PeerConnections.
1334 SdpSemantics original_semantics = sdp_semantics_;
1335 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001336 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001337 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Johannes Kron184ea662020-01-29 12:43:36 +01001338 nullptr, /*media_transport_factory=*/nullptr,
1339 /*reset_encoder_factory=*/false,
1340 /*reset_decoder_factory=*/false);
Steve Anton3acffc32018-04-12 17:21:03 -07001341 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001342 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001343 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Johannes Kron184ea662020-01-29 12:43:36 +01001344 nullptr, /*media_transport_factory=*/nullptr,
1345 /*reset_encoder_factory=*/false,
1346 /*reset_decoder_factory=*/false);
Steve Anton3acffc32018-04-12 17:21:03 -07001347 sdp_semantics_ = original_semantics;
1348 return caller_ && callee_;
1349 }
1350
deadbeef1dcb1642017-03-29 21:08:16 -07001351 bool CreatePeerConnectionWrappersWithConfig(
1352 const PeerConnectionInterface::RTCConfiguration& caller_config,
1353 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001354 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001355 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001356 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron184ea662020-01-29 12:43:36 +01001357 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1358 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001359 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001360 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001361 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron184ea662020-01-29 12:43:36 +01001362 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1363 /*reset_decoder_factory=*/false);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001364 return caller_ && callee_;
1365 }
1366
1367 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1368 const PeerConnectionInterface::RTCConfiguration& caller_config,
1369 const PeerConnectionInterface::RTCConfiguration& callee_config,
1370 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1371 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
Johannes Kron184ea662020-01-29 12:43:36 +01001372 caller_ = CreatePeerConnectionWrapper(
1373 "Caller", nullptr, &caller_config,
1374 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1375 std::move(caller_factory), /*reset_encoder_factory=*/false,
1376 /*reset_decoder_factory=*/false);
1377 callee_ = CreatePeerConnectionWrapper(
1378 "Callee", nullptr, &callee_config,
1379 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1380 std::move(callee_factory), /*reset_encoder_factory=*/false,
1381 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001382 return caller_ && callee_;
1383 }
1384
1385 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1386 const PeerConnectionInterface::RTCConfiguration& caller_config,
1387 webrtc::PeerConnectionDependencies caller_dependencies,
1388 const PeerConnectionInterface::RTCConfiguration& callee_config,
1389 webrtc::PeerConnectionDependencies callee_dependencies) {
Johannes Kron184ea662020-01-29 12:43:36 +01001390 caller_ = CreatePeerConnectionWrapper(
1391 "Caller", nullptr, &caller_config, std::move(caller_dependencies),
1392 nullptr,
1393 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1394 /*reset_decoder_factory=*/false);
1395 callee_ = CreatePeerConnectionWrapper(
1396 "Callee", nullptr, &callee_config, std::move(callee_dependencies),
1397 nullptr,
1398 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1399 /*reset_decoder_factory=*/false);
deadbeef1dcb1642017-03-29 21:08:16 -07001400 return caller_ && callee_;
1401 }
1402
1403 bool CreatePeerConnectionWrappersWithOptions(
1404 const PeerConnectionFactory::Options& caller_options,
1405 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001406 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001407 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001408 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron184ea662020-01-29 12:43:36 +01001409 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1410 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001411 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001412 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001413 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron184ea662020-01-29 12:43:36 +01001414 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1415 /*reset_decoder_factory=*/false);
Qingsi Wang7685e862018-06-11 20:15:46 -07001416 return caller_ && callee_;
1417 }
1418
1419 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1420 PeerConnectionInterface::RTCConfiguration default_config;
1421 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001422 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001423 webrtc::PeerConnectionDependencies(nullptr));
1424 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001425 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001426 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001427 return caller_ && callee_;
1428 }
1429
Seth Hampson2f0d7022018-02-20 11:54:42 -08001430 std::unique_ptr<PeerConnectionWrapper>
1431 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001432 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1433 new FakeRTCCertificateGenerator());
1434 cert_generator->use_alternate_key();
1435
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001436 webrtc::PeerConnectionDependencies dependencies(nullptr);
1437 dependencies.cert_generator = std::move(cert_generator);
Johannes Kron184ea662020-01-29 12:43:36 +01001438 return CreatePeerConnectionWrapper(
1439 "New Peer", nullptr, nullptr, std::move(dependencies), nullptr,
1440 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1441 /*reset_decoder_factory=*/false);
1442 }
1443
1444 bool CreateOneDirectionalPeerConnectionWrappers(bool caller_to_callee) {
1445 caller_ = CreatePeerConnectionWrapper(
1446 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1447 nullptr, /*media_transport_factory=*/nullptr,
1448 /*reset_encoder_factory=*/!caller_to_callee,
1449 /*reset_decoder_factory=*/caller_to_callee);
1450 callee_ = CreatePeerConnectionWrapper(
1451 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1452 nullptr, /*media_transport_factory=*/nullptr,
1453 /*reset_encoder_factory=*/caller_to_callee,
1454 /*reset_decoder_factory=*/!caller_to_callee);
1455 return caller_ && callee_;
deadbeef1dcb1642017-03-29 21:08:16 -07001456 }
1457
Seth Hampsonaed71642018-06-11 07:41:32 -07001458 cricket::TestTurnServer* CreateTurnServer(
1459 rtc::SocketAddress internal_address,
1460 rtc::SocketAddress external_address,
1461 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1462 const std::string& common_name = "test turn server") {
1463 rtc::Thread* thread = network_thread();
1464 std::unique_ptr<cricket::TestTurnServer> turn_server =
1465 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1466 RTC_FROM_HERE,
1467 [thread, internal_address, external_address, type, common_name] {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001468 return std::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001469 thread, internal_address, external_address, type,
1470 /*ignore_bad_certs=*/true, common_name);
1471 });
1472 turn_servers_.push_back(std::move(turn_server));
1473 // Interactions with the turn server should be done on the network thread.
1474 return turn_servers_.back().get();
1475 }
1476
1477 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1478 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1479 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1480 RTC_FROM_HERE,
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001481 [] { return std::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001482 turn_customizers_.push_back(std::move(turn_customizer));
1483 // Interactions with the turn customizer should be done on the network
1484 // thread.
1485 return turn_customizers_.back().get();
1486 }
1487
1488 // Checks that the function counters for a TestTurnCustomizer are greater than
1489 // 0.
1490 void ExpectTurnCustomizerCountersIncremented(
1491 cricket::TestTurnCustomizer* turn_customizer) {
1492 unsigned int allow_channel_data_counter =
1493 network_thread()->Invoke<unsigned int>(
1494 RTC_FROM_HERE, [turn_customizer] {
1495 return turn_customizer->allow_channel_data_cnt_;
1496 });
1497 EXPECT_GT(allow_channel_data_counter, 0u);
1498 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1499 RTC_FROM_HERE,
1500 [turn_customizer] { return turn_customizer->modify_cnt_; });
1501 EXPECT_GT(modify_counter, 0u);
1502 }
1503
deadbeef1dcb1642017-03-29 21:08:16 -07001504 // Once called, SDP blobs and ICE candidates will be automatically signaled
1505 // between PeerConnections.
1506 void ConnectFakeSignaling() {
1507 caller_->set_signaling_message_receiver(callee_.get());
1508 callee_->set_signaling_message_receiver(caller_.get());
1509 }
1510
Steve Antonede9ca52017-10-16 13:04:27 -07001511 // Once called, SDP blobs will be automatically signaled between
1512 // PeerConnections. Note that ICE candidates will not be signaled unless they
1513 // are in the exchanged SDP blobs.
1514 void ConnectFakeSignalingForSdpOnly() {
1515 ConnectFakeSignaling();
1516 SetSignalIceCandidates(false);
1517 }
1518
deadbeef1dcb1642017-03-29 21:08:16 -07001519 void SetSignalingDelayMs(int delay_ms) {
1520 caller_->set_signaling_delay_ms(delay_ms);
1521 callee_->set_signaling_delay_ms(delay_ms);
1522 }
1523
Steve Antonede9ca52017-10-16 13:04:27 -07001524 void SetSignalIceCandidates(bool signal) {
1525 caller_->set_signal_ice_candidates(signal);
1526 callee_->set_signal_ice_candidates(signal);
1527 }
1528
deadbeef1dcb1642017-03-29 21:08:16 -07001529 // Messages may get lost on the unreliable DataChannel, so we send multiple
1530 // times to avoid test flakiness.
1531 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1532 const std::string& data,
1533 int retries) {
1534 for (int i = 0; i < retries; ++i) {
1535 dc->Send(DataBuffer(data));
1536 }
1537 }
1538
1539 rtc::Thread* network_thread() { return network_thread_.get(); }
1540
1541 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1542
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001543 webrtc::MediaTransportPair* loopback_media_transports() {
1544 return &loopback_media_transports_;
1545 }
1546
deadbeef1dcb1642017-03-29 21:08:16 -07001547 PeerConnectionWrapper* caller() { return caller_.get(); }
1548
1549 // Set the |caller_| to the |wrapper| passed in and return the
1550 // original |caller_|.
1551 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1552 PeerConnectionWrapper* wrapper) {
1553 PeerConnectionWrapper* old = caller_.release();
1554 caller_.reset(wrapper);
1555 return old;
1556 }
1557
1558 PeerConnectionWrapper* callee() { return callee_.get(); }
1559
1560 // Set the |callee_| to the |wrapper| passed in and return the
1561 // original |callee_|.
1562 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1563 PeerConnectionWrapper* wrapper) {
1564 PeerConnectionWrapper* old = callee_.release();
1565 callee_.reset(wrapper);
1566 return old;
1567 }
1568
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001569 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1570 network_thread()->Invoke<void>(
1571 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1572 caller()->port_allocator(), caller_flags));
1573 network_thread()->Invoke<void>(
1574 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1575 callee()->port_allocator(), callee_flags));
1576 }
1577
Steve Antonede9ca52017-10-16 13:04:27 -07001578 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1579
Seth Hampson2f0d7022018-02-20 11:54:42 -08001580 // Expects the provided number of new frames to be received within
1581 // kMaxWaitForFramesMs. The new expected frames are specified in
1582 // |media_expectations|. Returns false if any of the expectations were
1583 // not met.
1584 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1585 // First initialize the expected frame counts based upon the current
1586 // frame count.
1587 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1588 if (media_expectations.caller_audio_expectation_ ==
1589 MediaExpectations::kExpectSomeFrames) {
1590 total_caller_audio_frames_expected +=
1591 media_expectations.caller_audio_frames_expected_;
1592 }
1593 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001594 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001595 if (media_expectations.caller_video_expectation_ ==
1596 MediaExpectations::kExpectSomeFrames) {
1597 total_caller_video_frames_expected +=
1598 media_expectations.caller_video_frames_expected_;
1599 }
1600 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1601 if (media_expectations.callee_audio_expectation_ ==
1602 MediaExpectations::kExpectSomeFrames) {
1603 total_callee_audio_frames_expected +=
1604 media_expectations.callee_audio_frames_expected_;
1605 }
1606 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001607 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001608 if (media_expectations.callee_video_expectation_ ==
1609 MediaExpectations::kExpectSomeFrames) {
1610 total_callee_video_frames_expected +=
1611 media_expectations.callee_video_frames_expected_;
1612 }
deadbeef1dcb1642017-03-29 21:08:16 -07001613
Seth Hampson2f0d7022018-02-20 11:54:42 -08001614 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001615 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001616 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001617 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001618 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001619 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001620 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001621 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001622 total_callee_video_frames_expected,
1623 kMaxWaitForFramesMs);
1624 bool expectations_correct =
1625 caller()->audio_frames_received() >=
1626 total_caller_audio_frames_expected &&
1627 caller()->min_video_frames_received_per_track() >=
1628 total_caller_video_frames_expected &&
1629 callee()->audio_frames_received() >=
1630 total_callee_audio_frames_expected &&
1631 callee()->min_video_frames_received_per_track() >=
1632 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001633
Seth Hampson2f0d7022018-02-20 11:54:42 -08001634 // After the combined wait, print out a more detailed message upon
1635 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001636 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001637 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001638 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001639 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001640 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001641 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001642 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001643 total_callee_video_frames_expected);
1644
1645 // We want to make sure nothing unexpected was received.
1646 if (media_expectations.caller_audio_expectation_ ==
1647 MediaExpectations::kExpectNoFrames) {
1648 EXPECT_EQ(caller()->audio_frames_received(),
1649 total_caller_audio_frames_expected);
1650 if (caller()->audio_frames_received() !=
1651 total_caller_audio_frames_expected) {
1652 expectations_correct = false;
1653 }
1654 }
1655 if (media_expectations.caller_video_expectation_ ==
1656 MediaExpectations::kExpectNoFrames) {
1657 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1658 total_caller_video_frames_expected);
1659 if (caller()->min_video_frames_received_per_track() !=
1660 total_caller_video_frames_expected) {
1661 expectations_correct = false;
1662 }
1663 }
1664 if (media_expectations.callee_audio_expectation_ ==
1665 MediaExpectations::kExpectNoFrames) {
1666 EXPECT_EQ(callee()->audio_frames_received(),
1667 total_callee_audio_frames_expected);
1668 if (callee()->audio_frames_received() !=
1669 total_callee_audio_frames_expected) {
1670 expectations_correct = false;
1671 }
1672 }
1673 if (media_expectations.callee_video_expectation_ ==
1674 MediaExpectations::kExpectNoFrames) {
1675 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1676 total_callee_video_frames_expected);
1677 if (callee()->min_video_frames_received_per_track() !=
1678 total_callee_video_frames_expected) {
1679 expectations_correct = false;
1680 }
1681 }
1682 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001683 }
1684
Steve Antond91969e2019-05-30 12:27:03 -07001685 void ClosePeerConnections() {
1686 caller()->pc()->Close();
1687 callee()->pc()->Close();
1688 }
1689
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001690 void TestNegotiatedCipherSuite(
1691 const PeerConnectionFactory::Options& caller_options,
1692 const PeerConnectionFactory::Options& callee_options,
1693 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001694 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1695 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001696 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001697 caller()->AddAudioVideoTracks();
1698 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001699 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001700 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001701 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001702 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001703 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01001704 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
1705 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1706 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001707 }
1708
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001709 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1710 bool remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001711 bool aes_ctr_enabled,
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001712 int expected_cipher_suite) {
1713 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001714 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1715 local_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001716 caller_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1717 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001718 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001719 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1720 remote_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001721 callee_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1722 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001723 TestNegotiatedCipherSuite(caller_options, callee_options,
1724 expected_cipher_suite);
1725 }
1726
Seth Hampson2f0d7022018-02-20 11:54:42 -08001727 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001728 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001729
deadbeef1dcb1642017-03-29 21:08:16 -07001730 private:
1731 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001732 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001733 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001734 // |network_thread_| and |worker_thread_| are used by both
1735 // |caller_| and |callee_| so they must be destroyed
1736 // later.
1737 std::unique_ptr<rtc::Thread> network_thread_;
1738 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001739 // The turn servers and turn customizers should be accessed & deleted on the
1740 // network thread to avoid a race with the socket read/write that occurs
1741 // on the network thread.
1742 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1743 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001744 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001745 std::unique_ptr<PeerConnectionWrapper> caller_;
1746 std::unique_ptr<PeerConnectionWrapper> callee_;
1747};
1748
Seth Hampson2f0d7022018-02-20 11:54:42 -08001749class PeerConnectionIntegrationTest
1750 : public PeerConnectionIntegrationBaseTest,
1751 public ::testing::WithParamInterface<SdpSemantics> {
1752 protected:
1753 PeerConnectionIntegrationTest()
1754 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1755};
1756
Yves Gerey100fe632020-01-17 19:15:53 +01001757// Fake clock must be set before threads are started to prevent race on
1758// Set/GetClockForTesting().
1759// To achieve that, multiple inheritance is used as a mixin pattern
1760// where order of construction is finely controlled.
1761// This also ensures peerconnection is closed before switching back to non-fake
1762// clock, avoiding other races and DCHECK failures such as in rtp_sender.cc.
1763class FakeClockForTest : public rtc::ScopedFakeClock {
1764 protected:
1765 FakeClockForTest() {
1766 // Some things use a time of "0" as a special value, so we need to start out
1767 // the fake clock at a nonzero time.
1768 // TODO(deadbeef): Fix this.
1769 AdvanceTime(webrtc::TimeDelta::seconds(1));
1770 }
1771
1772 // Explicit handle.
1773 ScopedFakeClock& FakeClock() { return *this; }
1774};
1775
1776// Ensure FakeClockForTest is constructed first (see class for rationale).
1777class PeerConnectionIntegrationTestWithFakeClock
1778 : public FakeClockForTest,
1779 public PeerConnectionIntegrationTest {};
1780
Seth Hampson2f0d7022018-02-20 11:54:42 -08001781class PeerConnectionIntegrationTestPlanB
1782 : public PeerConnectionIntegrationBaseTest {
1783 protected:
1784 PeerConnectionIntegrationTestPlanB()
1785 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1786};
1787
1788class PeerConnectionIntegrationTestUnifiedPlan
1789 : public PeerConnectionIntegrationBaseTest {
1790 protected:
1791 PeerConnectionIntegrationTestUnifiedPlan()
1792 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1793};
1794
deadbeef1dcb1642017-03-29 21:08:16 -07001795// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1796// includes testing that the callback is invoked if an observer is connected
1797// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001798TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001799 RtpReceiverObserverOnFirstPacketReceived) {
1800 ASSERT_TRUE(CreatePeerConnectionWrappers());
1801 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001802 caller()->AddAudioVideoTracks();
1803 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001804 // Start offer/answer exchange and wait for it to complete.
1805 caller()->CreateAndSetAndSignalOffer();
1806 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1807 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001808 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1809 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001810 // Wait for all "first packet received" callbacks to be fired.
1811 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001812 absl::c_all_of(caller()->rtp_receiver_observers(),
1813 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1814 return o->first_packet_received();
1815 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001816 kMaxWaitForFramesMs);
1817 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001818 absl::c_all_of(callee()->rtp_receiver_observers(),
1819 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1820 return o->first_packet_received();
1821 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001822 kMaxWaitForFramesMs);
1823 // If new observers are set after the first packet was already received, the
1824 // callback should still be invoked.
1825 caller()->ResetRtpReceiverObservers();
1826 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001827 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1828 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001829 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001830 absl::c_all_of(caller()->rtp_receiver_observers(),
1831 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1832 return o->first_packet_received();
1833 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001834 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001835 absl::c_all_of(callee()->rtp_receiver_observers(),
1836 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1837 return o->first_packet_received();
1838 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001839}
1840
1841class DummyDtmfObserver : public DtmfSenderObserverInterface {
1842 public:
1843 DummyDtmfObserver() : completed_(false) {}
1844
1845 // Implements DtmfSenderObserverInterface.
1846 void OnToneChange(const std::string& tone) override {
1847 tones_.push_back(tone);
1848 if (tone.empty()) {
1849 completed_ = true;
1850 }
1851 }
1852
1853 const std::vector<std::string>& tones() const { return tones_; }
1854 bool completed() const { return completed_; }
1855
1856 private:
1857 bool completed_;
1858 std::vector<std::string> tones_;
1859};
1860
1861// Assumes |sender| already has an audio track added and the offer/answer
1862// exchange is done.
1863void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1864 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001865 // We should be able to get a DTMF sender from the local sender.
1866 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1867 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1868 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001869 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001870 dtmf_sender->RegisterObserver(&observer);
1871
1872 // Test the DtmfSender object just created.
1873 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1874 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1875
1876 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1877 std::vector<std::string> tones = {"1", "a", ""};
1878 EXPECT_EQ(tones, observer.tones());
1879 dtmf_sender->UnregisterObserver();
1880 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1881}
1882
1883// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1884// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001885TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001886 ASSERT_TRUE(CreatePeerConnectionWrappers());
1887 ConnectFakeSignaling();
1888 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001889 caller()->AddAudioTrack();
1890 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001891 caller()->CreateAndSetAndSignalOffer();
1892 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001893 // DTLS must finish before the DTMF sender can be used reliably.
1894 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001895 TestDtmfFromSenderToReceiver(caller(), callee());
1896 TestDtmfFromSenderToReceiver(callee(), caller());
1897}
1898
1899// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1900// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001901TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001902 ASSERT_TRUE(CreatePeerConnectionWrappers());
1903 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001904
deadbeef1dcb1642017-03-29 21:08:16 -07001905 // Do normal offer/answer and wait for some frames to be received in each
1906 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001907 caller()->AddAudioVideoTracks();
1908 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001909 caller()->CreateAndSetAndSignalOffer();
1910 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001911 MediaExpectations media_expectations;
1912 media_expectations.ExpectBidirectionalAudioAndVideo();
1913 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001914 EXPECT_METRIC_LE(
1915 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1916 webrtc::kEnumCounterKeyProtocolDtls));
1917 EXPECT_METRIC_EQ(
1918 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1919 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001920}
1921
1922// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001923TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001924 PeerConnectionInterface::RTCConfiguration sdes_config;
1925 sdes_config.enable_dtls_srtp.emplace(false);
1926 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1927 ConnectFakeSignaling();
1928
1929 // Do normal offer/answer and wait for some frames to be received in each
1930 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001931 caller()->AddAudioVideoTracks();
1932 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001933 caller()->CreateAndSetAndSignalOffer();
1934 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001935 MediaExpectations media_expectations;
1936 media_expectations.ExpectBidirectionalAudioAndVideo();
1937 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001938 EXPECT_METRIC_LE(
1939 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1940 webrtc::kEnumCounterKeyProtocolSdes));
1941 EXPECT_METRIC_EQ(
1942 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1943 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001944}
1945
Steve Anton9a44b2d2019-07-12 12:58:30 -07001946// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1947// option to offer encrypted versions of all header extensions alongside the
1948// unencrypted versions.
1949TEST_P(PeerConnectionIntegrationTest,
1950 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1951 CryptoOptions crypto_options;
1952 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1953 PeerConnectionInterface::RTCConfiguration config;
1954 config.crypto_options = crypto_options;
1955 // Note: This allows offering >14 RTP header extensions.
1956 config.offer_extmap_allow_mixed = true;
1957 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1958 ConnectFakeSignaling();
1959
1960 // Do normal offer/answer and wait for some frames to be received in each
1961 // direction.
1962 caller()->AddAudioVideoTracks();
1963 callee()->AddAudioVideoTracks();
1964 caller()->CreateAndSetAndSignalOffer();
1965 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1966 MediaExpectations media_expectations;
1967 media_expectations.ExpectBidirectionalAudioAndVideo();
1968 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1969}
1970
Steve Anton8c0f7a72017-10-03 10:03:10 -07001971// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1972// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001973TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001974 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1975 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1976 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1977 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1978 return pc->GetRemoteAudioSSLCertificate();
1979 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001980 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1981 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1982 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1983 return pc->GetRemoteAudioSSLCertChain();
1984 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001985
1986 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1987 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1988
1989 // Configure each side with a known certificate so they can be compared later.
1990 PeerConnectionInterface::RTCConfiguration caller_config;
1991 caller_config.enable_dtls_srtp.emplace(true);
1992 caller_config.certificates.push_back(caller_cert);
1993 PeerConnectionInterface::RTCConfiguration callee_config;
1994 callee_config.enable_dtls_srtp.emplace(true);
1995 callee_config.certificates.push_back(callee_cert);
1996 ASSERT_TRUE(
1997 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1998 ConnectFakeSignaling();
1999
2000 // When first initialized, there should not be a remote SSL certificate (and
2001 // calling this method should not crash).
2002 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
2003 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08002004 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
2005 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07002006
Steve Anton15324772018-01-16 10:26:49 -08002007 caller()->AddAudioTrack();
2008 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07002009 caller()->CreateAndSetAndSignalOffer();
2010 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2011 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
2012
2013 // Once DTLS has been connected, each side should return the other's SSL
2014 // certificate when calling GetRemoteAudioSSLCertificate.
2015
2016 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
2017 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002018 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07002019 caller_remote_cert->ToPEMString());
2020
2021 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
2022 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002023 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07002024 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08002025
2026 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
2027 ASSERT_TRUE(caller_remote_cert_chain);
2028 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
2029 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002030 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08002031 remote_cert->ToPEMString());
2032
2033 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
2034 ASSERT_TRUE(callee_remote_cert_chain);
2035 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
2036 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002037 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08002038 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002039}
2040
deadbeef1dcb1642017-03-29 21:08:16 -07002041// This test sets up a call between two parties with a source resolution of
2042// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002043TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002044 Send1280By720ResolutionAndReceive16To9AspectRatio) {
2045 ASSERT_TRUE(CreatePeerConnectionWrappers());
2046 ConnectFakeSignaling();
2047
Niels Möller5c7efe72018-05-11 10:34:46 +02002048 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
2049 webrtc::FakePeriodicVideoSource::Config config;
2050 config.width = 1280;
2051 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02002052 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02002053 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
2054 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07002055
2056 // Do normal offer/answer and wait for at least one frame to be received in
2057 // each direction.
2058 caller()->CreateAndSetAndSignalOffer();
2059 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2060 callee()->min_video_frames_received_per_track() > 0,
2061 kMaxWaitForFramesMs);
2062
2063 // Check rendered aspect ratio.
2064 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
2065 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
2066 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
2067 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
2068}
2069
2070// This test sets up an one-way call, with media only from caller to
2071// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002072TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07002073 ASSERT_TRUE(CreatePeerConnectionWrappers());
2074 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002075 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002076 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002077 MediaExpectations media_expectations;
2078 media_expectations.CalleeExpectsSomeAudioAndVideo();
2079 media_expectations.CallerExpectsNoAudio();
2080 media_expectations.CallerExpectsNoVideo();
2081 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002082}
2083
Johannes Kron184ea662020-01-29 12:43:36 +01002084// Tests that send only works without the caller having a decoder factory and
2085// the callee having an encoder factory.
2086TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSendOnlyVideo) {
2087 ASSERT_TRUE(
2088 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/true));
2089 ConnectFakeSignaling();
2090 // Add one-directional video, from caller to callee.
2091 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2092 caller()->CreateLocalVideoTrack();
2093 caller()->AddTrack(caller_track);
2094 PeerConnectionInterface::RTCOfferAnswerOptions options;
2095 options.offer_to_receive_video = 0;
2096 caller()->SetOfferAnswerOptions(options);
2097 caller()->CreateAndSetAndSignalOffer();
2098 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2099 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
2100
2101 // Expect video to be received in one direction.
2102 MediaExpectations media_expectations;
2103 media_expectations.CallerExpectsNoVideo();
2104 media_expectations.CalleeExpectsSomeVideo();
2105
2106 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2107}
2108
2109// Tests that receive only works without the caller having an encoder factory
2110// and the callee having a decoder factory.
2111TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithReceiveOnlyVideo) {
2112 ASSERT_TRUE(
2113 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/false));
2114 ConnectFakeSignaling();
2115 // Add one-directional video, from callee to caller.
2116 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2117 callee()->CreateLocalVideoTrack();
2118 callee()->AddTrack(callee_track);
2119 PeerConnectionInterface::RTCOfferAnswerOptions options;
2120 options.offer_to_receive_video = 1;
2121 caller()->SetOfferAnswerOptions(options);
2122 caller()->CreateAndSetAndSignalOffer();
2123 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2124 ASSERT_EQ(caller()->pc()->GetReceivers().size(), 1u);
2125
2126 // Expect video to be received in one direction.
2127 MediaExpectations media_expectations;
2128 media_expectations.CallerExpectsSomeVideo();
2129 media_expectations.CalleeExpectsNoVideo();
2130
2131 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2132}
2133
2134TEST_P(PeerConnectionIntegrationTest,
2135 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2136 ASSERT_TRUE(CreatePeerConnectionWrappers());
2137 ConnectFakeSignaling();
2138 // Add one-directional video, from caller to callee.
2139 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2140 caller()->CreateLocalVideoTrack();
2141 caller()->AddTrack(caller_track);
2142 caller()->CreateAndSetAndSignalOffer();
2143 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2144
2145 // Add receive video.
2146 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2147 callee()->CreateLocalVideoTrack();
2148 callee()->AddTrack(callee_track);
2149 caller()->CreateAndSetAndSignalOffer();
2150 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2151
2152 // Ensure that video frames are received end-to-end.
2153 MediaExpectations media_expectations;
2154 media_expectations.ExpectBidirectionalVideo();
2155 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2156}
2157
2158TEST_P(PeerConnectionIntegrationTest,
2159 EndToEndCallAddSendVideoToReceiveOnlyCall) {
2160 ASSERT_TRUE(CreatePeerConnectionWrappers());
2161 ConnectFakeSignaling();
2162 // Add one-directional video, from callee to caller.
2163 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2164 callee()->CreateLocalVideoTrack();
2165 callee()->AddTrack(callee_track);
2166 caller()->CreateAndSetAndSignalOffer();
2167 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2168
2169 // Add send video.
2170 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2171 caller()->CreateLocalVideoTrack();
2172 caller()->AddTrack(caller_track);
2173 caller()->CreateAndSetAndSignalOffer();
2174 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2175
2176 // Expect video to be received in one direction.
2177 MediaExpectations media_expectations;
2178 media_expectations.ExpectBidirectionalVideo();
2179 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2180}
2181
2182TEST_P(PeerConnectionIntegrationTest,
2183 EndToEndCallRemoveReceiveVideoFromSendReceiveCall) {
2184 ASSERT_TRUE(CreatePeerConnectionWrappers());
2185 ConnectFakeSignaling();
2186 // Add send video, from caller to callee.
2187 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2188 caller()->CreateLocalVideoTrack();
2189 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2190 caller()->AddTrack(caller_track);
2191 // Add receive video, from callee to caller.
2192 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2193 callee()->CreateLocalVideoTrack();
2194
2195 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2196 callee()->AddTrack(callee_track);
2197 caller()->CreateAndSetAndSignalOffer();
2198 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2199
2200 // Remove receive video (i.e., callee sender track).
2201 callee()->pc()->RemoveTrack(callee_sender);
2202
2203 caller()->CreateAndSetAndSignalOffer();
2204 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2205
2206 // Expect one-directional video.
2207 MediaExpectations media_expectations;
2208 media_expectations.CallerExpectsNoVideo();
2209 media_expectations.CalleeExpectsSomeVideo();
2210
2211 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2212}
2213
2214TEST_P(PeerConnectionIntegrationTest,
2215 EndToEndCallRemoveSendVideoFromSendReceiveCall) {
2216 ASSERT_TRUE(CreatePeerConnectionWrappers());
2217 ConnectFakeSignaling();
2218 // Add send video, from caller to callee.
2219 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2220 caller()->CreateLocalVideoTrack();
2221 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2222 caller()->AddTrack(caller_track);
2223 // Add receive video, from callee to caller.
2224 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2225 callee()->CreateLocalVideoTrack();
2226
2227 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2228 callee()->AddTrack(callee_track);
2229 caller()->CreateAndSetAndSignalOffer();
2230 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2231
2232 // Remove send video (i.e., caller sender track).
2233 caller()->pc()->RemoveTrack(caller_sender);
2234
2235 caller()->CreateAndSetAndSignalOffer();
2236 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2237
2238 // Expect one-directional video.
2239 MediaExpectations media_expectations;
2240 media_expectations.CalleeExpectsNoVideo();
2241 media_expectations.CallerExpectsSomeVideo();
2242
2243 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2244}
2245
deadbeef1dcb1642017-03-29 21:08:16 -07002246// This test sets up a audio call initially, with the callee rejecting video
2247// initially. Then later the callee decides to upgrade to audio/video, and
2248// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002249TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07002250 ASSERT_TRUE(CreatePeerConnectionWrappers());
2251 ConnectFakeSignaling();
2252 // Initially, offer an audio/video stream from the caller, but refuse to
2253 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08002254 caller()->AddAudioVideoTracks();
2255 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002256 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2257 PeerConnectionInterface::RTCOfferAnswerOptions options;
2258 options.offer_to_receive_video = 0;
2259 callee()->SetOfferAnswerOptions(options);
2260 } else {
2261 callee()->SetRemoteOfferHandler([this] {
2262 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2263 });
2264 }
deadbeef1dcb1642017-03-29 21:08:16 -07002265 // Do offer/answer and make sure audio is still received end-to-end.
2266 caller()->CreateAndSetAndSignalOffer();
2267 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002268 {
2269 MediaExpectations media_expectations;
2270 media_expectations.ExpectBidirectionalAudio();
2271 media_expectations.ExpectNoVideo();
2272 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2273 }
deadbeef1dcb1642017-03-29 21:08:16 -07002274 // Sanity check that the callee's description has a rejected video section.
2275 ASSERT_NE(nullptr, callee()->pc()->local_description());
2276 const ContentInfo* callee_video_content =
2277 GetFirstVideoContent(callee()->pc()->local_description()->description());
2278 ASSERT_NE(nullptr, callee_video_content);
2279 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002280
deadbeef1dcb1642017-03-29 21:08:16 -07002281 // Now negotiate with video and ensure negotiation succeeds, with video
2282 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002283 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002284 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2285 PeerConnectionInterface::RTCOfferAnswerOptions options;
2286 options.offer_to_receive_video = 1;
2287 callee()->SetOfferAnswerOptions(options);
2288 } else {
2289 callee()->SetRemoteOfferHandler(nullptr);
2290 caller()->SetRemoteOfferHandler([this] {
2291 // The caller creates a new transceiver to receive video on when receiving
2292 // the offer, but by default it is send only.
2293 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002294 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002295 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
2296 transceivers[2]->receiver()->media_type());
2297 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2298 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
2299 });
2300 }
deadbeef1dcb1642017-03-29 21:08:16 -07002301 callee()->CreateAndSetAndSignalOffer();
2302 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002303 {
2304 // Expect additional audio frames to be received after the upgrade.
2305 MediaExpectations media_expectations;
2306 media_expectations.ExpectBidirectionalAudioAndVideo();
2307 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2308 }
deadbeef1dcb1642017-03-29 21:08:16 -07002309}
2310
deadbeef4389b4d2017-09-07 09:07:36 -07002311// Simpler than the above test; just add an audio track to an established
2312// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002313TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002314 ASSERT_TRUE(CreatePeerConnectionWrappers());
2315 ConnectFakeSignaling();
2316 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002317 caller()->AddVideoTrack();
2318 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002319 caller()->CreateAndSetAndSignalOffer();
2320 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2321 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002322 caller()->AddAudioTrack();
2323 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002324 caller()->CreateAndSetAndSignalOffer();
2325 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2326 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002327 MediaExpectations media_expectations;
2328 media_expectations.ExpectBidirectionalAudioAndVideo();
2329 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002330}
2331
deadbeef1dcb1642017-03-29 21:08:16 -07002332// This test sets up a call that's transferred to a new caller with a different
2333// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002334TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002335 ASSERT_TRUE(CreatePeerConnectionWrappers());
2336 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002337 caller()->AddAudioVideoTracks();
2338 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002339 caller()->CreateAndSetAndSignalOffer();
2340 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2341
2342 // Keep the original peer around which will still send packets to the
2343 // receiving client. These SRTP packets will be dropped.
2344 std::unique_ptr<PeerConnectionWrapper> original_peer(
2345 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002346 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002347 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2348 // directly above.
2349 original_peer->pc()->Close();
2350
2351 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002352 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002353 caller()->CreateAndSetAndSignalOffer();
2354 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2355 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002356 MediaExpectations media_expectations;
2357 media_expectations.ExpectBidirectionalAudioAndVideo();
2358 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002359}
2360
2361// This test sets up a call that's transferred to a new callee with a different
2362// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002363TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002364 ASSERT_TRUE(CreatePeerConnectionWrappers());
2365 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002366 caller()->AddAudioVideoTracks();
2367 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002368 caller()->CreateAndSetAndSignalOffer();
2369 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2370
2371 // Keep the original peer around which will still send packets to the
2372 // receiving client. These SRTP packets will be dropped.
2373 std::unique_ptr<PeerConnectionWrapper> original_peer(
2374 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002375 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002376 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2377 // directly above.
2378 original_peer->pc()->Close();
2379
2380 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002381 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002382 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2383 caller()->CreateAndSetAndSignalOffer();
2384 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2385 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002386 MediaExpectations media_expectations;
2387 media_expectations.ExpectBidirectionalAudioAndVideo();
2388 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002389}
2390
2391// This test sets up a non-bundled call and negotiates bundling at the same
2392// time as starting an ICE restart. When bundling is in effect in the restart,
2393// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002394TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002395 ASSERT_TRUE(CreatePeerConnectionWrappers());
2396 ConnectFakeSignaling();
2397
Steve Anton15324772018-01-16 10:26:49 -08002398 caller()->AddAudioVideoTracks();
2399 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002400 // Remove the bundle group from the SDP received by the callee.
2401 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2402 desc->RemoveGroupByName("BUNDLE");
2403 });
2404 caller()->CreateAndSetAndSignalOffer();
2405 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002406 {
2407 MediaExpectations media_expectations;
2408 media_expectations.ExpectBidirectionalAudioAndVideo();
2409 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2410 }
deadbeef1dcb1642017-03-29 21:08:16 -07002411 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2412 callee()->SetReceivedSdpMunger(nullptr);
2413 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2414 caller()->CreateAndSetAndSignalOffer();
2415 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2416
2417 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002418 {
2419 MediaExpectations media_expectations;
2420 media_expectations.ExpectBidirectionalAudioAndVideo();
2421 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2422 }
deadbeef1dcb1642017-03-29 21:08:16 -07002423}
2424
2425// Test CVO (Coordination of Video Orientation). If a video source is rotated
2426// and both peers support the CVO RTP header extension, the actual video frames
2427// don't need to be encoded in different resolutions, since the rotation is
2428// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002429TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002430 ASSERT_TRUE(CreatePeerConnectionWrappers());
2431 ConnectFakeSignaling();
2432 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002433 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002434 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002435 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002436 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2437
2438 // Wait for video frames to be received by both sides.
2439 caller()->CreateAndSetAndSignalOffer();
2440 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2441 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2442 callee()->min_video_frames_received_per_track() > 0,
2443 kMaxWaitForFramesMs);
2444
2445 // Ensure that the aspect ratio is unmodified.
2446 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2447 // not just assumed.
2448 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2449 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2450 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2451 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2452 // Ensure that the CVO bits were surfaced to the renderer.
2453 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2454 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2455}
2456
2457// Test that when the CVO extension isn't supported, video is rotated the
2458// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002459TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002460 ASSERT_TRUE(CreatePeerConnectionWrappers());
2461 ConnectFakeSignaling();
2462 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002463 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002464 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002465 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002466 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2467
2468 // Remove the CVO extension from the offered SDP.
2469 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2470 cricket::VideoContentDescription* video =
2471 GetFirstVideoContentDescription(desc);
2472 video->ClearRtpHeaderExtensions();
2473 });
2474 // Wait for video frames to be received by both sides.
2475 caller()->CreateAndSetAndSignalOffer();
2476 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2477 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2478 callee()->min_video_frames_received_per_track() > 0,
2479 kMaxWaitForFramesMs);
2480
2481 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2482 // rotation.
2483 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2484 // not just assumed.
2485 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2486 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2487 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2488 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2489 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2490 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2491 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2492}
2493
deadbeef1dcb1642017-03-29 21:08:16 -07002494// Test that if the answerer rejects the audio m= section, no audio is sent or
2495// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002496TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002497 ASSERT_TRUE(CreatePeerConnectionWrappers());
2498 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002499 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002500 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2501 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2502 // it will reject the audio m= section completely.
2503 PeerConnectionInterface::RTCOfferAnswerOptions options;
2504 options.offer_to_receive_audio = 0;
2505 callee()->SetOfferAnswerOptions(options);
2506 } else {
2507 // Stopping the audio RtpTransceiver will cause the media section to be
2508 // rejected in the answer.
2509 callee()->SetRemoteOfferHandler([this] {
2510 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2511 });
2512 }
Steve Anton15324772018-01-16 10:26:49 -08002513 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002514 // Do offer/answer and wait for successful end-to-end video frames.
2515 caller()->CreateAndSetAndSignalOffer();
2516 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002517 MediaExpectations media_expectations;
2518 media_expectations.ExpectBidirectionalVideo();
2519 media_expectations.ExpectNoAudio();
2520 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2521
deadbeef1dcb1642017-03-29 21:08:16 -07002522 // Sanity check that the callee's description has a rejected audio section.
2523 ASSERT_NE(nullptr, callee()->pc()->local_description());
2524 const ContentInfo* callee_audio_content =
2525 GetFirstAudioContent(callee()->pc()->local_description()->description());
2526 ASSERT_NE(nullptr, callee_audio_content);
2527 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002528 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2529 // The caller's transceiver should have stopped after receiving the answer.
2530 EXPECT_TRUE(caller()
2531 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2532 ->stopped());
2533 }
deadbeef1dcb1642017-03-29 21:08:16 -07002534}
2535
2536// Test that if the answerer rejects the video m= section, no video is sent or
2537// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002538TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002539 ASSERT_TRUE(CreatePeerConnectionWrappers());
2540 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002541 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002542 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2543 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2544 // it will reject the video m= section completely.
2545 PeerConnectionInterface::RTCOfferAnswerOptions options;
2546 options.offer_to_receive_video = 0;
2547 callee()->SetOfferAnswerOptions(options);
2548 } else {
2549 // Stopping the video RtpTransceiver will cause the media section to be
2550 // rejected in the answer.
2551 callee()->SetRemoteOfferHandler([this] {
2552 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2553 });
2554 }
Steve Anton15324772018-01-16 10:26:49 -08002555 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002556 // Do offer/answer and wait for successful end-to-end audio frames.
2557 caller()->CreateAndSetAndSignalOffer();
2558 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002559 MediaExpectations media_expectations;
2560 media_expectations.ExpectBidirectionalAudio();
2561 media_expectations.ExpectNoVideo();
2562 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2563
deadbeef1dcb1642017-03-29 21:08:16 -07002564 // Sanity check that the callee's description has a rejected video section.
2565 ASSERT_NE(nullptr, callee()->pc()->local_description());
2566 const ContentInfo* callee_video_content =
2567 GetFirstVideoContent(callee()->pc()->local_description()->description());
2568 ASSERT_NE(nullptr, callee_video_content);
2569 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002570 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2571 // The caller's transceiver should have stopped after receiving the answer.
2572 EXPECT_TRUE(caller()
2573 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2574 ->stopped());
2575 }
deadbeef1dcb1642017-03-29 21:08:16 -07002576}
2577
2578// Test that if the answerer rejects both audio and video m= sections, nothing
2579// bad happens.
2580// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2581// test anything but the fact that negotiation succeeds, which doesn't mean
2582// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002583TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002584 ASSERT_TRUE(CreatePeerConnectionWrappers());
2585 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002586 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002587 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2588 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2589 // will reject both audio and video m= sections.
2590 PeerConnectionInterface::RTCOfferAnswerOptions options;
2591 options.offer_to_receive_audio = 0;
2592 options.offer_to_receive_video = 0;
2593 callee()->SetOfferAnswerOptions(options);
2594 } else {
2595 callee()->SetRemoteOfferHandler([this] {
2596 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002597 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002598 transceiver->Stop();
2599 }
2600 });
2601 }
deadbeef1dcb1642017-03-29 21:08:16 -07002602 // Do offer/answer and wait for stable signaling state.
2603 caller()->CreateAndSetAndSignalOffer();
2604 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002605
deadbeef1dcb1642017-03-29 21:08:16 -07002606 // Sanity check that the callee's description has rejected m= sections.
2607 ASSERT_NE(nullptr, callee()->pc()->local_description());
2608 const ContentInfo* callee_audio_content =
2609 GetFirstAudioContent(callee()->pc()->local_description()->description());
2610 ASSERT_NE(nullptr, callee_audio_content);
2611 EXPECT_TRUE(callee_audio_content->rejected);
2612 const ContentInfo* callee_video_content =
2613 GetFirstVideoContent(callee()->pc()->local_description()->description());
2614 ASSERT_NE(nullptr, callee_video_content);
2615 EXPECT_TRUE(callee_video_content->rejected);
2616}
2617
2618// This test sets up an audio and video call between two parties. After the
2619// call runs for a while, the caller sends an updated offer with video being
2620// rejected. Once the re-negotiation is done, the video flow should stop and
2621// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002622TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002623 ASSERT_TRUE(CreatePeerConnectionWrappers());
2624 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002625 caller()->AddAudioVideoTracks();
2626 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002627 caller()->CreateAndSetAndSignalOffer();
2628 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002629 {
2630 MediaExpectations media_expectations;
2631 media_expectations.ExpectBidirectionalAudioAndVideo();
2632 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2633 }
deadbeef1dcb1642017-03-29 21:08:16 -07002634 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002635 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2636 caller()->SetGeneratedSdpMunger(
2637 [](cricket::SessionDescription* description) {
2638 for (cricket::ContentInfo& content : description->contents()) {
2639 if (cricket::IsVideoContent(&content)) {
2640 content.rejected = true;
2641 }
2642 }
2643 });
2644 } else {
2645 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2646 }
deadbeef1dcb1642017-03-29 21:08:16 -07002647 caller()->CreateAndSetAndSignalOffer();
2648 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2649
2650 // Sanity check that the caller's description has a rejected video section.
2651 ASSERT_NE(nullptr, caller()->pc()->local_description());
2652 const ContentInfo* caller_video_content =
2653 GetFirstVideoContent(caller()->pc()->local_description()->description());
2654 ASSERT_NE(nullptr, caller_video_content);
2655 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002656 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002657 {
2658 MediaExpectations media_expectations;
2659 media_expectations.ExpectBidirectionalAudio();
2660 media_expectations.ExpectNoVideo();
2661 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2662 }
deadbeef1dcb1642017-03-29 21:08:16 -07002663}
2664
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002665// Do one offer/answer with audio, another that disables it (rejecting the m=
2666// section), and another that re-enables it. Regression test for:
2667// bugs.webrtc.org/6023
2668TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2669 ASSERT_TRUE(CreatePeerConnectionWrappers());
2670 ConnectFakeSignaling();
2671
2672 // Add audio track, do normal offer/answer.
2673 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2674 caller()->CreateLocalAudioTrack();
2675 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2676 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2677 caller()->CreateAndSetAndSignalOffer();
2678 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2679
2680 // Remove audio track, and set offer_to_receive_audio to false to cause the
2681 // m= section to be completely disabled, not just "recvonly".
2682 caller()->pc()->RemoveTrack(sender);
2683 PeerConnectionInterface::RTCOfferAnswerOptions options;
2684 options.offer_to_receive_audio = 0;
2685 caller()->SetOfferAnswerOptions(options);
2686 caller()->CreateAndSetAndSignalOffer();
2687 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2688
2689 // Add the audio track again, expecting negotiation to succeed and frames to
2690 // flow.
2691 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2692 options.offer_to_receive_audio = 1;
2693 caller()->SetOfferAnswerOptions(options);
2694 caller()->CreateAndSetAndSignalOffer();
2695 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2696
2697 MediaExpectations media_expectations;
2698 media_expectations.CalleeExpectsSomeAudio();
2699 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2700}
2701
deadbeef1dcb1642017-03-29 21:08:16 -07002702// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2703// is needed to support legacy endpoints.
2704// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2705// add a test for an end-to-end test without MID signaling either (basically,
2706// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002707TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002708 ASSERT_TRUE(CreatePeerConnectionWrappers());
2709 ConnectFakeSignaling();
2710 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002711 caller()->AddAudioVideoTracks();
2712 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002713 // Remove SSRCs and MSIDs from the received offer SDP.
2714 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002715 caller()->CreateAndSetAndSignalOffer();
2716 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002717 MediaExpectations media_expectations;
2718 media_expectations.ExpectBidirectionalAudioAndVideo();
2719 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002720}
2721
Seth Hampson5897a6e2018-04-03 11:16:33 -07002722// Basic end-to-end test, without SSRC signaling. This means that the track
2723// was created properly and frames are delivered when the MSIDs are communicated
2724// with a=msid lines and no a=ssrc lines.
2725TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2726 EndToEndCallWithoutSsrcSignaling) {
2727 const char kStreamId[] = "streamId";
2728 ASSERT_TRUE(CreatePeerConnectionWrappers());
2729 ConnectFakeSignaling();
2730 // Add just audio tracks.
2731 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2732 callee()->AddAudioTrack();
2733
2734 // Remove SSRCs from the received offer SDP.
2735 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2736 caller()->CreateAndSetAndSignalOffer();
2737 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2738 MediaExpectations media_expectations;
2739 media_expectations.ExpectBidirectionalAudio();
2740 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2741}
2742
Johannes Kron184ea662020-01-29 12:43:36 +01002743TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2744 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2745 ASSERT_TRUE(CreatePeerConnectionWrappers());
2746 ConnectFakeSignaling();
2747 // Add one-directional video, from caller to callee.
2748 rtc::scoped_refptr<webrtc::VideoTrackInterface> track =
2749 caller()->CreateLocalVideoTrack();
2750
2751 RtpTransceiverInit video_transceiver_init;
2752 video_transceiver_init.stream_ids = {"video1"};
2753 video_transceiver_init.direction = RtpTransceiverDirection::kSendOnly;
2754 auto video_sender =
2755 caller()->pc()->AddTransceiver(track, video_transceiver_init).MoveValue();
2756 caller()->CreateAndSetAndSignalOffer();
2757 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2758
2759 // Add receive direction.
2760 video_sender->SetDirection(RtpTransceiverDirection::kSendRecv);
2761
2762 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2763 callee()->CreateLocalVideoTrack();
2764
2765 callee()->AddTrack(callee_track);
2766 caller()->CreateAndSetAndSignalOffer();
2767 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2768 // Ensure that video frames are received end-to-end.
2769 MediaExpectations media_expectations;
2770 media_expectations.ExpectBidirectionalVideo();
2771 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2772}
2773
Steve Antondf527fd2018-04-27 15:52:03 -07002774// Tests that video flows between multiple video tracks when SSRCs are not
2775// signaled. This exercises the MID RTP header extension which is needed to
2776// demux the incoming video tracks.
2777TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2778 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2779 ASSERT_TRUE(CreatePeerConnectionWrappers());
2780 ConnectFakeSignaling();
2781 caller()->AddVideoTrack();
2782 caller()->AddVideoTrack();
2783 callee()->AddVideoTrack();
2784 callee()->AddVideoTrack();
2785
2786 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2787 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2788 caller()->CreateAndSetAndSignalOffer();
2789 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2790 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2791 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2792
2793 // Expect video to be received in both directions on both tracks.
2794 MediaExpectations media_expectations;
2795 media_expectations.ExpectBidirectionalVideo();
2796 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2797}
2798
Henrik Boström5b147782018-12-04 11:25:05 +01002799TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2800 ASSERT_TRUE(CreatePeerConnectionWrappers());
2801 ConnectFakeSignaling();
2802 caller()->AddAudioTrack();
2803 caller()->AddVideoTrack();
2804 caller()->CreateAndSetAndSignalOffer();
2805 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2806 auto callee_receivers = callee()->pc()->GetReceivers();
2807 ASSERT_EQ(2u, callee_receivers.size());
2808 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2809 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2810}
2811
2812TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2813 ASSERT_TRUE(CreatePeerConnectionWrappers());
2814 ConnectFakeSignaling();
2815 caller()->AddAudioTrack();
2816 caller()->AddVideoTrack();
2817 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2818 caller()->CreateAndSetAndSignalOffer();
2819 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2820 auto callee_receivers = callee()->pc()->GetReceivers();
2821 ASSERT_EQ(2u, callee_receivers.size());
2822 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2823 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2824 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2825 callee_receivers[1]->stream_ids()[0]);
2826 EXPECT_EQ(callee_receivers[0]->streams()[0],
2827 callee_receivers[1]->streams()[0]);
2828}
2829
deadbeef1dcb1642017-03-29 21:08:16 -07002830// Test that if two video tracks are sent (from caller to callee, in this test),
2831// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002832TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002833 ASSERT_TRUE(CreatePeerConnectionWrappers());
2834 ConnectFakeSignaling();
2835 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002836 caller()->AddAudioVideoTracks();
2837 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002838 caller()->CreateAndSetAndSignalOffer();
2839 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002840 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002841
2842 MediaExpectations media_expectations;
2843 media_expectations.CalleeExpectsSomeAudioAndVideo();
2844 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002845}
2846
2847static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2848 bool first = true;
2849 for (cricket::ContentInfo& content : desc->contents()) {
2850 if (first) {
2851 first = false;
2852 continue;
2853 }
2854 content.bundle_only = true;
2855 }
2856 first = true;
2857 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2858 if (first) {
2859 first = false;
2860 continue;
2861 }
2862 transport.description.ice_ufrag.clear();
2863 transport.description.ice_pwd.clear();
2864 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2865 transport.description.identity_fingerprint.reset(nullptr);
2866 }
2867}
2868
2869// Test that if applying a true "max bundle" offer, which uses ports of 0,
2870// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2871// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2872// successfully and media flows.
2873// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2874// TODO(deadbeef): Won't need this test once we start generating actual
2875// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002876TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002877 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2878 ASSERT_TRUE(CreatePeerConnectionWrappers());
2879 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002880 caller()->AddAudioVideoTracks();
2881 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002882 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2883 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2884 // but the first m= section.
2885 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2886 caller()->CreateAndSetAndSignalOffer();
2887 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002888 MediaExpectations media_expectations;
2889 media_expectations.ExpectBidirectionalAudioAndVideo();
2890 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002891}
2892
2893// Test that we can receive the audio output level from a remote audio track.
2894// TODO(deadbeef): Use a fake audio source and verify that the output level is
2895// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002896TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002897 ASSERT_TRUE(CreatePeerConnectionWrappers());
2898 ConnectFakeSignaling();
2899 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002900 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002901 caller()->CreateAndSetAndSignalOffer();
2902 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2903
2904 // Get the audio output level stats. Note that the level is not available
2905 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002906 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002907 kMaxWaitForFramesMs);
2908}
2909
2910// Test that an audio input level is reported.
2911// TODO(deadbeef): Use a fake audio source and verify that the input level is
2912// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002913TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002914 ASSERT_TRUE(CreatePeerConnectionWrappers());
2915 ConnectFakeSignaling();
2916 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002917 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002918 caller()->CreateAndSetAndSignalOffer();
2919 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2920
2921 // Get the audio input level stats. The level should be available very
2922 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002923 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002924 kMaxWaitForStatsMs);
2925}
2926
2927// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002928TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002929 ASSERT_TRUE(CreatePeerConnectionWrappers());
2930 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002931 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002932 // Do offer/answer, wait for the callee to receive some frames.
2933 caller()->CreateAndSetAndSignalOffer();
2934 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002935
2936 MediaExpectations media_expectations;
2937 media_expectations.CalleeExpectsSomeAudioAndVideo();
2938 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002939
2940 // Get a handle to the remote tracks created, so they can be used as GetStats
2941 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002942 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002943 // We received frames, so we definitely should have nonzero "received bytes"
2944 // stats at this point.
2945 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2946 0);
2947 }
deadbeef1dcb1642017-03-29 21:08:16 -07002948}
2949
2950// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002951TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002952 ASSERT_TRUE(CreatePeerConnectionWrappers());
2953 ConnectFakeSignaling();
2954 auto audio_track = caller()->CreateLocalAudioTrack();
2955 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002956 caller()->AddTrack(audio_track);
2957 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002958 // Do offer/answer, wait for the callee to receive some frames.
2959 caller()->CreateAndSetAndSignalOffer();
2960 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002961 MediaExpectations media_expectations;
2962 media_expectations.CalleeExpectsSomeAudioAndVideo();
2963 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002964
2965 // The callee received frames, so we definitely should have nonzero "sent
2966 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002967 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2968 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2969}
2970
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002971// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002972TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002973 ASSERT_TRUE(CreatePeerConnectionWrappers());
2974 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002975 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002976
Steve Anton15324772018-01-16 10:26:49 -08002977 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002978
2979 // Do offer/answer, wait for the callee to receive some frames.
2980 caller()->CreateAndSetAndSignalOffer();
2981 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2982
2983 // Get the remote audio track created on the receiver, so they can be used as
2984 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002985 auto receivers = callee()->pc()->GetReceivers();
2986 ASSERT_EQ(1u, receivers.size());
2987 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002988
2989 // Get the audio output level stats. Note that the level is not available
2990 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002991 EXPECT_TRUE_WAIT(
2992 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2993 0,
2994 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002995}
2996
Steve Antona41959e2018-11-28 11:15:33 -08002997// Test that the track ID is associated with all local and remote SSRC stats
2998// using the old GetStats() and more than 1 audio and more than 1 video track.
2999// This is a regression test for crbug.com/906988
3000TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
3001 OldGetStatsAssociatesTrackIdForManyMediaSections) {
3002 ASSERT_TRUE(CreatePeerConnectionWrappers());
3003 ConnectFakeSignaling();
3004 auto audio_sender_1 = caller()->AddAudioTrack();
3005 auto video_sender_1 = caller()->AddVideoTrack();
3006 auto audio_sender_2 = caller()->AddAudioTrack();
3007 auto video_sender_2 = caller()->AddVideoTrack();
3008 caller()->CreateAndSetAndSignalOffer();
3009 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3010
3011 MediaExpectations media_expectations;
3012 media_expectations.CalleeExpectsSomeAudioAndVideo();
3013 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3014
3015 std::vector<std::string> track_ids = {
3016 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3017 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3018
3019 auto caller_stats = caller()->OldGetStats();
3020 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3021 auto callee_stats = callee()->OldGetStats();
3022 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3023}
3024
Steve Antonffa6ce42018-11-30 09:26:08 -08003025// Test that the new GetStats() returns stats for all outgoing/incoming streams
3026// with the correct track IDs if there are more than one audio and more than one
3027// video senders/receivers.
3028TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
3029 ASSERT_TRUE(CreatePeerConnectionWrappers());
3030 ConnectFakeSignaling();
3031 auto audio_sender_1 = caller()->AddAudioTrack();
3032 auto video_sender_1 = caller()->AddVideoTrack();
3033 auto audio_sender_2 = caller()->AddAudioTrack();
3034 auto video_sender_2 = caller()->AddVideoTrack();
3035 caller()->CreateAndSetAndSignalOffer();
3036 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3037
3038 MediaExpectations media_expectations;
3039 media_expectations.CalleeExpectsSomeAudioAndVideo();
3040 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3041
3042 std::vector<std::string> track_ids = {
3043 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3044 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3045
3046 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
3047 caller()->NewGetStats();
3048 ASSERT_TRUE(caller_report);
3049 auto outbound_stream_stats =
3050 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
3051 ASSERT_EQ(4u, outbound_stream_stats.size());
3052 std::vector<std::string> outbound_track_ids;
3053 for (const auto& stat : outbound_stream_stats) {
3054 ASSERT_TRUE(stat->bytes_sent.is_defined());
3055 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02003056 if (*stat->kind == "video") {
3057 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
3058 EXPECT_GT(*stat->key_frames_encoded, 0u);
3059 ASSERT_TRUE(stat->frames_encoded.is_defined());
3060 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
3061 }
Steve Antonffa6ce42018-11-30 09:26:08 -08003062 ASSERT_TRUE(stat->track_id.is_defined());
3063 const auto* track_stat =
3064 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3065 ASSERT_TRUE(track_stat);
3066 outbound_track_ids.push_back(*track_stat->track_identifier);
3067 }
3068 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
3069
3070 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
3071 callee()->NewGetStats();
3072 ASSERT_TRUE(callee_report);
3073 auto inbound_stream_stats =
3074 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3075 ASSERT_EQ(4u, inbound_stream_stats.size());
3076 std::vector<std::string> inbound_track_ids;
3077 for (const auto& stat : inbound_stream_stats) {
3078 ASSERT_TRUE(stat->bytes_received.is_defined());
3079 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02003080 if (*stat->kind == "video") {
3081 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
3082 EXPECT_GT(*stat->key_frames_decoded, 0u);
3083 ASSERT_TRUE(stat->frames_decoded.is_defined());
3084 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
3085 }
Steve Antonffa6ce42018-11-30 09:26:08 -08003086 ASSERT_TRUE(stat->track_id.is_defined());
3087 const auto* track_stat =
3088 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3089 ASSERT_TRUE(track_stat);
3090 inbound_track_ids.push_back(*track_stat->track_identifier);
3091 }
3092 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
3093}
3094
3095// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07003096// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
3097// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003098TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07003099 GetStatsForUnsignaledStreamWithNewStatsApi) {
3100 ASSERT_TRUE(CreatePeerConnectionWrappers());
3101 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003102 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07003103 // Remove SSRCs and MSIDs from the received offer SDP.
3104 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3105 caller()->CreateAndSetAndSignalOffer();
3106 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003107 MediaExpectations media_expectations;
3108 media_expectations.CalleeExpectsSomeAudio(1);
3109 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07003110
3111 // We received a frame, so we should have nonzero "bytes received" stats for
3112 // the unsignaled stream, if stats are working for it.
3113 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3114 callee()->NewGetStats();
3115 ASSERT_NE(nullptr, report);
3116 auto inbound_stream_stats =
3117 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3118 ASSERT_EQ(1U, inbound_stream_stats.size());
3119 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
3120 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07003121 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
3122}
3123
Taylor Brandstettera4653442018-06-19 09:44:26 -07003124// Same as above but for the legacy stats implementation.
3125TEST_P(PeerConnectionIntegrationTest,
3126 GetStatsForUnsignaledStreamWithOldStatsApi) {
3127 ASSERT_TRUE(CreatePeerConnectionWrappers());
3128 ConnectFakeSignaling();
3129 caller()->AddAudioTrack();
3130 // Remove SSRCs and MSIDs from the received offer SDP.
3131 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3132 caller()->CreateAndSetAndSignalOffer();
3133 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3134
3135 // Note that, since the old stats implementation associates SSRCs with tracks
3136 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
3137 // associated track ID. So we can't use the track "selector" argument.
3138 //
3139 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
3140 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003141 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07003142 kDefaultTimeout);
3143}
3144
zhihuangf8164932017-05-19 13:09:47 -07003145// Test that we can successfully get the media related stats (audio level
3146// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003147TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07003148 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
3149 ASSERT_TRUE(CreatePeerConnectionWrappers());
3150 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003151 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07003152 // Remove SSRCs and MSIDs from the received offer SDP.
3153 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3154 caller()->CreateAndSetAndSignalOffer();
3155 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003156 MediaExpectations media_expectations;
3157 media_expectations.CalleeExpectsSomeAudio(1);
3158 media_expectations.CalleeExpectsSomeVideo(1);
3159 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07003160
3161 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3162 callee()->NewGetStats();
3163 ASSERT_NE(nullptr, report);
3164
3165 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3166 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
3167 ASSERT_GE(audio_index, 0);
3168 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07003169}
3170
deadbeef4e2deab2017-09-20 13:56:21 -07003171// Helper for test below.
3172void ModifySsrcs(cricket::SessionDescription* desc) {
3173 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07003174 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08003175 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07003176 for (uint32_t& ssrc : stream.ssrcs) {
3177 ssrc = rtc::CreateRandomId();
3178 }
3179 }
3180 }
3181}
3182
3183// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
3184// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
3185// This should result in two "RTCInboundRTPStreamStats", but only one
3186// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
3187// being reset to 0 once the SSRC change occurs.
3188//
3189// Regression test for this bug:
3190// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
3191//
3192// The bug causes the track stats to only represent one of the two streams:
3193// whichever one has the higher SSRC. So with this bug, there was a 50% chance
3194// that the track stat counters would reset to 0 when the new stream is
3195// received, and a 50% chance that they'll stop updating (while
3196// "concealed_samples" continues increasing, due to silence being generated for
3197// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003198TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003199 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07003200 ASSERT_TRUE(CreatePeerConnectionWrappers());
3201 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003202 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07003203 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
3204 // that doesn't signal SSRCs (from the callee's perspective).
3205 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3206 caller()->CreateAndSetAndSignalOffer();
3207 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3208 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003209 {
3210 MediaExpectations media_expectations;
3211 media_expectations.CalleeExpectsSomeAudio(50);
3212 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3213 }
deadbeef4e2deab2017-09-20 13:56:21 -07003214 // Some audio frames were received, so we should have nonzero "samples
3215 // received" for the track.
3216 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3217 callee()->NewGetStats();
3218 ASSERT_NE(nullptr, report);
3219 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3220 ASSERT_EQ(1U, track_stats.size());
3221 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3222 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
3223 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
3224
3225 // Create a new offer and munge it to cause the caller to use a new SSRC.
3226 caller()->SetGeneratedSdpMunger(ModifySsrcs);
3227 caller()->CreateAndSetAndSignalOffer();
3228 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3229 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
3230 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003231 {
3232 MediaExpectations media_expectations;
3233 media_expectations.CalleeExpectsSomeAudio(25);
3234 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3235 }
deadbeef4e2deab2017-09-20 13:56:21 -07003236
3237 report = callee()->NewGetStats();
3238 ASSERT_NE(nullptr, report);
3239 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3240 ASSERT_EQ(1U, track_stats.size());
3241 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3242 // The "total samples received" stat should only be greater than it was
3243 // before.
3244 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
3245 // Right now, the new SSRC will cause the counters to reset to 0.
3246 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
3247
3248 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08003249 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07003250 // good sign that we're seeing stats from the old stream that's no longer
3251 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08003252 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07003253 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
3254 EXPECT_LT(*track_stats[0]->concealed_samples,
3255 *track_stats[0]->total_samples_received *
3256 kAcceptableConcealedSamplesPercentage);
3257
3258 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
3259 // sanity check that the SSRC really changed.
3260 // TODO(deadbeef): This isn't working right now, because we're not returning
3261 // *any* stats for the inactive stream. Uncomment when the bug is completely
3262 // fixed.
3263 // auto inbound_stream_stats =
3264 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3265 // ASSERT_EQ(2U, inbound_stream_stats.size());
3266}
3267
deadbeef1dcb1642017-03-29 21:08:16 -07003268// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003269TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003270 PeerConnectionFactory::Options dtls_10_options;
3271 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3272 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3273 dtls_10_options));
3274 ConnectFakeSignaling();
3275 // Do normal offer/answer and wait for some frames to be received in each
3276 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003277 caller()->AddAudioVideoTracks();
3278 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003279 caller()->CreateAndSetAndSignalOffer();
3280 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003281 MediaExpectations media_expectations;
3282 media_expectations.ExpectBidirectionalAudioAndVideo();
3283 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003284}
3285
3286// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003287TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003288 PeerConnectionFactory::Options dtls_10_options;
3289 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3290 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3291 dtls_10_options));
3292 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003293 caller()->AddAudioVideoTracks();
3294 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003295 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003296 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003297 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003298 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003299 kDefaultTimeout);
3300 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003301 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003302 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003303 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3304 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3305 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003306}
3307
3308// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003309TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003310 PeerConnectionFactory::Options dtls_12_options;
3311 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3312 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3313 dtls_12_options));
3314 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003315 caller()->AddAudioVideoTracks();
3316 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003317 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003318 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003319 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003320 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003321 kDefaultTimeout);
3322 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003323 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003324 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003325 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3326 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3327 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003328}
3329
3330// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3331// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003332TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003333 PeerConnectionFactory::Options caller_options;
3334 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3335 PeerConnectionFactory::Options callee_options;
3336 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3337 ASSERT_TRUE(
3338 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3339 ConnectFakeSignaling();
3340 // Do normal offer/answer and wait for some frames to be received in each
3341 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003342 caller()->AddAudioVideoTracks();
3343 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003344 caller()->CreateAndSetAndSignalOffer();
3345 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003346 MediaExpectations media_expectations;
3347 media_expectations.ExpectBidirectionalAudioAndVideo();
3348 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003349}
3350
3351// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3352// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003353TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003354 PeerConnectionFactory::Options caller_options;
3355 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3356 PeerConnectionFactory::Options callee_options;
3357 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3358 ASSERT_TRUE(
3359 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3360 ConnectFakeSignaling();
3361 // Do normal offer/answer and wait for some frames to be received in each
3362 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003363 caller()->AddAudioVideoTracks();
3364 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003365 caller()->CreateAndSetAndSignalOffer();
3366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003367 MediaExpectations media_expectations;
3368 media_expectations.ExpectBidirectionalAudioAndVideo();
3369 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003370}
3371
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003372// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3373// works as expected; the cipher should only be used if enabled by both sides.
3374TEST_P(PeerConnectionIntegrationTest,
3375 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3376 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003377 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003378 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003379 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3380 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003381 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3382 TestNegotiatedCipherSuite(caller_options, callee_options,
3383 expected_cipher_suite);
3384}
3385
3386TEST_P(PeerConnectionIntegrationTest,
3387 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3388 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003389 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3390 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003391 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003392 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003393 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3394 TestNegotiatedCipherSuite(caller_options, callee_options,
3395 expected_cipher_suite);
3396}
3397
3398TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3399 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003400 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003401 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003402 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003403 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3404 TestNegotiatedCipherSuite(caller_options, callee_options,
3405 expected_cipher_suite);
3406}
3407
deadbeef1dcb1642017-03-29 21:08:16 -07003408// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003409TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003410 bool local_gcm_enabled = false;
3411 bool remote_gcm_enabled = false;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003412 bool aes_ctr_enabled = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003413 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3414 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003415 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003416}
3417
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003418// Test that a GCM cipher is used if both ends support it and non-GCM is
3419// disabled.
3420TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenOnlyGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003421 bool local_gcm_enabled = true;
3422 bool remote_gcm_enabled = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003423 bool aes_ctr_enabled = false;
deadbeef1dcb1642017-03-29 21:08:16 -07003424 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3425 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003426 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003427}
3428
deadbeef7914b8c2017-04-21 03:23:33 -07003429// Verify that media can be transmitted end-to-end when GCM crypto suites are
3430// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3431// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3432// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003433TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003434 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003435 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003436 gcm_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher = false;
deadbeef7914b8c2017-04-21 03:23:33 -07003437 ASSERT_TRUE(
3438 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3439 ConnectFakeSignaling();
3440 // Do normal offer/answer and wait for some frames to be received in each
3441 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003442 caller()->AddAudioVideoTracks();
3443 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003444 caller()->CreateAndSetAndSignalOffer();
3445 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003446 MediaExpectations media_expectations;
3447 media_expectations.ExpectBidirectionalAudioAndVideo();
3448 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003449}
3450
deadbeef1dcb1642017-03-29 21:08:16 -07003451// This test sets up a call between two parties with audio, video and an RTP
3452// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003453TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003454 PeerConnectionInterface::RTCConfiguration rtc_config;
3455 rtc_config.enable_rtp_data_channel = true;
3456 rtc_config.enable_dtls_srtp = false;
3457 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003458 ConnectFakeSignaling();
3459 // Expect that data channel created on caller side will show up for callee as
3460 // well.
3461 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003462 caller()->AddAudioVideoTracks();
3463 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003464 caller()->CreateAndSetAndSignalOffer();
3465 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3466 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003467 MediaExpectations media_expectations;
3468 media_expectations.ExpectBidirectionalAudioAndVideo();
3469 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003470 ASSERT_NE(nullptr, caller()->data_channel());
3471 ASSERT_NE(nullptr, callee()->data_channel());
3472 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3473 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3474
3475 // Ensure data can be sent in both directions.
3476 std::string data = "hello world";
3477 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3478 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3479 kDefaultTimeout);
3480 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3481 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3482 kDefaultTimeout);
3483}
3484
3485// Ensure that an RTP data channel is signaled as closed for the caller when
3486// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003487TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003488 RtpDataChannelSignaledClosedInCalleeOffer) {
3489 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003490 PeerConnectionInterface::RTCConfiguration rtc_config;
3491 rtc_config.enable_rtp_data_channel = true;
3492 rtc_config.enable_dtls_srtp = false;
3493 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003494 ConnectFakeSignaling();
3495 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003496 caller()->AddAudioVideoTracks();
3497 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003498 caller()->CreateAndSetAndSignalOffer();
3499 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3500 ASSERT_NE(nullptr, caller()->data_channel());
3501 ASSERT_NE(nullptr, callee()->data_channel());
3502 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3503 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3504
3505 // Close the data channel on the callee, and do an updated offer/answer.
3506 callee()->data_channel()->Close();
3507 callee()->CreateAndSetAndSignalOffer();
3508 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3509 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3510 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3511}
3512
3513// Tests that data is buffered in an RTP data channel until an observer is
3514// registered for it.
3515//
3516// NOTE: RTP data channels can receive data before the underlying
3517// transport has detected that a channel is writable and thus data can be
3518// received before the data channel state changes to open. That is hard to test
3519// but the same buffering is expected to be used in that case.
Yves Gerey100fe632020-01-17 19:15:53 +01003520//
3521// Use fake clock and simulated network delay so that we predictably can wait
3522// until an SCTP message has been delivered without "sleep()"ing.
3523TEST_P(PeerConnectionIntegrationTestWithFakeClock,
deadbeef1dcb1642017-03-29 21:08:16 -07003524 DataBufferedUntilRtpDataChannelObserverRegistered) {
deadbeef1dcb1642017-03-29 21:08:16 -07003525 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3526 virtual_socket_server()->UpdateDelayDistribution();
3527
Niels Möllerf06f9232018-08-07 12:32:18 +02003528 PeerConnectionInterface::RTCConfiguration rtc_config;
3529 rtc_config.enable_rtp_data_channel = true;
3530 rtc_config.enable_dtls_srtp = false;
3531 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003532 ConnectFakeSignaling();
3533 caller()->CreateDataChannel();
3534 caller()->CreateAndSetAndSignalOffer();
3535 ASSERT_TRUE(caller()->data_channel() != nullptr);
3536 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
Yves Gerey100fe632020-01-17 19:15:53 +01003537 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003538 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
Yves Gerey100fe632020-01-17 19:15:53 +01003539 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003540 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3541 callee()->data_channel()->state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003542 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003543
3544 // Unregister the observer which is normally automatically registered.
3545 callee()->data_channel()->UnregisterObserver();
3546 // Send data and advance fake clock until it should have been received.
3547 std::string data = "hello world";
3548 caller()->data_channel()->Send(DataBuffer(data));
Yves Gerey100fe632020-01-17 19:15:53 +01003549 SIMULATED_WAIT(false, 50, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003550
3551 // Attach data channel and expect data to be received immediately. Note that
3552 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3553 // further, but data can be received even if the callback is asynchronous.
3554 MockDataChannelObserver new_observer(callee()->data_channel());
3555 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003556 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003557}
3558
3559// This test sets up a call between two parties with audio, video and but only
3560// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003561TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003562 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3563 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003564 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003565 rtc_config_1.enable_dtls_srtp = false;
3566 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3567 rtc_config_2.enable_dtls_srtp = false;
3568 rtc_config_2.enable_dtls_srtp = false;
3569 ASSERT_TRUE(
3570 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003571 ConnectFakeSignaling();
3572 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003573 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003574 caller()->AddAudioVideoTracks();
3575 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003576 caller()->CreateAndSetAndSignalOffer();
3577 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3578 // The caller should still have a data channel, but it should be closed, and
3579 // one should ever have been created for the callee.
3580 EXPECT_TRUE(caller()->data_channel() != nullptr);
3581 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3582 EXPECT_EQ(nullptr, callee()->data_channel());
3583}
3584
3585// This test sets up a call between two parties with audio, and video. When
3586// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003587TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003588 PeerConnectionInterface::RTCConfiguration rtc_config;
3589 rtc_config.enable_rtp_data_channel = true;
3590 rtc_config.enable_dtls_srtp = false;
3591 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003592 ConnectFakeSignaling();
3593 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003594 caller()->AddAudioVideoTracks();
3595 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003596 caller()->CreateAndSetAndSignalOffer();
3597 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3598 // Create data channel and do new offer and answer.
3599 caller()->CreateDataChannel();
3600 caller()->CreateAndSetAndSignalOffer();
3601 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3602 ASSERT_NE(nullptr, caller()->data_channel());
3603 ASSERT_NE(nullptr, callee()->data_channel());
3604 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3605 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3606 // Ensure data can be sent in both directions.
3607 std::string data = "hello world";
3608 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3609 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3610 kDefaultTimeout);
3611 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3612 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3613 kDefaultTimeout);
3614}
3615
3616#ifdef HAVE_SCTP
3617
3618// This test sets up a call between two parties with audio, video and an SCTP
3619// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003620TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003621 ASSERT_TRUE(CreatePeerConnectionWrappers());
3622 ConnectFakeSignaling();
3623 // Expect that data channel created on caller side will show up for callee as
3624 // well.
3625 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003626 caller()->AddAudioVideoTracks();
3627 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003628 caller()->CreateAndSetAndSignalOffer();
3629 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3630 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003631 MediaExpectations media_expectations;
3632 media_expectations.ExpectBidirectionalAudioAndVideo();
3633 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003634 // Caller data channel should already exist (it created one). Callee data
3635 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3636 ASSERT_NE(nullptr, caller()->data_channel());
3637 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3638 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3639 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3640
3641 // Ensure data can be sent in both directions.
3642 std::string data = "hello world";
3643 caller()->data_channel()->Send(DataBuffer(data));
3644 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3645 kDefaultTimeout);
3646 callee()->data_channel()->Send(DataBuffer(data));
3647 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3648 kDefaultTimeout);
3649}
3650
3651// Ensure that when the callee closes an SCTP data channel, the closing
3652// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003653TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003654 // Same procedure as above test.
3655 ASSERT_TRUE(CreatePeerConnectionWrappers());
3656 ConnectFakeSignaling();
3657 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003658 caller()->AddAudioVideoTracks();
3659 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003660 caller()->CreateAndSetAndSignalOffer();
3661 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3662 ASSERT_NE(nullptr, caller()->data_channel());
3663 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3664 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3665 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3666
3667 // Close the data channel on the callee side, and wait for it to reach the
3668 // "closed" state on both sides.
3669 callee()->data_channel()->Close();
3670 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3671 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3672}
3673
Seth Hampson2f0d7022018-02-20 11:54:42 -08003674TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003675 ASSERT_TRUE(CreatePeerConnectionWrappers());
3676 ConnectFakeSignaling();
3677 webrtc::DataChannelInit init;
3678 init.id = 53;
3679 init.maxRetransmits = 52;
3680 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003681 caller()->AddAudioVideoTracks();
3682 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003683 caller()->CreateAndSetAndSignalOffer();
3684 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003685 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3686 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003687 // Since "negotiated" is false, the "id" parameter should be ignored.
3688 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003689 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3690 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3691 EXPECT_FALSE(callee()->data_channel()->negotiated());
3692}
3693
deadbeef1dcb1642017-03-29 21:08:16 -07003694// Test usrsctp's ability to process unordered data stream, where data actually
3695// arrives out of order using simulated delays. Previously there have been some
3696// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003697TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003698 // Introduce random network delays.
3699 // Otherwise it's not a true "unordered" test.
3700 virtual_socket_server()->set_delay_mean(20);
3701 virtual_socket_server()->set_delay_stddev(5);
3702 virtual_socket_server()->UpdateDelayDistribution();
3703 // Normal procedure, but with unordered data channel config.
3704 ASSERT_TRUE(CreatePeerConnectionWrappers());
3705 ConnectFakeSignaling();
3706 webrtc::DataChannelInit init;
3707 init.ordered = false;
3708 caller()->CreateDataChannel(&init);
3709 caller()->CreateAndSetAndSignalOffer();
3710 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3711 ASSERT_NE(nullptr, caller()->data_channel());
3712 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3713 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3714 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3715
3716 static constexpr int kNumMessages = 100;
3717 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3718 static constexpr size_t kMaxMessageSize = 4096;
3719 // Create and send random messages.
3720 std::vector<std::string> sent_messages;
3721 for (int i = 0; i < kNumMessages; ++i) {
3722 size_t length =
3723 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3724 std::string message;
3725 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3726 caller()->data_channel()->Send(DataBuffer(message));
3727 callee()->data_channel()->Send(DataBuffer(message));
3728 sent_messages.push_back(message);
3729 }
3730
3731 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003732 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003733 caller()->data_observer()->received_message_count(),
3734 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003735 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003736 callee()->data_observer()->received_message_count(),
3737 kDefaultTimeout);
3738
3739 // Sort and compare to make sure none of the messages were corrupted.
3740 std::vector<std::string> caller_received_messages =
3741 caller()->data_observer()->messages();
3742 std::vector<std::string> callee_received_messages =
3743 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003744 absl::c_sort(sent_messages);
3745 absl::c_sort(caller_received_messages);
3746 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003747 EXPECT_EQ(sent_messages, caller_received_messages);
3748 EXPECT_EQ(sent_messages, callee_received_messages);
3749}
3750
3751// This test sets up a call between two parties with audio, and video. When
3752// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003753TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003754 ASSERT_TRUE(CreatePeerConnectionWrappers());
3755 ConnectFakeSignaling();
3756 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003757 caller()->AddAudioVideoTracks();
3758 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003759 caller()->CreateAndSetAndSignalOffer();
3760 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3761 // Create data channel and do new offer and answer.
3762 caller()->CreateDataChannel();
3763 caller()->CreateAndSetAndSignalOffer();
3764 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3765 // Caller data channel should already exist (it created one). Callee data
3766 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3767 ASSERT_NE(nullptr, caller()->data_channel());
3768 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3769 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3770 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3771 // Ensure data can be sent in both directions.
3772 std::string data = "hello world";
3773 caller()->data_channel()->Send(DataBuffer(data));
3774 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3775 kDefaultTimeout);
3776 callee()->data_channel()->Send(DataBuffer(data));
3777 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3778 kDefaultTimeout);
3779}
3780
deadbeef7914b8c2017-04-21 03:23:33 -07003781// Set up a connection initially just using SCTP data channels, later upgrading
3782// to audio/video, ensuring frames are received end-to-end. Effectively the
3783// inverse of the test above.
3784// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003785TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003786 ASSERT_TRUE(CreatePeerConnectionWrappers());
3787 ConnectFakeSignaling();
3788 // Do initial offer/answer with just data channel.
3789 caller()->CreateDataChannel();
3790 caller()->CreateAndSetAndSignalOffer();
3791 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3792 // Wait until data can be sent over the data channel.
3793 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3794 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3795 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3796
3797 // Do subsequent offer/answer with two-way audio and video. Audio and video
3798 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003799 caller()->AddAudioVideoTracks();
3800 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003801 caller()->CreateAndSetAndSignalOffer();
3802 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003803 MediaExpectations media_expectations;
3804 media_expectations.ExpectBidirectionalAudioAndVideo();
3805 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003806}
3807
deadbeef8b7e9ad2017-05-25 09:38:55 -07003808static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003809 cricket::SctpDataContentDescription* dcd_offer =
3810 GetFirstSctpDataContentDescription(desc);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01003811 // See https://crbug.com/webrtc/11211 - this function is a no-op
Steve Antonb1c1de12017-12-21 15:14:30 -08003812 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003813 dcd_offer->set_use_sctpmap(false);
3814 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3815}
3816
3817// Test that the data channel works when a spec-compliant SCTP m= section is
3818// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3819// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003820TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003821 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3822 ASSERT_TRUE(CreatePeerConnectionWrappers());
3823 ConnectFakeSignaling();
3824 caller()->CreateDataChannel();
3825 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3826 caller()->CreateAndSetAndSignalOffer();
3827 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3828 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3829 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3830 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3831
3832 // Ensure data can be sent in both directions.
3833 std::string data = "hello world";
3834 caller()->data_channel()->Send(DataBuffer(data));
3835 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3836 kDefaultTimeout);
3837 callee()->data_channel()->Send(DataBuffer(data));
3838 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3839 kDefaultTimeout);
3840}
3841
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003842// Tests that the datagram transport to SCTP fallback works correctly when
3843// datagram transport negotiation fails.
3844TEST_P(PeerConnectionIntegrationTest,
3845 DatagramTransportDataChannelFallbackToSctp) {
3846 PeerConnectionInterface::RTCConfiguration rtc_config;
3847 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3848 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3849 rtc_config.use_datagram_transport_for_data_channels = true;
3850
3851 // Configure one endpoint to use datagram transport for data channels while
3852 // the other does not.
3853 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3854 rtc_config, RTCConfiguration(),
3855 loopback_media_transports()->first_factory(), nullptr));
3856 ConnectFakeSignaling();
3857
3858 // The caller offers a data channel using either datagram transport or SCTP.
3859 caller()->CreateDataChannel();
3860 caller()->AddAudioVideoTracks();
3861 callee()->AddAudioVideoTracks();
3862 caller()->CreateAndSetAndSignalOffer();
3863 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3864
3865 // Negotiation should fallback to SCTP, allowing the data channel to be
3866 // established.
3867 ASSERT_NE(nullptr, caller()->data_channel());
3868 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3869 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3870 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3871
3872 // Ensure data can be sent in both directions.
3873 std::string data = "hello world";
3874 caller()->data_channel()->Send(DataBuffer(data));
3875 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3876 kDefaultTimeout);
3877 callee()->data_channel()->Send(DataBuffer(data));
3878 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3879 kDefaultTimeout);
3880
3881 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3882 MediaExpectations media_expectations;
3883 media_expectations.ExpectBidirectionalAudioAndVideo();
3884 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3885}
3886
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07003887// Tests that the data channel transport works correctly when datagram transport
3888// negotiation succeeds and does not fall back to SCTP.
3889TEST_P(PeerConnectionIntegrationTest,
3890 DatagramTransportDataChannelDoesNotFallbackToSctp) {
3891 PeerConnectionInterface::RTCConfiguration rtc_config;
3892 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3893 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3894 rtc_config.use_datagram_transport_for_data_channels = true;
3895
3896 // Configure one endpoint to use datagram transport for data channels while
3897 // the other does not.
3898 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3899 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3900 loopback_media_transports()->second_factory()));
3901 ConnectFakeSignaling();
3902
3903 // The caller offers a data channel using either datagram transport or SCTP.
3904 caller()->CreateDataChannel();
3905 caller()->AddAudioVideoTracks();
3906 callee()->AddAudioVideoTracks();
3907 caller()->CreateAndSetAndSignalOffer();
3908 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3909
3910 // Ensure that the data channel transport is ready.
3911 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3912 loopback_media_transports()->FlushAsyncInvokes();
3913
3914 // Negotiation should succeed, allowing the data channel to be established.
3915 ASSERT_NE(nullptr, caller()->data_channel());
3916 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3917 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3918 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3919
3920 // Ensure data can be sent in both directions.
3921 std::string data = "hello world";
3922 caller()->data_channel()->Send(DataBuffer(data));
3923 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3924 kDefaultTimeout);
3925 callee()->data_channel()->Send(DataBuffer(data));
3926 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3927 kDefaultTimeout);
3928
3929 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3930 MediaExpectations media_expectations;
3931 media_expectations.ExpectBidirectionalAudioAndVideo();
3932 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3933}
3934
Bjorn A Mellem0cda7b82020-01-28 17:06:55 -08003935// Tests that the datagram transport to SCTP fallback works correctly when
3936// datagram transports do not advertise compatible transport parameters.
3937TEST_P(PeerConnectionIntegrationTest,
3938 DatagramTransportIncompatibleParametersFallsBackToSctp) {
3939 PeerConnectionInterface::RTCConfiguration rtc_config;
3940 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3941 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3942 rtc_config.use_datagram_transport_for_data_channels = true;
3943
3944 // By default, only equal parameters are compatible.
3945 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
3946 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
3947
3948 // Configure one endpoint to use datagram transport for data channels while
3949 // the other does not.
3950 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3951 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3952 loopback_media_transports()->second_factory()));
3953 ConnectFakeSignaling();
3954
3955 // The caller offers a data channel using either datagram transport or SCTP.
3956 caller()->CreateDataChannel();
3957 caller()->AddAudioVideoTracks();
3958 callee()->AddAudioVideoTracks();
3959 caller()->CreateAndSetAndSignalOffer();
3960 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3961
3962 // Negotiation should fallback to SCTP, allowing the data channel to be
3963 // established.
3964 ASSERT_NE(nullptr, caller()->data_channel());
3965 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3966 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3967 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3968
3969 // Both endpoints should agree to use SCTP for data channels.
3970 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
3971 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
3972
3973 // Ensure data can be sent in both directions.
3974 std::string data = "hello world";
3975 caller()->data_channel()->Send(DataBuffer(data));
3976 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3977 kDefaultTimeout);
3978 callee()->data_channel()->Send(DataBuffer(data));
3979 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3980 kDefaultTimeout);
3981
3982 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3983 MediaExpectations media_expectations;
3984 media_expectations.ExpectBidirectionalAudioAndVideo();
3985 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3986}
3987
3988// Tests that the datagram transport to SCTP fallback works correctly when
3989// only the answerer believes datagram transport parameters are incompatible.
3990TEST_P(PeerConnectionIntegrationTest,
3991 DatagramTransportIncompatibleParametersOnAnswererFallsBackToSctp) {
3992 PeerConnectionInterface::RTCConfiguration rtc_config;
3993 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3994 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3995 rtc_config.use_datagram_transport_for_data_channels = true;
3996
3997 // By default, only equal parameters are compatible.
3998 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
3999 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
4000
4001 // Set the offerer to accept different parameters, while the answerer rejects
4002 // them.
4003 loopback_media_transports()->SetFirstDatagramTransportParametersComparison(
4004 [](absl::string_view a, absl::string_view b) { return true; });
4005 loopback_media_transports()->SetSecondDatagramTransportParametersComparison(
4006 [](absl::string_view a, absl::string_view b) { return false; });
4007
4008 // Configure one endpoint to use datagram transport for data channels while
4009 // the other does not.
4010 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4011 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4012 loopback_media_transports()->second_factory()));
4013 ConnectFakeSignaling();
4014
4015 // The caller offers a data channel using either datagram transport or SCTP.
4016 caller()->CreateDataChannel();
4017 caller()->AddAudioVideoTracks();
4018 callee()->AddAudioVideoTracks();
4019 caller()->CreateAndSetAndSignalOffer();
4020 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4021
4022 // Negotiation should fallback to SCTP, allowing the data channel to be
4023 // established.
4024 ASSERT_NE(nullptr, caller()->data_channel());
4025 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4026 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4027 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4028
4029 // Both endpoints should agree to use SCTP for data channels.
4030 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4031 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4032
4033 // Ensure data can be sent in both directions.
4034 std::string data = "hello world";
4035 caller()->data_channel()->Send(DataBuffer(data));
4036 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4037 kDefaultTimeout);
4038 callee()->data_channel()->Send(DataBuffer(data));
4039 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4040 kDefaultTimeout);
4041
4042 // Ensure that failure of the datagram negotiation doesn't impede media flow.
4043 MediaExpectations media_expectations;
4044 media_expectations.ExpectBidirectionalAudioAndVideo();
4045 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4046}
4047
4048// Tests that the data channel transport works correctly when datagram
4049// transports provide different, but compatible, transport parameters.
4050TEST_P(PeerConnectionIntegrationTest,
4051 DatagramTransportCompatibleParametersDoNotFallbackToSctp) {
4052 PeerConnectionInterface::RTCConfiguration rtc_config;
4053 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4054 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4055 rtc_config.use_datagram_transport_for_data_channels = true;
4056
4057 // By default, only equal parameters are compatible.
4058 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
4059 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
4060
4061 // Change the comparison used to treat these transport parameters are
4062 // compatible (on both sides).
4063 loopback_media_transports()->SetFirstDatagramTransportParametersComparison(
4064 [](absl::string_view a, absl::string_view b) { return true; });
4065 loopback_media_transports()->SetSecondDatagramTransportParametersComparison(
4066 [](absl::string_view a, absl::string_view b) { return true; });
4067
4068 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4069 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4070 loopback_media_transports()->second_factory()));
4071 ConnectFakeSignaling();
4072
4073 // The caller offers a data channel using either datagram transport or SCTP.
4074 caller()->CreateDataChannel();
4075 caller()->AddAudioVideoTracks();
4076 callee()->AddAudioVideoTracks();
4077 caller()->CreateAndSetAndSignalOffer();
4078 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4079
4080 // Ensure that the data channel transport is ready.
4081 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4082 loopback_media_transports()->FlushAsyncInvokes();
4083
4084 // Negotiation should succeed, allowing the data channel to be established.
4085 ASSERT_NE(nullptr, caller()->data_channel());
4086 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4087 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4088 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4089
4090 // Both endpoints should agree to use datagram transport for data channels.
4091 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4092 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4093
4094 // Ensure data can be sent in both directions.
4095 std::string data = "hello world";
4096 caller()->data_channel()->Send(DataBuffer(data));
4097 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4098 kDefaultTimeout);
4099 callee()->data_channel()->Send(DataBuffer(data));
4100 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4101 kDefaultTimeout);
4102
4103 // Ensure that failure of the datagram negotiation doesn't impede media flow.
4104 MediaExpectations media_expectations;
4105 media_expectations.ExpectBidirectionalAudioAndVideo();
4106 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4107}
4108
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004109TEST_P(PeerConnectionIntegrationTest,
4110 DatagramTransportDataChannelWithMediaOnCaller) {
4111 // Configure the caller to attempt use of datagram transport for media and
4112 // data channels.
4113 PeerConnectionInterface::RTCConfiguration offerer_config;
4114 offerer_config.rtcp_mux_policy =
4115 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4116 offerer_config.bundle_policy =
4117 PeerConnectionInterface::kBundlePolicyMaxBundle;
4118 offerer_config.use_datagram_transport_for_data_channels = true;
4119 offerer_config.use_datagram_transport = true;
4120
4121 // Configure the callee to only use datagram transport for data channels.
4122 PeerConnectionInterface::RTCConfiguration answerer_config;
4123 answerer_config.rtcp_mux_policy =
4124 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4125 answerer_config.bundle_policy =
4126 PeerConnectionInterface::kBundlePolicyMaxBundle;
4127 answerer_config.use_datagram_transport_for_data_channels = true;
4128
4129 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4130 offerer_config, answerer_config,
4131 loopback_media_transports()->first_factory(),
4132 loopback_media_transports()->second_factory()));
4133 ConnectFakeSignaling();
4134
4135 // Offer both media and data.
4136 caller()->AddAudioVideoTracks();
4137 callee()->AddAudioVideoTracks();
4138 caller()->CreateDataChannel();
4139 caller()->CreateAndSetAndSignalOffer();
4140 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4141
4142 // Ensure that the data channel transport is ready.
4143 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4144 loopback_media_transports()->FlushAsyncInvokes();
4145
4146 ASSERT_NE(nullptr, caller()->data_channel());
4147 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4148 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4149 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4150
4151 // Both endpoints should agree to use datagram transport for data channels.
4152 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4153 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4154
4155 // Ensure data can be sent in both directions.
4156 std::string data = "hello world";
4157 caller()->data_channel()->Send(DataBuffer(data));
4158 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4159 kDefaultTimeout);
4160 callee()->data_channel()->Send(DataBuffer(data));
4161 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4162 kDefaultTimeout);
4163
4164 // Media flow should not be impacted.
4165 MediaExpectations media_expectations;
4166 media_expectations.ExpectBidirectionalAudioAndVideo();
4167 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4168}
4169
4170TEST_P(PeerConnectionIntegrationTest,
4171 DatagramTransportMediaWithDataChannelOnCaller) {
4172 // Configure the caller to attempt use of datagram transport for media and
4173 // data channels.
4174 PeerConnectionInterface::RTCConfiguration offerer_config;
4175 offerer_config.rtcp_mux_policy =
4176 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4177 offerer_config.bundle_policy =
4178 PeerConnectionInterface::kBundlePolicyMaxBundle;
4179 offerer_config.use_datagram_transport_for_data_channels = true;
4180 offerer_config.use_datagram_transport = true;
4181
4182 // Configure the callee to only use datagram transport for media.
4183 PeerConnectionInterface::RTCConfiguration answerer_config;
4184 answerer_config.rtcp_mux_policy =
4185 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4186 answerer_config.bundle_policy =
4187 PeerConnectionInterface::kBundlePolicyMaxBundle;
4188 answerer_config.use_datagram_transport = true;
4189
4190 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4191 offerer_config, answerer_config,
4192 loopback_media_transports()->first_factory(),
4193 loopback_media_transports()->second_factory()));
4194 ConnectFakeSignaling();
4195
4196 // Offer both media and data.
4197 caller()->AddAudioVideoTracks();
4198 callee()->AddAudioVideoTracks();
4199 caller()->CreateDataChannel();
4200 caller()->CreateAndSetAndSignalOffer();
4201 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4202
4203 // Ensure that the data channel transport is ready.
4204 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4205 loopback_media_transports()->FlushAsyncInvokes();
4206
4207 ASSERT_NE(nullptr, caller()->data_channel());
4208 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4209 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4210 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4211
4212 // Both endpoints should agree to use SCTP for data channels.
4213 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4214 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4215
4216 // Ensure data can be sent in both directions.
4217 std::string data = "hello world";
4218 caller()->data_channel()->Send(DataBuffer(data));
4219 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4220 kDefaultTimeout);
4221 callee()->data_channel()->Send(DataBuffer(data));
4222 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4223 kDefaultTimeout);
4224
4225 // Media flow should not be impacted.
4226 MediaExpectations media_expectations;
4227 media_expectations.ExpectBidirectionalAudioAndVideo();
4228 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4229}
4230
4231TEST_P(PeerConnectionIntegrationTest,
4232 DatagramTransportDataChannelWithMediaOnCallee) {
4233 // Configure the caller to attempt use of datagram transport for data
4234 // channels.
4235 PeerConnectionInterface::RTCConfiguration offerer_config;
4236 offerer_config.rtcp_mux_policy =
4237 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4238 offerer_config.bundle_policy =
4239 PeerConnectionInterface::kBundlePolicyMaxBundle;
4240 offerer_config.use_datagram_transport_for_data_channels = true;
4241
4242 // Configure the callee to use datagram transport for data channels and media.
4243 PeerConnectionInterface::RTCConfiguration answerer_config;
4244 answerer_config.rtcp_mux_policy =
4245 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4246 answerer_config.bundle_policy =
4247 PeerConnectionInterface::kBundlePolicyMaxBundle;
4248 answerer_config.use_datagram_transport_for_data_channels = true;
4249 answerer_config.use_datagram_transport = true;
4250
4251 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4252 offerer_config, answerer_config,
4253 loopback_media_transports()->first_factory(),
4254 loopback_media_transports()->second_factory()));
4255 ConnectFakeSignaling();
4256
4257 // Offer both media and data.
4258 caller()->AddAudioVideoTracks();
4259 callee()->AddAudioVideoTracks();
4260 caller()->CreateDataChannel();
4261 caller()->CreateAndSetAndSignalOffer();
4262 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4263
4264 // Ensure that the data channel transport is ready.
4265 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4266 loopback_media_transports()->FlushAsyncInvokes();
4267
4268 ASSERT_NE(nullptr, caller()->data_channel());
4269 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4270 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4271 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4272
4273 // Both endpoints should agree to use datagram transport for data channels.
4274 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4275 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4276
4277 // Ensure data can be sent in both directions.
4278 std::string data = "hello world";
4279 caller()->data_channel()->Send(DataBuffer(data));
4280 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4281 kDefaultTimeout);
4282 callee()->data_channel()->Send(DataBuffer(data));
4283 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4284 kDefaultTimeout);
4285
4286 // Media flow should not be impacted.
4287 MediaExpectations media_expectations;
4288 media_expectations.ExpectBidirectionalAudioAndVideo();
4289 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4290}
4291
4292TEST_P(PeerConnectionIntegrationTest,
4293 DatagramTransportMediaWithDataChannelOnCallee) {
4294 // Configure the caller to attempt use of datagram transport for media.
4295 PeerConnectionInterface::RTCConfiguration offerer_config;
4296 offerer_config.rtcp_mux_policy =
4297 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4298 offerer_config.bundle_policy =
4299 PeerConnectionInterface::kBundlePolicyMaxBundle;
4300 offerer_config.use_datagram_transport = true;
4301
4302 // Configure the callee to only use datagram transport for media and data
4303 // channels.
4304 PeerConnectionInterface::RTCConfiguration answerer_config;
4305 answerer_config.rtcp_mux_policy =
4306 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4307 answerer_config.bundle_policy =
4308 PeerConnectionInterface::kBundlePolicyMaxBundle;
4309 answerer_config.use_datagram_transport = true;
4310 answerer_config.use_datagram_transport_for_data_channels = true;
4311
4312 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4313 offerer_config, answerer_config,
4314 loopback_media_transports()->first_factory(),
4315 loopback_media_transports()->second_factory()));
4316 ConnectFakeSignaling();
4317
4318 // Offer both media and data.
4319 caller()->AddAudioVideoTracks();
4320 callee()->AddAudioVideoTracks();
4321 caller()->CreateDataChannel();
4322 caller()->CreateAndSetAndSignalOffer();
4323 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4324
4325 // Ensure that the data channel transport is ready.
4326 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4327 loopback_media_transports()->FlushAsyncInvokes();
4328
4329 ASSERT_NE(nullptr, caller()->data_channel());
4330 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4331 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4332 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4333
4334 // Both endpoints should agree to use SCTP for data channels.
4335 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4336 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4337
4338 // Ensure data can be sent in both directions.
4339 std::string data = "hello world";
4340 caller()->data_channel()->Send(DataBuffer(data));
4341 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4342 kDefaultTimeout);
4343 callee()->data_channel()->Send(DataBuffer(data));
4344 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4345 kDefaultTimeout);
4346
4347 // Media flow should not be impacted.
4348 MediaExpectations media_expectations;
4349 media_expectations.ExpectBidirectionalAudioAndVideo();
4350 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4351}
4352
4353TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelAndMedia) {
4354 // Configure the caller to use datagram transport for data channels and media.
4355 PeerConnectionInterface::RTCConfiguration offerer_config;
4356 offerer_config.rtcp_mux_policy =
4357 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4358 offerer_config.bundle_policy =
4359 PeerConnectionInterface::kBundlePolicyMaxBundle;
4360 offerer_config.use_datagram_transport_for_data_channels = true;
4361 offerer_config.use_datagram_transport = true;
4362
4363 // Configure the callee to use datagram transport for data channels and media.
4364 PeerConnectionInterface::RTCConfiguration answerer_config;
4365 answerer_config.rtcp_mux_policy =
4366 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4367 answerer_config.bundle_policy =
4368 PeerConnectionInterface::kBundlePolicyMaxBundle;
4369 answerer_config.use_datagram_transport_for_data_channels = true;
4370 answerer_config.use_datagram_transport = true;
4371
4372 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4373 offerer_config, answerer_config,
4374 loopback_media_transports()->first_factory(),
4375 loopback_media_transports()->second_factory()));
4376 ConnectFakeSignaling();
4377
4378 // Offer both media and data.
4379 caller()->AddAudioVideoTracks();
4380 callee()->AddAudioVideoTracks();
4381 caller()->CreateDataChannel();
4382 caller()->CreateAndSetAndSignalOffer();
4383 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4384
4385 // Ensure that the data channel transport is ready.
4386 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4387 loopback_media_transports()->FlushAsyncInvokes();
4388
4389 ASSERT_NE(nullptr, caller()->data_channel());
4390 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4391 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4392 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4393
4394 // Both endpoints should agree to use datagram transport for data channels.
4395 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4396 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4397
4398 // Ensure data can be sent in both directions.
4399 std::string data = "hello world";
4400 caller()->data_channel()->Send(DataBuffer(data));
4401 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4402 kDefaultTimeout);
4403 callee()->data_channel()->Send(DataBuffer(data));
4404 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4405 kDefaultTimeout);
4406
4407 // Media flow should not be impacted.
4408 MediaExpectations media_expectations;
4409 media_expectations.ExpectBidirectionalAudioAndVideo();
4410 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4411}
4412
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004413// Tests that data channels use SCTP instead of datagram transport if datagram
4414// transport is configured in receive-only mode on the caller.
4415TEST_P(PeerConnectionIntegrationTest,
4416 DatagramTransportDataChannelReceiveOnlyOnCallerUsesSctp) {
4417 PeerConnectionInterface::RTCConfiguration rtc_config;
4418 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4419 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4420 rtc_config.use_datagram_transport_for_data_channels = true;
4421 rtc_config.use_datagram_transport_for_data_channels_receive_only = true;
4422
4423 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4424 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4425 loopback_media_transports()->second_factory()));
4426 ConnectFakeSignaling();
4427
4428 // The caller should offer a data channel using SCTP.
4429 caller()->CreateDataChannel();
4430 caller()->AddAudioVideoTracks();
4431 callee()->AddAudioVideoTracks();
4432 caller()->CreateAndSetAndSignalOffer();
4433 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4434
4435 ASSERT_NE(nullptr, caller()->data_channel());
4436 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4437 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4438 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4439
4440 // SCTP transports should be present, since they are in use.
4441 EXPECT_NE(caller()->pc()->GetSctpTransport(), nullptr);
4442 EXPECT_NE(callee()->pc()->GetSctpTransport(), nullptr);
4443
4444 // Ensure data can be sent in both directions.
4445 std::string data = "hello world";
4446 caller()->data_channel()->Send(DataBuffer(data));
4447 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4448 kDefaultTimeout);
4449 callee()->data_channel()->Send(DataBuffer(data));
4450 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4451 kDefaultTimeout);
4452}
4453
deadbeef1dcb1642017-03-29 21:08:16 -07004454#endif // HAVE_SCTP
4455
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004456// Tests that a callee configured for receive-only use of datagram transport
4457// data channels accepts them on incoming calls.
4458TEST_P(PeerConnectionIntegrationTest,
4459 DatagramTransportDataChannelReceiveOnlyOnCallee) {
4460 PeerConnectionInterface::RTCConfiguration offerer_config;
4461 offerer_config.rtcp_mux_policy =
4462 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4463 offerer_config.bundle_policy =
4464 PeerConnectionInterface::kBundlePolicyMaxBundle;
4465 offerer_config.use_datagram_transport_for_data_channels = true;
4466
4467 PeerConnectionInterface::RTCConfiguration answerer_config;
4468 answerer_config.rtcp_mux_policy =
4469 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4470 answerer_config.bundle_policy =
4471 PeerConnectionInterface::kBundlePolicyMaxBundle;
4472 answerer_config.use_datagram_transport_for_data_channels = true;
4473 answerer_config.use_datagram_transport_for_data_channels_receive_only = true;
4474
4475 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4476 offerer_config, answerer_config,
4477 loopback_media_transports()->first_factory(),
4478 loopback_media_transports()->second_factory()));
4479 ConnectFakeSignaling();
4480
4481 caller()->CreateDataChannel();
4482 caller()->CreateAndSetAndSignalOffer();
4483 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4484
4485 // Ensure that the data channel transport is ready.
4486 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4487 loopback_media_transports()->FlushAsyncInvokes();
4488
4489 ASSERT_NE(nullptr, caller()->data_channel());
4490 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4491 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4492 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4493
4494 // SCTP transports should not be present, since datagram transport is used.
4495 EXPECT_EQ(caller()->pc()->GetSctpTransport(), nullptr);
4496 EXPECT_EQ(callee()->pc()->GetSctpTransport(), nullptr);
4497
4498 // Ensure data can be sent in both directions.
4499 std::string data = "hello world";
4500 caller()->data_channel()->Send(DataBuffer(data));
4501 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4502 kDefaultTimeout);
4503 callee()->data_channel()->Send(DataBuffer(data));
4504 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4505 kDefaultTimeout);
4506}
4507
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004508// This test sets up a call between two parties with a datagram transport data
4509// channel.
4510TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelEndToEnd) {
4511 PeerConnectionInterface::RTCConfiguration rtc_config;
4512 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4513 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4514 rtc_config.use_datagram_transport_for_data_channels = true;
4515 rtc_config.enable_dtls_srtp = false;
4516 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4517 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4518 loopback_media_transports()->second_factory()));
4519 ConnectFakeSignaling();
4520
4521 // Expect that data channel created on caller side will show up for callee as
4522 // well.
4523 caller()->CreateDataChannel();
4524 caller()->CreateAndSetAndSignalOffer();
4525 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4526
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004527 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004528 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4529 loopback_media_transports()->FlushAsyncInvokes();
4530
4531 // Caller data channel should already exist (it created one). Callee data
4532 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4533 ASSERT_NE(nullptr, caller()->data_channel());
4534 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4535 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4536 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4537
4538 // Ensure data can be sent in both directions.
4539 std::string data = "hello world";
4540 caller()->data_channel()->Send(DataBuffer(data));
4541 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4542 kDefaultTimeout);
4543 callee()->data_channel()->Send(DataBuffer(data));
4544 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4545 kDefaultTimeout);
4546}
4547
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004548// Tests that 'zero-rtt' data channel transports (which are ready-to-send as
4549// soon as they're created) work correctly.
4550TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelZeroRtt) {
4551 PeerConnectionInterface::RTCConfiguration rtc_config;
4552 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4553 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4554 rtc_config.use_datagram_transport_for_data_channels = true;
4555 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
4556 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4557 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4558 loopback_media_transports()->second_factory()));
4559 ConnectFakeSignaling();
4560
4561 // Ensure that the callee's media transport is ready-to-send immediately.
4562 // Note that only the callee can become writable in zero RTTs. The caller
4563 // must wait for the callee's answer.
4564 loopback_media_transports()->SetSecondStateAfterConnect(
4565 webrtc::MediaTransportState::kWritable);
4566 loopback_media_transports()->FlushAsyncInvokes();
4567
4568 // Expect that data channel created on caller side will show up for callee as
4569 // well.
4570 caller()->CreateDataChannel();
4571 caller()->CreateAndSetAndSignalOffer();
4572 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4573
4574 loopback_media_transports()->SetFirstState(
4575 webrtc::MediaTransportState::kWritable);
4576 loopback_media_transports()->FlushAsyncInvokes();
4577
4578 // Caller data channel should already exist (it created one). Callee data
4579 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4580 ASSERT_NE(nullptr, caller()->data_channel());
4581 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4582 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4583 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4584
4585 // Ensure data can be sent in both directions.
4586 std::string data = "hello world";
4587 caller()->data_channel()->Send(DataBuffer(data));
4588 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4589 kDefaultTimeout);
4590 callee()->data_channel()->Send(DataBuffer(data));
4591 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4592 kDefaultTimeout);
4593}
4594
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004595// Ensures that when the callee closes a datagram transport data channel, the
4596// closing procedure results in the data channel being closed for the caller
4597// as well.
4598TEST_P(PeerConnectionIntegrationTest,
4599 DatagramTransportDataChannelCalleeCloses) {
4600 PeerConnectionInterface::RTCConfiguration rtc_config;
4601 rtc_config.use_datagram_transport_for_data_channels = true;
4602 rtc_config.enable_dtls_srtp = false;
4603 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4604 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4605 loopback_media_transports()->second_factory()));
4606 ConnectFakeSignaling();
4607
4608 // Create a data channel on the caller and signal it to the callee.
4609 caller()->CreateDataChannel();
4610 caller()->CreateAndSetAndSignalOffer();
4611 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4612
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004613 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004614 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4615 loopback_media_transports()->FlushAsyncInvokes();
4616
4617 // Data channels exist and open on both ends of the connection.
4618 ASSERT_NE(nullptr, caller()->data_channel());
4619 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4620 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4621 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4622
4623 // Close the data channel on the callee side, and wait for it to reach the
4624 // "closed" state on both sides.
4625 callee()->data_channel()->Close();
4626 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
4627 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
4628}
4629
4630// Tests that datagram transport data channels can do in-band negotiation.
4631TEST_P(PeerConnectionIntegrationTest,
4632 DatagramTransportDataChannelConfigSentToOtherSide) {
4633 PeerConnectionInterface::RTCConfiguration rtc_config;
4634 rtc_config.use_datagram_transport_for_data_channels = true;
4635 rtc_config.enable_dtls_srtp = false;
4636 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4637 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4638 loopback_media_transports()->second_factory()));
4639 ConnectFakeSignaling();
4640
4641 // Create a data channel with a non-default configuration and signal it to the
4642 // callee.
4643 webrtc::DataChannelInit init;
4644 init.id = 53;
4645 init.maxRetransmits = 52;
4646 caller()->CreateDataChannel("data-channel", &init);
4647 caller()->CreateAndSetAndSignalOffer();
4648 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4649
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004650 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004651 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4652 loopback_media_transports()->FlushAsyncInvokes();
4653
4654 // Ensure that the data channel exists on the callee with the correct
4655 // configuration.
4656 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4657 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4658 // Since "negotiate" is false, the "id" parameter is ignored.
4659 EXPECT_NE(init.id, callee()->data_channel()->id());
4660 EXPECT_EQ("data-channel", callee()->data_channel()->label());
4661 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
4662 EXPECT_FALSE(callee()->data_channel()->negotiated());
4663}
4664
4665TEST_P(PeerConnectionIntegrationTest,
4666 DatagramTransportDataChannelRejectedWithNoFallback) {
4667 PeerConnectionInterface::RTCConfiguration offerer_config;
4668 offerer_config.rtcp_mux_policy =
4669 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4670 offerer_config.bundle_policy =
4671 PeerConnectionInterface::kBundlePolicyMaxBundle;
4672 offerer_config.use_datagram_transport_for_data_channels = true;
4673 // Disabling DTLS precludes a fallback to SCTP.
4674 offerer_config.enable_dtls_srtp = false;
4675
4676 PeerConnectionInterface::RTCConfiguration answerer_config;
4677 answerer_config.rtcp_mux_policy =
4678 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4679 answerer_config.bundle_policy =
4680 PeerConnectionInterface::kBundlePolicyMaxBundle;
4681 // Both endpoints must disable DTLS or SetRemoteDescription will fail.
4682 answerer_config.enable_dtls_srtp = false;
4683
4684 // Configure one endpoint to use datagram transport for data channels while
4685 // the other does not.
4686 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4687 offerer_config, answerer_config,
4688 loopback_media_transports()->first_factory(), nullptr));
4689 ConnectFakeSignaling();
4690
4691 // The caller offers a data channel using either datagram transport or SCTP.
4692 caller()->CreateDataChannel();
4693 caller()->AddAudioVideoTracks();
4694 callee()->AddAudioVideoTracks();
4695 caller()->CreateAndSetAndSignalOffer();
4696 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4697
4698 // Caller data channel should already exist (it created one). Callee data
4699 // channel should not exist, since negotiation happens in-band, not in SDP.
4700 EXPECT_NE(nullptr, caller()->data_channel());
4701 EXPECT_EQ(nullptr, callee()->data_channel());
4702
4703 // The caller's data channel should close when the datagram transport is
4704 // rejected.
4705 EXPECT_FALSE(caller()->data_observer()->IsOpen());
4706
4707 // Media flow should not be impacted by the failed data channel.
4708 MediaExpectations media_expectations;
4709 media_expectations.ExpectBidirectionalAudioAndVideo();
4710 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4711}
4712
deadbeef1dcb1642017-03-29 21:08:16 -07004713// Test that the ICE connection and gathering states eventually reach
4714// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08004715TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07004716 ASSERT_TRUE(CreatePeerConnectionWrappers());
4717 ConnectFakeSignaling();
4718 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08004719 caller()->AddAudioVideoTracks();
4720 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004721 caller()->CreateAndSetAndSignalOffer();
4722 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4723 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4724 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
4725 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4726 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
4727 // After the best candidate pair is selected and all candidates are signaled,
4728 // the ICE connection state should reach "complete".
4729 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
4730 // answerer/"callee" by default) only reaches "connected". When this is
4731 // fixed, this test should be updated.
4732 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4733 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00004734 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4735 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07004736}
4737
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004738constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
4739 cricket::PORTALLOCATOR_DISABLE_RELAY |
4740 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004741
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004742// Use a mock resolver to resolve the hostname back to the original IP on both
4743// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004744TEST_P(PeerConnectionIntegrationTest,
4745 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004746 auto caller_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004747 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004748 auto callee_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004749 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004750 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
4751 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004752
4753 // This also verifies that the injected AsyncResolverFactory is used by
4754 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004755 EXPECT_CALL(*caller_resolver_factory, Create())
4756 .WillOnce(Return(&caller_async_resolver));
4757 webrtc::PeerConnectionDependencies caller_deps(nullptr);
4758 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
4759
4760 EXPECT_CALL(*callee_resolver_factory, Create())
4761 .WillOnce(Return(&callee_async_resolver));
4762 webrtc::PeerConnectionDependencies callee_deps(nullptr);
4763 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
4764
4765 PeerConnectionInterface::RTCConfiguration config;
4766 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4767 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4768
4769 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4770 config, std::move(caller_deps), config, std::move(callee_deps)));
4771
4772 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
4773 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
4774
4775 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07004776 caller()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004777 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wangecd30542019-05-22 14:34:56 -07004778 callee()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004779 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004780
4781 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004782
4783 ConnectFakeSignaling();
4784 caller()->AddAudioVideoTracks();
4785 callee()->AddAudioVideoTracks();
4786 caller()->CreateAndSetAndSignalOffer();
4787 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4788 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4789 caller()->ice_connection_state(), kDefaultTimeout);
4790 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4791 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08004792
Ying Wangef3998f2019-12-09 13:06:53 +01004793 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
4794 "WebRTC.PeerConnection.CandidatePairType_UDP",
4795 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004796}
4797
Steve Antonede9ca52017-10-16 13:04:27 -07004798// Test that firewalling the ICE connection causes the clients to identify the
4799// disconnected state and then removing the firewall causes them to reconnect.
4800class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004801 : public PeerConnectionIntegrationBaseTest,
4802 public ::testing::WithParamInterface<
4803 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07004804 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004805 PeerConnectionIntegrationIceStatesTest()
4806 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
4807 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07004808 }
4809
4810 void StartStunServer(const SocketAddress& server_address) {
4811 stun_server_.reset(
4812 cricket::TestStunServer::Create(network_thread(), server_address));
4813 }
4814
4815 bool TestIPv6() {
4816 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
4817 }
4818
4819 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004820 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
4821 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07004822 }
4823
4824 std::vector<SocketAddress> CallerAddresses() {
4825 std::vector<SocketAddress> addresses;
4826 addresses.push_back(SocketAddress("1.1.1.1", 0));
4827 if (TestIPv6()) {
4828 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
4829 }
4830 return addresses;
4831 }
4832
4833 std::vector<SocketAddress> CalleeAddresses() {
4834 std::vector<SocketAddress> addresses;
4835 addresses.push_back(SocketAddress("2.2.2.2", 0));
4836 if (TestIPv6()) {
4837 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
4838 }
4839 return addresses;
4840 }
4841
4842 void SetUpNetworkInterfaces() {
4843 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07004844 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
4845 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07004846
4847 // Add network addresses for test.
4848 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004849 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004850 }
4851 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004852 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004853 }
4854 }
4855
4856 private:
4857 uint32_t port_allocator_flags_;
4858 std::unique_ptr<cricket::TestStunServer> stun_server_;
4859};
4860
Yves Gerey100fe632020-01-17 19:15:53 +01004861// Ensure FakeClockForTest is constructed first (see class for rationale).
4862class PeerConnectionIntegrationIceStatesTestWithFakeClock
4863 : public FakeClockForTest,
4864 public PeerConnectionIntegrationIceStatesTest {};
4865
Steve Antonede9ca52017-10-16 13:04:27 -07004866// Tests that the PeerConnection goes through all the ICE gathering/connection
4867// states over the duration of the call. This includes Disconnected and Failed
4868// states, induced by putting a firewall between the peers and waiting for them
4869// to time out.
Yves Gerey100fe632020-01-17 19:15:53 +01004870TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock, VerifyIceStates) {
Steve Antonede9ca52017-10-16 13:04:27 -07004871 const SocketAddress kStunServerAddress =
4872 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
4873 StartStunServer(kStunServerAddress);
4874
4875 PeerConnectionInterface::RTCConfiguration config;
4876 PeerConnectionInterface::IceServer ice_stun_server;
4877 ice_stun_server.urls.push_back(
4878 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4879 kStunServerAddress.PortAsString());
4880 config.servers.push_back(ice_stun_server);
4881
4882 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4883 ConnectFakeSignaling();
4884 SetPortAllocatorFlags();
4885 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004886 caller()->AddAudioVideoTracks();
4887 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004888
4889 // Initial state before anything happens.
4890 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4891 caller()->ice_gathering_state());
4892 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4893 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004894 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4895 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004896
4897 // Start the call by creating the offer, setting it as the local description,
4898 // then sending it to the peer who will respond with an answer. This happens
4899 // asynchronously so that we can watch the states as it runs in the
4900 // background.
4901 caller()->CreateAndSetAndSignalOffer();
4902
Steve Antona9b67ce2020-01-16 14:00:44 -08004903 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4904 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004905 FakeClock());
Steve Antona9b67ce2020-01-16 14:00:44 -08004906 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4907 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004908 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004909
4910 // Verify that the observer was notified of the intermediate transitions.
4911 EXPECT_THAT(caller()->ice_connection_state_history(),
4912 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4913 PeerConnectionInterface::kIceConnectionConnected,
4914 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004915 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4916 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4917 PeerConnectionInterface::kIceConnectionConnected,
4918 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004919 EXPECT_THAT(
4920 caller()->peer_connection_state_history(),
4921 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004922 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004923 EXPECT_THAT(caller()->ice_gathering_state_history(),
4924 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4925 PeerConnectionInterface::kIceGatheringComplete));
4926
4927 // Block connections to/from the caller and wait for ICE to become
4928 // disconnected.
4929 for (const auto& caller_address : CallerAddresses()) {
4930 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4931 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004932 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004933 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4934 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004935 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004936 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4937 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004938 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004939
4940 // Let ICE re-establish by removing the firewall rules.
4941 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004942 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004943 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4944 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004945 FakeClock());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004946 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004947 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004948 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004949
4950 // According to RFC7675, if there is no response within 30 seconds then the
4951 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004952 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004953 constexpr int kConsentTimeout = 30000;
4954 for (const auto& caller_address : CallerAddresses()) {
4955 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4956 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004957 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004958 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4959 caller()->ice_connection_state(), kConsentTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004960 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004961 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4962 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004963 kConsentTimeout, FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004964}
4965
4966// Tests that if the connection doesn't get set up properly we eventually reach
4967// the "failed" iceConnectionState.
Yves Gerey100fe632020-01-17 19:15:53 +01004968TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock,
4969 IceStateSetupFailure) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004970 // Block connections to/from the caller and wait for ICE to become
4971 // disconnected.
4972 for (const auto& caller_address : CallerAddresses()) {
4973 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4974 }
4975
4976 ASSERT_TRUE(CreatePeerConnectionWrappers());
4977 ConnectFakeSignaling();
4978 SetPortAllocatorFlags();
4979 SetUpNetworkInterfaces();
4980 caller()->AddAudioVideoTracks();
4981 caller()->CreateAndSetAndSignalOffer();
4982
4983 // According to RFC7675, if there is no response within 30 seconds then the
4984 // peer should consider the other side to have rejected the connection. This
4985 // is signaled by the state transitioning to "failed".
4986 constexpr int kConsentTimeout = 30000;
4987 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4988 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004989 kConsentTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004990}
4991
4992// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4993// and that the statistics in the metric observers are updated correctly.
4994TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4995 ASSERT_TRUE(CreatePeerConnectionWrappers());
4996 ConnectFakeSignaling();
4997 SetPortAllocatorFlags();
4998 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004999 caller()->AddAudioVideoTracks();
5000 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07005001 caller()->CreateAndSetAndSignalOffer();
5002
5003 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton692f3c72020-01-16 14:12:31 -08005004 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5005 caller()->ice_connection_state(), kDefaultTimeout);
5006 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5007 callee()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07005008
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005009 // TODO(bugs.webrtc.org/9456): Fix it.
5010 const int num_best_ipv4 = webrtc::metrics::NumEvents(
5011 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
5012 const int num_best_ipv6 = webrtc::metrics::NumEvents(
5013 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07005014 if (TestIPv6()) {
5015 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
5016 // connection.
Ying Wangef3998f2019-12-09 13:06:53 +01005017 EXPECT_METRIC_EQ(0, num_best_ipv4);
5018 EXPECT_METRIC_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07005019 } else {
Ying Wangef3998f2019-12-09 13:06:53 +01005020 EXPECT_METRIC_EQ(1, num_best_ipv4);
5021 EXPECT_METRIC_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07005022 }
5023
Ying Wangef3998f2019-12-09 13:06:53 +01005024 EXPECT_METRIC_EQ(0, webrtc::metrics::NumEvents(
5025 "WebRTC.PeerConnection.CandidatePairType_UDP",
5026 webrtc::kIceCandidatePairHostHost));
5027 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
5028 "WebRTC.PeerConnection.CandidatePairType_UDP",
5029 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07005030}
5031
5032constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
5033 cricket::PORTALLOCATOR_DISABLE_STUN |
5034 cricket::PORTALLOCATOR_DISABLE_RELAY;
5035constexpr uint32_t kFlagsIPv6NoStun =
5036 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
5037 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
5038constexpr uint32_t kFlagsIPv4Stun =
5039 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
5040
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005041INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08005042 PeerConnectionIntegrationTest,
5043 PeerConnectionIntegrationIceStatesTest,
5044 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5045 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
5046 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
5047 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07005048
Yves Gerey100fe632020-01-17 19:15:53 +01005049INSTANTIATE_TEST_SUITE_P(
5050 PeerConnectionIntegrationTest,
5051 PeerConnectionIntegrationIceStatesTestWithFakeClock,
5052 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5053 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
5054 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
5055 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
5056
deadbeef1dcb1642017-03-29 21:08:16 -07005057// This test sets up a call between two parties with audio and video.
5058// During the call, the caller restarts ICE and the test verifies that
5059// new ICE candidates are generated and audio and video still can flow, and the
5060// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005061TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07005062 ASSERT_TRUE(CreatePeerConnectionWrappers());
5063 ConnectFakeSignaling();
5064 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08005065 caller()->AddAudioVideoTracks();
5066 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07005067 caller()->CreateAndSetAndSignalOffer();
5068 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5069 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5070 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00005071 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5072 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07005073
5074 // To verify that the ICE restart actually occurs, get
5075 // ufrag/password/candidates before and after restart.
5076 // Create an SDP string of the first audio candidate for both clients.
5077 const webrtc::IceCandidateCollection* audio_candidates_caller =
5078 caller()->pc()->local_description()->candidates(0);
5079 const webrtc::IceCandidateCollection* audio_candidates_callee =
5080 callee()->pc()->local_description()->candidates(0);
5081 ASSERT_GT(audio_candidates_caller->count(), 0u);
5082 ASSERT_GT(audio_candidates_callee->count(), 0u);
5083 std::string caller_candidate_pre_restart;
5084 ASSERT_TRUE(
5085 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
5086 std::string callee_candidate_pre_restart;
5087 ASSERT_TRUE(
5088 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
5089 const cricket::SessionDescription* desc =
5090 caller()->pc()->local_description()->description();
5091 std::string caller_ufrag_pre_restart =
5092 desc->transport_infos()[0].description.ice_ufrag;
5093 desc = callee()->pc()->local_description()->description();
5094 std::string callee_ufrag_pre_restart =
5095 desc->transport_infos()[0].description.ice_ufrag;
5096
Alex Drake00c7ecf2019-08-06 10:54:47 -07005097 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07005098 // Have the caller initiate an ICE restart.
5099 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
5100 caller()->CreateAndSetAndSignalOffer();
5101 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5102 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5103 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00005104 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07005105 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5106
5107 // Grab the ufrags/candidates again.
5108 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
5109 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
5110 ASSERT_GT(audio_candidates_caller->count(), 0u);
5111 ASSERT_GT(audio_candidates_callee->count(), 0u);
5112 std::string caller_candidate_post_restart;
5113 ASSERT_TRUE(
5114 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
5115 std::string callee_candidate_post_restart;
5116 ASSERT_TRUE(
5117 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
5118 desc = caller()->pc()->local_description()->description();
5119 std::string caller_ufrag_post_restart =
5120 desc->transport_infos()[0].description.ice_ufrag;
5121 desc = callee()->pc()->local_description()->description();
5122 std::string callee_ufrag_post_restart =
5123 desc->transport_infos()[0].description.ice_ufrag;
5124 // Sanity check that an ICE restart was actually negotiated in SDP.
5125 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
5126 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
5127 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
5128 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07005129 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07005130
5131 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005132 MediaExpectations media_expectations;
5133 media_expectations.ExpectBidirectionalAudioAndVideo();
5134 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005135}
5136
5137// Verify that audio/video can be received end-to-end when ICE renomination is
5138// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005139TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07005140 PeerConnectionInterface::RTCConfiguration config;
5141 config.enable_ice_renomination = true;
5142 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5143 ConnectFakeSignaling();
5144 // Do normal offer/answer and wait for some frames to be received in each
5145 // direction.
Steve Anton15324772018-01-16 10:26:49 -08005146 caller()->AddAudioVideoTracks();
5147 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07005148 caller()->CreateAndSetAndSignalOffer();
5149 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5150 // Sanity check that ICE renomination was actually negotiated.
5151 const cricket::SessionDescription* desc =
5152 caller()->pc()->local_description()->description();
5153 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08005154 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07005155 }
5156 desc = callee()->pc()->local_description()->description();
5157 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08005158 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07005159 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08005160 MediaExpectations media_expectations;
5161 media_expectations.ExpectBidirectionalAudioAndVideo();
5162 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005163}
5164
Steve Anton6f25b092017-10-23 09:39:20 -07005165// With a max bundle policy and RTCP muxing, adding a new media description to
5166// the connection should not affect ICE at all because the new media will use
5167// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005168TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08005169 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07005170 PeerConnectionInterface::RTCConfiguration config;
5171 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5172 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
5173 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
5174 config, PeerConnectionInterface::RTCConfiguration()));
5175 ConnectFakeSignaling();
5176
Steve Anton15324772018-01-16 10:26:49 -08005177 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07005178 caller()->CreateAndSetAndSignalOffer();
5179 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07005180 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
5181 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07005182
5183 caller()->clear_ice_connection_state_history();
5184
Steve Anton15324772018-01-16 10:26:49 -08005185 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07005186 caller()->CreateAndSetAndSignalOffer();
5187 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5188
5189 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
5190}
5191
deadbeef1dcb1642017-03-29 21:08:16 -07005192// This test sets up a call between two parties with audio and video. It then
5193// renegotiates setting the video m-line to "port 0", then later renegotiates
5194// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005195TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07005196 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
5197 ASSERT_TRUE(CreatePeerConnectionWrappers());
5198 ConnectFakeSignaling();
5199
5200 // Do initial negotiation, only sending media from the caller. Will result in
5201 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08005202 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07005203 caller()->CreateAndSetAndSignalOffer();
5204 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5205
5206 // Negotiate again, disabling the video "m=" section (the callee will set the
5207 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005208 if (sdp_semantics_ == SdpSemantics::kPlanB) {
5209 PeerConnectionInterface::RTCOfferAnswerOptions options;
5210 options.offer_to_receive_video = 0;
5211 callee()->SetOfferAnswerOptions(options);
5212 } else {
5213 callee()->SetRemoteOfferHandler([this] {
5214 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
5215 });
5216 }
deadbeef1dcb1642017-03-29 21:08:16 -07005217 caller()->CreateAndSetAndSignalOffer();
5218 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5219 // Sanity check that video "m=" section was actually rejected.
5220 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
5221 callee()->pc()->local_description()->description());
5222 ASSERT_NE(nullptr, answer_video_content);
5223 ASSERT_TRUE(answer_video_content->rejected);
5224
5225 // Enable video and do negotiation again, making sure video is received
5226 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005227 if (sdp_semantics_ == SdpSemantics::kPlanB) {
5228 PeerConnectionInterface::RTCOfferAnswerOptions options;
5229 options.offer_to_receive_video = 1;
5230 callee()->SetOfferAnswerOptions(options);
5231 } else {
5232 // The caller's transceiver is stopped, so we need to add another track.
5233 auto caller_transceiver =
5234 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
5235 EXPECT_TRUE(caller_transceiver->stopped());
5236 caller()->AddVideoTrack();
5237 }
5238 callee()->AddVideoTrack();
5239 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07005240 caller()->CreateAndSetAndSignalOffer();
5241 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005242
deadbeef1dcb1642017-03-29 21:08:16 -07005243 // Verify the caller receives frames from the newly added stream, and the
5244 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005245 MediaExpectations media_expectations;
5246 media_expectations.CalleeExpectsSomeAudio();
5247 media_expectations.ExpectBidirectionalVideo();
5248 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005249}
5250
deadbeef1dcb1642017-03-29 21:08:16 -07005251// This tests that if we negotiate after calling CreateSender but before we
5252// have a track, then set a track later, frames from the newly-set track are
5253// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005254TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07005255 MediaFlowsAfterEarlyWarmupWithCreateSender) {
5256 ASSERT_TRUE(CreatePeerConnectionWrappers());
5257 ConnectFakeSignaling();
5258 auto caller_audio_sender =
5259 caller()->pc()->CreateSender("audio", "caller_stream");
5260 auto caller_video_sender =
5261 caller()->pc()->CreateSender("video", "caller_stream");
5262 auto callee_audio_sender =
5263 callee()->pc()->CreateSender("audio", "callee_stream");
5264 auto callee_video_sender =
5265 callee()->pc()->CreateSender("video", "callee_stream");
5266 caller()->CreateAndSetAndSignalOffer();
5267 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5268 // Wait for ICE to complete, without any tracks being set.
5269 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5270 caller()->ice_connection_state(), kMaxWaitForFramesMs);
5271 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5272 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5273 // Now set the tracks, and expect frames to immediately start flowing.
5274 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
5275 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
5276 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
5277 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08005278 MediaExpectations media_expectations;
5279 media_expectations.ExpectBidirectionalAudioAndVideo();
5280 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5281}
5282
5283// This tests that if we negotiate after calling AddTransceiver but before we
5284// have a track, then set a track later, frames from the newly-set tracks are
5285// received end-to-end.
5286TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5287 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
5288 ASSERT_TRUE(CreatePeerConnectionWrappers());
5289 ConnectFakeSignaling();
5290 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
5291 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
5292 auto caller_audio_sender = audio_result.MoveValue()->sender();
5293 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
5294 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
5295 auto caller_video_sender = video_result.MoveValue()->sender();
5296 callee()->SetRemoteOfferHandler([this] {
5297 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
5298 callee()->pc()->GetTransceivers()[0]->SetDirection(
5299 RtpTransceiverDirection::kSendRecv);
5300 callee()->pc()->GetTransceivers()[1]->SetDirection(
5301 RtpTransceiverDirection::kSendRecv);
5302 });
5303 caller()->CreateAndSetAndSignalOffer();
5304 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5305 // Wait for ICE to complete, without any tracks being set.
5306 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5307 caller()->ice_connection_state(), kMaxWaitForFramesMs);
5308 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5309 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5310 // Now set the tracks, and expect frames to immediately start flowing.
5311 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
5312 auto callee_video_sender = callee()->pc()->GetSenders()[1];
5313 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
5314 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
5315 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
5316 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
5317 MediaExpectations media_expectations;
5318 media_expectations.ExpectBidirectionalAudioAndVideo();
5319 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005320}
5321
5322// This test verifies that a remote video track can be added via AddStream,
5323// and sent end-to-end. For this particular test, it's simply echoed back
5324// from the caller to the callee, rather than being forwarded to a third
5325// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005326TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07005327 ASSERT_TRUE(CreatePeerConnectionWrappers());
5328 ConnectFakeSignaling();
5329 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08005330 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07005331 caller()->CreateAndSetAndSignalOffer();
5332 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02005333 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07005334
5335 // Echo the stream back, and do a new offer/anwer (initiated by callee this
5336 // time).
5337 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
5338 callee()->CreateAndSetAndSignalOffer();
5339 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5340
Seth Hampson2f0d7022018-02-20 11:54:42 -08005341 MediaExpectations media_expectations;
5342 media_expectations.ExpectBidirectionalVideo();
5343 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005344}
5345
5346// Test that we achieve the expected end-to-end connection time, using a
5347// fake clock and simulated latency on the media and signaling paths.
5348// We use a TURN<->TURN connection because this is usually the quickest to
5349// set up initially, especially when we're confident the connection will work
5350// and can start sending media before we get a STUN response.
5351//
5352// With various optimizations enabled, here are the network delays we expect to
5353// be on the critical path:
5354// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
5355// signaling answer (with DTLS fingerprint).
5356// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
5357// using TURN<->TURN pair, and DTLS exchange is 4 packets,
5358// the first of which should have arrived before the answer.
Yves Gerey100fe632020-01-17 19:15:53 +01005359TEST_P(PeerConnectionIntegrationTestWithFakeClock,
5360 EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07005361 static constexpr int media_hop_delay_ms = 50;
5362 static constexpr int signaling_trip_delay_ms = 500;
5363 // For explanation of these values, see comment above.
5364 static constexpr int required_media_hops = 9;
5365 static constexpr int required_signaling_trips = 2;
5366 // For internal delays (such as posting an event asychronously).
5367 static constexpr int allowed_internal_delay_ms = 20;
5368 static constexpr int total_connection_time_ms =
5369 media_hop_delay_ms * required_media_hops +
5370 signaling_trip_delay_ms * required_signaling_trips +
5371 allowed_internal_delay_ms;
5372
5373 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
5374 3478};
5375 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
5376 0};
5377 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
5378 3478};
5379 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
5380 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07005381 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
5382 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005383
Seth Hampsonaed71642018-06-11 07:41:32 -07005384 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
5385 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07005386 // Bypass permission check on received packets so media can be sent before
5387 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07005388 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
5389 turn_server_1->set_enable_permission_checks(false);
5390 });
5391 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
5392 turn_server_2->set_enable_permission_checks(false);
5393 });
deadbeef1dcb1642017-03-29 21:08:16 -07005394
5395 PeerConnectionInterface::RTCConfiguration client_1_config;
5396 webrtc::PeerConnectionInterface::IceServer ice_server_1;
5397 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
5398 ice_server_1.username = "test";
5399 ice_server_1.password = "test";
5400 client_1_config.servers.push_back(ice_server_1);
5401 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5402 client_1_config.presume_writable_when_fully_relayed = true;
5403
5404 PeerConnectionInterface::RTCConfiguration client_2_config;
5405 webrtc::PeerConnectionInterface::IceServer ice_server_2;
5406 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
5407 ice_server_2.username = "test";
5408 ice_server_2.password = "test";
5409 client_2_config.servers.push_back(ice_server_2);
5410 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5411 client_2_config.presume_writable_when_fully_relayed = true;
5412
5413 ASSERT_TRUE(
5414 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5415 // Set up the simulated delays.
5416 SetSignalingDelayMs(signaling_trip_delay_ms);
5417 ConnectFakeSignaling();
5418 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
5419 virtual_socket_server()->UpdateDelayDistribution();
5420
5421 // Set "offer to receive audio/video" without adding any tracks, so we just
5422 // set up ICE/DTLS with no media.
5423 PeerConnectionInterface::RTCOfferAnswerOptions options;
5424 options.offer_to_receive_audio = 1;
5425 options.offer_to_receive_video = 1;
5426 caller()->SetOfferAnswerOptions(options);
5427 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07005428 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
Yves Gerey100fe632020-01-17 19:15:53 +01005429 FakeClock());
Seth Hampson1d4a76d2018-06-19 14:31:41 -07005430 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
5431 // If this is not done a DCHECK can be hit in ports.cc, because a large
5432 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07005433 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07005434}
5435
Jonas Orelandbdcee282017-10-10 14:01:40 +02005436// Verify that a TurnCustomizer passed in through RTCConfiguration
5437// is actually used by the underlying TURN candidate pair.
5438// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005439TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02005440 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
5441 3478};
5442 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
5443 0};
5444 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
5445 3478};
5446 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
5447 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07005448 CreateTurnServer(turn_server_1_internal_address,
5449 turn_server_1_external_address);
5450 CreateTurnServer(turn_server_2_internal_address,
5451 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005452
5453 PeerConnectionInterface::RTCConfiguration client_1_config;
5454 webrtc::PeerConnectionInterface::IceServer ice_server_1;
5455 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
5456 ice_server_1.username = "test";
5457 ice_server_1.password = "test";
5458 client_1_config.servers.push_back(ice_server_1);
5459 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005460 auto* customizer1 = CreateTurnCustomizer();
5461 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005462
5463 PeerConnectionInterface::RTCConfiguration client_2_config;
5464 webrtc::PeerConnectionInterface::IceServer ice_server_2;
5465 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
5466 ice_server_2.username = "test";
5467 ice_server_2.password = "test";
5468 client_2_config.servers.push_back(ice_server_2);
5469 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005470 auto* customizer2 = CreateTurnCustomizer();
5471 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005472
5473 ASSERT_TRUE(
5474 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5475 ConnectFakeSignaling();
5476
5477 // Set "offer to receive audio/video" without adding any tracks, so we just
5478 // set up ICE/DTLS with no media.
5479 PeerConnectionInterface::RTCOfferAnswerOptions options;
5480 options.offer_to_receive_audio = 1;
5481 options.offer_to_receive_video = 1;
5482 caller()->SetOfferAnswerOptions(options);
5483 caller()->CreateAndSetAndSignalOffer();
5484 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5485
Seth Hampsonaed71642018-06-11 07:41:32 -07005486 ExpectTurnCustomizerCountersIncremented(customizer1);
5487 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005488}
5489
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005490// Verifies that you can use TCP instead of UDP to connect to a TURN server and
5491// send media between the caller and the callee.
5492TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
5493 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5494 3478};
5495 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5496
5497 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07005498 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5499 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005500
5501 webrtc::PeerConnectionInterface::IceServer ice_server;
5502 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
5503 ice_server.username = "test";
5504 ice_server.password = "test";
5505
5506 PeerConnectionInterface::RTCConfiguration client_1_config;
5507 client_1_config.servers.push_back(ice_server);
5508 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5509
5510 PeerConnectionInterface::RTCConfiguration client_2_config;
5511 client_2_config.servers.push_back(ice_server);
5512 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5513
5514 ASSERT_TRUE(
5515 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5516
5517 // Do normal offer/answer and wait for ICE to complete.
5518 ConnectFakeSignaling();
5519 caller()->AddAudioVideoTracks();
5520 callee()->AddAudioVideoTracks();
5521 caller()->CreateAndSetAndSignalOffer();
5522 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5523 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5524 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5525
5526 MediaExpectations media_expectations;
5527 media_expectations.ExpectBidirectionalAudioAndVideo();
5528 EXPECT_TRUE(ExpectNewFrames(media_expectations));
5529}
5530
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005531// Verify that a SSLCertificateVerifier passed in through
5532// PeerConnectionDependencies is actually used by the underlying SSL
5533// implementation to determine whether a certificate presented by the TURN
5534// server is accepted by the client. Note that openssladapter_unittest.cc
5535// contains more detailed, lower-level tests.
5536TEST_P(PeerConnectionIntegrationTest,
5537 SSLCertificateVerifierUsedForTurnConnections) {
5538 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5539 3478};
5540 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5541
5542 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5543 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005544 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5545 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005546
5547 webrtc::PeerConnectionInterface::IceServer ice_server;
5548 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5549 ice_server.username = "test";
5550 ice_server.password = "test";
5551
5552 PeerConnectionInterface::RTCConfiguration client_1_config;
5553 client_1_config.servers.push_back(ice_server);
5554 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5555
5556 PeerConnectionInterface::RTCConfiguration client_2_config;
5557 client_2_config.servers.push_back(ice_server);
5558 // Setting the type to kRelay forces the connection to go through a TURN
5559 // server.
5560 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5561
5562 // Get a copy to the pointer so we can verify calls later.
5563 rtc::TestCertificateVerifier* client_1_cert_verifier =
5564 new rtc::TestCertificateVerifier();
5565 client_1_cert_verifier->verify_certificate_ = true;
5566 rtc::TestCertificateVerifier* client_2_cert_verifier =
5567 new rtc::TestCertificateVerifier();
5568 client_2_cert_verifier->verify_certificate_ = true;
5569
5570 // Create the dependencies with the test certificate verifier.
5571 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5572 client_1_deps.tls_cert_verifier =
5573 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5574 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5575 client_2_deps.tls_cert_verifier =
5576 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5577
5578 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5579 client_1_config, std::move(client_1_deps), client_2_config,
5580 std::move(client_2_deps)));
5581 ConnectFakeSignaling();
5582
5583 // Set "offer to receive audio/video" without adding any tracks, so we just
5584 // set up ICE/DTLS with no media.
5585 PeerConnectionInterface::RTCOfferAnswerOptions options;
5586 options.offer_to_receive_audio = 1;
5587 options.offer_to_receive_video = 1;
5588 caller()->SetOfferAnswerOptions(options);
5589 caller()->CreateAndSetAndSignalOffer();
5590 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5591
5592 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5593 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005594}
5595
5596TEST_P(PeerConnectionIntegrationTest,
5597 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
5598 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5599 3478};
5600 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5601
5602 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5603 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005604 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5605 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005606
5607 webrtc::PeerConnectionInterface::IceServer ice_server;
5608 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5609 ice_server.username = "test";
5610 ice_server.password = "test";
5611
5612 PeerConnectionInterface::RTCConfiguration client_1_config;
5613 client_1_config.servers.push_back(ice_server);
5614 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5615
5616 PeerConnectionInterface::RTCConfiguration client_2_config;
5617 client_2_config.servers.push_back(ice_server);
5618 // Setting the type to kRelay forces the connection to go through a TURN
5619 // server.
5620 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5621
5622 // Get a copy to the pointer so we can verify calls later.
5623 rtc::TestCertificateVerifier* client_1_cert_verifier =
5624 new rtc::TestCertificateVerifier();
5625 client_1_cert_verifier->verify_certificate_ = false;
5626 rtc::TestCertificateVerifier* client_2_cert_verifier =
5627 new rtc::TestCertificateVerifier();
5628 client_2_cert_verifier->verify_certificate_ = false;
5629
5630 // Create the dependencies with the test certificate verifier.
5631 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5632 client_1_deps.tls_cert_verifier =
5633 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5634 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5635 client_2_deps.tls_cert_verifier =
5636 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5637
5638 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5639 client_1_config, std::move(client_1_deps), client_2_config,
5640 std::move(client_2_deps)));
5641 ConnectFakeSignaling();
5642
5643 // Set "offer to receive audio/video" without adding any tracks, so we just
5644 // set up ICE/DTLS with no media.
5645 PeerConnectionInterface::RTCOfferAnswerOptions options;
5646 options.offer_to_receive_audio = 1;
5647 options.offer_to_receive_video = 1;
5648 caller()->SetOfferAnswerOptions(options);
5649 caller()->CreateAndSetAndSignalOffer();
5650 bool wait_res = true;
5651 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
5652 // properly, should be able to just wait for a state of "failed" instead of
5653 // waiting a fixed 10 seconds.
5654 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
5655 ASSERT_FALSE(wait_res);
5656
5657 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5658 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005659}
5660
Qingsi Wang25ec8882019-11-15 12:33:05 -08005661// Test that the injected ICE transport factory is used to create ICE transports
5662// for WebRTC connections.
5663TEST_P(PeerConnectionIntegrationTest, IceTransportFactoryUsedForConnections) {
5664 PeerConnectionInterface::RTCConfiguration default_config;
5665 PeerConnectionDependencies dependencies(nullptr);
5666 auto ice_transport_factory = std::make_unique<MockIceTransportFactory>();
5667 EXPECT_CALL(*ice_transport_factory, RecordIceTransportCreated()).Times(1);
5668 dependencies.ice_transport_factory = std::move(ice_transport_factory);
Johannes Kron184ea662020-01-29 12:43:36 +01005669 auto wrapper = CreatePeerConnectionWrapper(
5670 "Caller", nullptr, &default_config, std::move(dependencies), nullptr,
5671 nullptr, /*reset_encoder_factory=*/false,
5672 /*reset_decoder_factory=*/false);
Qingsi Wang25ec8882019-11-15 12:33:05 -08005673 ASSERT_TRUE(wrapper);
5674 wrapper->CreateDataChannel();
5675 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5676 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5677 wrapper->pc()->SetLocalDescription(observer,
5678 wrapper->CreateOfferAndWait().release());
5679}
5680
deadbeefc964d0b2017-04-03 10:03:35 -07005681// Test that audio and video flow end-to-end when codec names don't use the
5682// expected casing, given that they're supposed to be case insensitive. To test
5683// this, all but one codec is removed from each media description, and its
5684// casing is changed.
5685//
5686// In the past, this has regressed and caused crashes/black video, due to the
5687// fact that code at some layers was doing case-insensitive comparisons and
5688// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005689TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07005690 ASSERT_TRUE(CreatePeerConnectionWrappers());
5691 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005692 caller()->AddAudioVideoTracks();
5693 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07005694
5695 // Remove all but one audio/video codec (opus and VP8), and change the
5696 // casing of the caller's generated offer.
5697 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
5698 cricket::AudioContentDescription* audio =
5699 GetFirstAudioContentDescription(description);
5700 ASSERT_NE(nullptr, audio);
5701 auto audio_codecs = audio->codecs();
5702 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
5703 [](const cricket::AudioCodec& codec) {
5704 return codec.name != "opus";
5705 }),
5706 audio_codecs.end());
5707 ASSERT_EQ(1u, audio_codecs.size());
5708 audio_codecs[0].name = "OpUs";
5709 audio->set_codecs(audio_codecs);
5710
5711 cricket::VideoContentDescription* video =
5712 GetFirstVideoContentDescription(description);
5713 ASSERT_NE(nullptr, video);
5714 auto video_codecs = video->codecs();
5715 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
5716 [](const cricket::VideoCodec& codec) {
5717 return codec.name != "VP8";
5718 }),
5719 video_codecs.end());
5720 ASSERT_EQ(1u, video_codecs.size());
5721 video_codecs[0].name = "vP8";
5722 video->set_codecs(video_codecs);
5723 });
5724
5725 caller()->CreateAndSetAndSignalOffer();
5726 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5727
5728 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005729 MediaExpectations media_expectations;
5730 media_expectations.ExpectBidirectionalAudioAndVideo();
5731 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07005732}
5733
Jonas Oreland49ac5952018-09-26 16:04:32 +02005734TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07005735 ASSERT_TRUE(CreatePeerConnectionWrappers());
5736 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005737 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07005738 caller()->CreateAndSetAndSignalOffer();
5739 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07005740 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005741 MediaExpectations media_expectations;
5742 media_expectations.CalleeExpectsSomeAudio(1);
5743 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02005744 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07005745 auto receiver = callee()->pc()->GetReceivers()[0];
5746 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005747 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07005748 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
5749 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02005750 sources[0].source_id());
5751 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
5752}
5753
5754TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
5755 ASSERT_TRUE(CreatePeerConnectionWrappers());
5756 ConnectFakeSignaling();
5757 caller()->AddVideoTrack();
5758 caller()->CreateAndSetAndSignalOffer();
5759 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5760 // Wait for one video frame to be received by the callee.
5761 MediaExpectations media_expectations;
5762 media_expectations.CalleeExpectsSomeVideo(1);
5763 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5764 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
5765 auto receiver = callee()->pc()->GetReceivers()[0];
5766 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
5767 auto sources = receiver->GetSources();
5768 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02005769 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005770 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
5771 sources[0].source_id());
5772 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07005773}
5774
deadbeef2f425aa2017-04-14 10:41:32 -07005775// Test that if a track is removed and added again with a different stream ID,
5776// the new stream ID is successfully communicated in SDP and media continues to
5777// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005778// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
5779// it will not reuse a transceiver that has already been sending. After creating
5780// a new transceiver it tries to create an offer with two senders of the same
5781// track ids and it fails.
5782TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07005783 ASSERT_TRUE(CreatePeerConnectionWrappers());
5784 ConnectFakeSignaling();
5785
deadbeef2f425aa2017-04-14 10:41:32 -07005786 // Add track using stream 1, do offer/answer.
5787 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
5788 caller()->CreateLocalAudioTrack();
5789 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07005790 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07005791 caller()->CreateAndSetAndSignalOffer();
5792 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005793 {
5794 MediaExpectations media_expectations;
5795 media_expectations.CalleeExpectsSomeAudio(1);
5796 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5797 }
deadbeef2f425aa2017-04-14 10:41:32 -07005798 // Remove the sender, and create a new one with the new stream.
5799 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07005800 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07005801 caller()->CreateAndSetAndSignalOffer();
5802 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5803 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005804 {
5805 MediaExpectations media_expectations;
5806 media_expectations.CalleeExpectsSomeAudio();
5807 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5808 }
deadbeef2f425aa2017-04-14 10:41:32 -07005809}
5810
Seth Hampson2f0d7022018-02-20 11:54:42 -08005811TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02005812 ASSERT_TRUE(CreatePeerConnectionWrappers());
5813 ConnectFakeSignaling();
5814
Mirko Bonadei317a1f02019-09-17 17:06:18 +02005815 auto output = std::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005816 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
5817 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02005818 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01005819 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
5820 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02005821
Steve Anton15324772018-01-16 10:26:49 -08005822 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02005823 caller()->CreateAndSetAndSignalOffer();
5824 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5825}
5826
Steve Antonede9ca52017-10-16 13:04:27 -07005827// Test that if candidates are only signaled by applying full session
5828// descriptions (instead of using AddIceCandidate), the peers can connect to
5829// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005830TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07005831 ASSERT_TRUE(CreatePeerConnectionWrappers());
5832 // Each side will signal the session descriptions but not candidates.
5833 ConnectFakeSignalingForSdpOnly();
5834
5835 // Add audio video track and exchange the initial offer/answer with media
5836 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08005837 caller()->AddAudioVideoTracks();
5838 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07005839 caller()->CreateAndSetAndSignalOffer();
5840
5841 // Wait for all candidates to be gathered on both the caller and callee.
5842 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5843 caller()->ice_gathering_state(), kDefaultTimeout);
5844 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5845 callee()->ice_gathering_state(), kDefaultTimeout);
5846
5847 // The candidates will now be included in the session description, so
5848 // signaling them will start the ICE connection.
5849 caller()->CreateAndSetAndSignalOffer();
5850 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5851
5852 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005853 MediaExpectations media_expectations;
5854 media_expectations.ExpectBidirectionalAudioAndVideo();
5855 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07005856}
5857
henrika5f6bf242017-11-01 11:06:56 +01005858// Test that SetAudioPlayout can be used to disable audio playout from the
5859// start, then later enable it. This may be useful, for example, if the caller
5860// needs to play a local ringtone until some event occurs, after which it
5861// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005862TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01005863 ASSERT_TRUE(CreatePeerConnectionWrappers());
5864 ConnectFakeSignaling();
5865
5866 // Set up audio-only call where audio playout is disabled on caller's side.
5867 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08005868 caller()->AddAudioTrack();
5869 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005870 caller()->CreateAndSetAndSignalOffer();
5871 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5872
5873 // Pump messages for a second.
5874 WAIT(false, 1000);
5875 // Since audio playout is disabled, the caller shouldn't have received
5876 // anything (at the playout level, at least).
5877 EXPECT_EQ(0, caller()->audio_frames_received());
5878 // As a sanity check, make sure the callee (for which playout isn't disabled)
5879 // did still see frames on its audio level.
5880 ASSERT_GT(callee()->audio_frames_received(), 0);
5881
5882 // Enable playout again, and ensure audio starts flowing.
5883 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005884 MediaExpectations media_expectations;
5885 media_expectations.ExpectBidirectionalAudio();
5886 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01005887}
5888
5889double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5890 auto report = pc->NewGetStats();
5891 auto track_stats_list =
5892 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5893 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5894 for (const auto* track_stats : track_stats_list) {
5895 if (track_stats->remote_source.is_defined() &&
5896 *track_stats->remote_source) {
5897 remote_track_stats = track_stats;
5898 break;
5899 }
5900 }
5901
5902 if (!remote_track_stats->total_audio_energy.is_defined()) {
5903 return 0.0;
5904 }
5905 return *remote_track_stats->total_audio_energy;
5906}
5907
5908// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5909// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005910TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005911 DisableAudioPlayoutStillGeneratesAudioStats) {
5912 ASSERT_TRUE(CreatePeerConnectionWrappers());
5913 ConnectFakeSignaling();
5914
5915 // Set up audio-only call where playout is disabled but audio-processing is
5916 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005917 caller()->AddAudioTrack();
5918 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005919 caller()->pc()->SetAudioPlayout(false);
5920
5921 caller()->CreateAndSetAndSignalOffer();
5922 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5923
5924 // Wait for the callee to receive audio stats.
5925 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5926}
5927
henrika4f167df2017-11-01 14:45:55 +01005928// Test that SetAudioRecording can be used to disable audio recording from the
5929// start, then later enable it. This may be useful, for example, if the caller
5930// wants to ensure that no audio resources are active before a certain state
5931// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005932TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005933 ASSERT_TRUE(CreatePeerConnectionWrappers());
5934 ConnectFakeSignaling();
5935
5936 // Set up audio-only call where audio recording is disabled on caller's side.
5937 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005938 caller()->AddAudioTrack();
5939 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005940 caller()->CreateAndSetAndSignalOffer();
5941 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5942
5943 // Pump messages for a second.
5944 WAIT(false, 1000);
5945 // Since caller has disabled audio recording, the callee shouldn't have
5946 // received anything.
5947 EXPECT_EQ(0, callee()->audio_frames_received());
5948 // As a sanity check, make sure the caller did still see frames on its
5949 // audio level since audio recording is enabled on the calle side.
5950 ASSERT_GT(caller()->audio_frames_received(), 0);
5951
5952 // Enable audio recording again, and ensure audio starts flowing.
5953 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005954 MediaExpectations media_expectations;
5955 media_expectations.ExpectBidirectionalAudio();
5956 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005957}
5958
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005959// Test that after closing PeerConnections, they stop sending any packets (ICE,
5960// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005961TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005962 // Set up audio/video/data, wait for some frames to be received.
5963 ASSERT_TRUE(CreatePeerConnectionWrappers());
5964 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005965 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005966#ifdef HAVE_SCTP
5967 caller()->CreateDataChannel();
5968#endif
5969 caller()->CreateAndSetAndSignalOffer();
5970 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005971 MediaExpectations media_expectations;
5972 media_expectations.CalleeExpectsSomeAudioAndVideo();
5973 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005974 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005975 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005976 // Pump messages for a second, and ensure no new packets end up sent.
5977 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5978 WAIT(false, 1000);
5979 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5980 EXPECT_EQ(sent_packets_a, sent_packets_b);
5981}
5982
Steve Anton7eca0932018-03-30 15:18:41 -07005983// Test that transport stats are generated by the RTCStatsCollector for a
5984// connection that only involves data channels. This is a regression test for
5985// crbug.com/826972.
5986#ifdef HAVE_SCTP
5987TEST_P(PeerConnectionIntegrationTest,
5988 TransportStatsReportedForDataChannelOnlyConnection) {
5989 ASSERT_TRUE(CreatePeerConnectionWrappers());
5990 ConnectFakeSignaling();
5991 caller()->CreateDataChannel();
5992
5993 caller()->CreateAndSetAndSignalOffer();
5994 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5995 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5996
5997 auto caller_report = caller()->NewGetStats();
5998 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5999 auto callee_report = callee()->NewGetStats();
6000 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
6001}
6002#endif // HAVE_SCTP
6003
Qingsi Wang7685e862018-06-11 20:15:46 -07006004TEST_P(PeerConnectionIntegrationTest,
6005 IceEventsGeneratedAndLoggedInRtcEventLog) {
6006 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
6007 ConnectFakeSignaling();
6008 PeerConnectionInterface::RTCOfferAnswerOptions options;
6009 options.offer_to_receive_audio = 1;
6010 caller()->SetOfferAnswerOptions(options);
6011 caller()->CreateAndSetAndSignalOffer();
6012 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
6013 ASSERT_NE(nullptr, caller()->event_log_factory());
6014 ASSERT_NE(nullptr, callee()->event_log_factory());
6015 webrtc::FakeRtcEventLog* caller_event_log =
6016 static_cast<webrtc::FakeRtcEventLog*>(
6017 caller()->event_log_factory()->last_log_created());
6018 webrtc::FakeRtcEventLog* callee_event_log =
6019 static_cast<webrtc::FakeRtcEventLog*>(
6020 callee()->event_log_factory()->last_log_created());
6021 ASSERT_NE(nullptr, caller_event_log);
6022 ASSERT_NE(nullptr, callee_event_log);
6023 int caller_ice_config_count = caller_event_log->GetEventCount(
6024 webrtc::RtcEvent::Type::IceCandidatePairConfig);
6025 int caller_ice_event_count = caller_event_log->GetEventCount(
6026 webrtc::RtcEvent::Type::IceCandidatePairEvent);
6027 int callee_ice_config_count = callee_event_log->GetEventCount(
6028 webrtc::RtcEvent::Type::IceCandidatePairConfig);
6029 int callee_ice_event_count = callee_event_log->GetEventCount(
6030 webrtc::RtcEvent::Type::IceCandidatePairEvent);
6031 EXPECT_LT(0, caller_ice_config_count);
6032 EXPECT_LT(0, caller_ice_event_count);
6033 EXPECT_LT(0, callee_ice_config_count);
6034 EXPECT_LT(0, callee_ice_event_count);
6035}
6036
Qingsi Wangc129c352019-04-18 10:41:58 -07006037TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07006038 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
6039 3478};
6040 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
6041
6042 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
6043
6044 webrtc::PeerConnectionInterface::IceServer ice_server;
6045 ice_server.urls.push_back("turn:88.88.88.0:3478");
6046 ice_server.username = "test";
6047 ice_server.password = "test";
6048
6049 PeerConnectionInterface::RTCConfiguration caller_config;
6050 caller_config.servers.push_back(ice_server);
6051 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
6052 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006053 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07006054
6055 PeerConnectionInterface::RTCConfiguration callee_config;
6056 callee_config.servers.push_back(ice_server);
6057 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
6058 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006059 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07006060
6061 ASSERT_TRUE(
6062 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
6063
6064 // Do normal offer/answer and wait for ICE to complete.
6065 ConnectFakeSignaling();
6066 caller()->AddAudioVideoTracks();
6067 callee()->AddAudioVideoTracks();
6068 caller()->CreateAndSetAndSignalOffer();
6069 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6070 // Since we are doing continual gathering, the ICE transport does not reach
6071 // kIceGatheringComplete (see
6072 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
6073 // kIceConnectionComplete.
6074 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
6075 caller()->ice_connection_state(), kDefaultTimeout);
6076 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
6077 callee()->ice_connection_state(), kDefaultTimeout);
6078 // Note that we cannot use the metric
6079 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
6080 // metric is only populated when we reach kIceConnectionComplete in the
6081 // current implementation.
6082 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
6083 caller()->last_candidate_gathered().type());
6084 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
6085 callee()->last_candidate_gathered().type());
6086
6087 // Loosen the caller's candidate filter.
6088 caller_config = caller()->pc()->GetConfiguration();
6089 caller_config.type = webrtc::PeerConnectionInterface::kAll;
6090 caller()->pc()->SetConfiguration(caller_config);
6091 // We should have gathered a new host candidate.
6092 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
6093 caller()->last_candidate_gathered().type(), kDefaultTimeout);
6094
6095 // Loosen the callee's candidate filter.
6096 callee_config = callee()->pc()->GetConfiguration();
6097 callee_config.type = webrtc::PeerConnectionInterface::kAll;
6098 callee()->pc()->SetConfiguration(callee_config);
6099 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
6100 callee()->last_candidate_gathered().type(), kDefaultTimeout);
6101}
6102
Eldar Relloda13ea22019-06-01 12:23:43 +03006103TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03006104 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
6105 3478};
6106 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
6107
6108 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
6109
6110 webrtc::PeerConnectionInterface::IceServer ice_server;
6111 ice_server.urls.push_back("turn:88.88.88.0:3478");
6112 ice_server.username = "test";
6113 ice_server.password = "123";
6114
6115 PeerConnectionInterface::RTCConfiguration caller_config;
6116 caller_config.servers.push_back(ice_server);
6117 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
6118 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
6119
6120 PeerConnectionInterface::RTCConfiguration callee_config;
6121 callee_config.servers.push_back(ice_server);
6122 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
6123 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
6124
6125 ASSERT_TRUE(
6126 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
6127
6128 // Do normal offer/answer and wait for ICE to complete.
6129 ConnectFakeSignaling();
6130 caller()->AddAudioVideoTracks();
6131 callee()->AddAudioVideoTracks();
6132 caller()->CreateAndSetAndSignalOffer();
6133 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6134 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
6135 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
6136 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
Eldar Rello0095d372019-12-02 22:22:07 +02006137 EXPECT_NE(caller()->error_event().address, "");
Eldar Relloda13ea22019-06-01 12:23:43 +03006138}
6139
Eldar Rello5ab79e62019-10-09 18:29:44 +03006140TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6141 AudioKeepsFlowingAfterImplicitRollback) {
6142 PeerConnectionInterface::RTCConfiguration config;
6143 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
6144 config.enable_implicit_rollback = true;
6145 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
6146 ConnectFakeSignaling();
6147 caller()->AddAudioTrack();
6148 callee()->AddAudioTrack();
6149 caller()->CreateAndSetAndSignalOffer();
6150 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6151 MediaExpectations media_expectations;
6152 media_expectations.ExpectBidirectionalAudio();
6153 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6154 SetSignalIceCandidates(false); // Workaround candidate outrace sdp.
6155 caller()->AddVideoTrack();
6156 callee()->AddVideoTrack();
6157 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
6158 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
6159 callee()->pc()->SetLocalDescription(observer,
6160 callee()->CreateOfferAndWait().release());
6161 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
6162 caller()->CreateAndSetAndSignalOffer(); // Implicit rollback.
6163 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6164 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6165}
6166
6167TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6168 ImplicitRollbackVisitsStableState) {
6169 RTCConfiguration config;
6170 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
6171 config.enable_implicit_rollback = true;
6172
6173 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
6174
6175 rtc::scoped_refptr<MockSetSessionDescriptionObserver> sld_observer(
6176 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
6177 callee()->pc()->SetLocalDescription(sld_observer,
6178 callee()->CreateOfferAndWait().release());
6179 EXPECT_TRUE_WAIT(sld_observer->called(), kDefaultTimeout);
6180 EXPECT_EQ(sld_observer->error(), "");
6181
6182 rtc::scoped_refptr<MockSetSessionDescriptionObserver> srd_observer(
6183 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
6184 callee()->pc()->SetRemoteDescription(
6185 srd_observer, caller()->CreateOfferAndWait().release());
6186 EXPECT_TRUE_WAIT(srd_observer->called(), kDefaultTimeout);
6187 EXPECT_EQ(srd_observer->error(), "");
6188
6189 EXPECT_THAT(callee()->peer_connection_signaling_state_history(),
6190 ElementsAre(PeerConnectionInterface::kHaveLocalOffer,
6191 PeerConnectionInterface::kStable,
6192 PeerConnectionInterface::kHaveRemoteOffer));
6193}
6194
Mirko Bonadeic84f6612019-01-31 12:20:57 +01006195INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
6196 PeerConnectionIntegrationTest,
6197 Values(SdpSemantics::kPlanB,
6198 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08006199
Yves Gerey100fe632020-01-17 19:15:53 +01006200INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
6201 PeerConnectionIntegrationTestWithFakeClock,
6202 Values(SdpSemantics::kPlanB,
6203 SdpSemantics::kUnifiedPlan));
6204
Steve Anton74255ff2018-01-24 18:32:57 -08006205// Tests that verify interoperability between Plan B and Unified Plan
6206// PeerConnections.
6207class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08006208 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08006209 public ::testing::WithParamInterface<
6210 std::tuple<SdpSemantics, SdpSemantics>> {
6211 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08006212 // Setting the SdpSemantics for the base test to kDefault does not matter
6213 // because we specify not to use the test semantics when creating
6214 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08006215 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07006216 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08006217 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08006218 callee_semantics_(std::get<1>(GetParam())) {}
6219
6220 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07006221 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
6222 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08006223 }
6224
6225 const SdpSemantics caller_semantics_;
6226 const SdpSemantics callee_semantics_;
6227};
6228
6229TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
6230 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6231 ConnectFakeSignaling();
6232
6233 caller()->CreateAndSetAndSignalOffer();
6234 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6235}
6236
6237TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
6238 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6239 ConnectFakeSignaling();
6240 auto audio_sender = caller()->AddAudioTrack();
6241
6242 caller()->CreateAndSetAndSignalOffer();
6243 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6244
6245 // Verify that one audio receiver has been created on the remote and that it
6246 // has the same track ID as the sending track.
6247 auto receivers = callee()->pc()->GetReceivers();
6248 ASSERT_EQ(1u, receivers.size());
6249 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
6250 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
6251
Seth Hampson2f0d7022018-02-20 11:54:42 -08006252 MediaExpectations media_expectations;
6253 media_expectations.CalleeExpectsSomeAudio();
6254 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006255}
6256
6257TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
6258 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6259 ConnectFakeSignaling();
6260 auto video_sender = caller()->AddVideoTrack();
6261 auto audio_sender = caller()->AddAudioTrack();
6262
6263 caller()->CreateAndSetAndSignalOffer();
6264 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6265
6266 // Verify that one audio and one video receiver have been created on the
6267 // remote and that they have the same track IDs as the sending tracks.
6268 auto audio_receivers =
6269 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
6270 ASSERT_EQ(1u, audio_receivers.size());
6271 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
6272 auto video_receivers =
6273 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
6274 ASSERT_EQ(1u, video_receivers.size());
6275 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
6276
Seth Hampson2f0d7022018-02-20 11:54:42 -08006277 MediaExpectations media_expectations;
6278 media_expectations.CalleeExpectsSomeAudioAndVideo();
6279 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006280}
6281
6282TEST_P(PeerConnectionIntegrationInteropTest,
6283 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
6284 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6285 ConnectFakeSignaling();
6286 caller()->AddAudioVideoTracks();
6287 callee()->AddAudioVideoTracks();
6288
6289 caller()->CreateAndSetAndSignalOffer();
6290 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6291
Seth Hampson2f0d7022018-02-20 11:54:42 -08006292 MediaExpectations media_expectations;
6293 media_expectations.ExpectBidirectionalAudioAndVideo();
6294 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006295}
6296
6297TEST_P(PeerConnectionIntegrationInteropTest,
6298 ReverseRolesOneAudioLocalToOneVideoRemote) {
6299 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6300 ConnectFakeSignaling();
6301 caller()->AddAudioTrack();
6302 callee()->AddVideoTrack();
6303
6304 caller()->CreateAndSetAndSignalOffer();
6305 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6306
6307 // Verify that only the audio track has been negotiated.
6308 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
6309 // Might also check that the callee's NegotiationNeeded flag is set.
6310
6311 // Reverse roles.
6312 callee()->CreateAndSetAndSignalOffer();
6313 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6314
Seth Hampson2f0d7022018-02-20 11:54:42 -08006315 MediaExpectations media_expectations;
6316 media_expectations.CallerExpectsSomeVideo();
6317 media_expectations.CalleeExpectsSomeAudio();
6318 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006319}
6320
Mirko Bonadeic84f6612019-01-31 12:20:57 +01006321INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07006322 PeerConnectionIntegrationTest,
6323 PeerConnectionIntegrationInteropTest,
6324 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
6325 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
6326
6327// Test that if the Unified Plan side offers two video tracks then the Plan B
6328// side will only see the first one and ignore the second.
6329TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07006330 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
6331 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08006332 ConnectFakeSignaling();
6333 auto first_sender = caller()->AddVideoTrack();
6334 caller()->AddVideoTrack();
6335
6336 caller()->CreateAndSetAndSignalOffer();
6337 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6338
6339 // Verify that there is only one receiver and it corresponds to the first
6340 // added track.
6341 auto receivers = callee()->pc()->GetReceivers();
6342 ASSERT_EQ(1u, receivers.size());
6343 EXPECT_TRUE(receivers[0]->track()->enabled());
6344 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
6345
Seth Hampson2f0d7022018-02-20 11:54:42 -08006346 MediaExpectations media_expectations;
6347 media_expectations.CalleeExpectsSomeVideo();
6348 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006349}
6350
Steve Anton2bed3972019-01-04 17:04:30 -08006351// Test that if the initial offer tagged BUNDLE section is rejected due to its
6352// associated RtpTransceiver being stopped and another transceiver is added,
6353// then renegotiation causes the callee to receive the new video track without
6354// error.
6355// This is a regression test for bugs.webrtc.org/9954
6356TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6357 ReOfferWithStoppedBundleTaggedTransceiver) {
6358 RTCConfiguration config;
6359 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
6360 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
6361 ConnectFakeSignaling();
6362 auto audio_transceiver_or_error =
6363 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
6364 ASSERT_TRUE(audio_transceiver_or_error.ok());
6365 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
6366
6367 caller()->CreateAndSetAndSignalOffer();
6368 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6369 {
6370 MediaExpectations media_expectations;
6371 media_expectations.CalleeExpectsSomeAudio();
6372 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6373 }
6374
6375 audio_transceiver->Stop();
6376 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
6377
6378 caller()->CreateAndSetAndSignalOffer();
6379 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6380 {
6381 MediaExpectations media_expectations;
6382 media_expectations.CalleeExpectsSomeVideo();
6383 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6384 }
6385}
6386
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006387#ifdef HAVE_SCTP
6388
6389TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6390 EndToEndCallWithBundledSctpDataChannel) {
6391 ASSERT_TRUE(CreatePeerConnectionWrappers());
6392 ConnectFakeSignaling();
6393 caller()->CreateDataChannel();
6394 caller()->AddAudioVideoTracks();
6395 callee()->AddAudioVideoTracks();
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006396 caller()->CreateAndSetAndSignalOffer();
6397 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01006398 ASSERT_EQ_WAIT(SctpTransportState::kConnected,
6399 caller()->pc()->GetSctpTransport()->Information().state(),
6400 kDefaultTimeout);
6401 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
6402 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6403}
6404
6405TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6406 EndToEndCallWithDataChannelOnlyConnects) {
6407 ASSERT_TRUE(CreatePeerConnectionWrappers());
6408 ConnectFakeSignaling();
6409 caller()->CreateDataChannel();
6410 caller()->CreateAndSetAndSignalOffer();
6411 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6412 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
6413 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6414 ASSERT_TRUE(caller()->data_observer()->IsOpen());
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006415}
6416
Harald Alvestrand2697ac12019-12-16 10:37:04 +01006417TEST_F(PeerConnectionIntegrationTestUnifiedPlan, DataChannelClosesWhenClosed) {
6418 ASSERT_TRUE(CreatePeerConnectionWrappers());
6419 ConnectFakeSignaling();
6420 caller()->CreateDataChannel();
6421 caller()->CreateAndSetAndSignalOffer();
6422 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6423 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6424 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6425 caller()->data_channel()->Close();
6426 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
6427}
6428
6429TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6430 DataChannelClosesWhenClosedReverse) {
6431 ASSERT_TRUE(CreatePeerConnectionWrappers());
6432 ConnectFakeSignaling();
6433 caller()->CreateDataChannel();
6434 caller()->CreateAndSetAndSignalOffer();
6435 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6436 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6437 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6438 callee()->data_channel()->Close();
6439 ASSERT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
6440}
6441
6442TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6443 DataChannelClosesWhenPeerConnectionClosed) {
6444 ASSERT_TRUE(CreatePeerConnectionWrappers());
6445 ConnectFakeSignaling();
6446 caller()->CreateDataChannel();
6447 caller()->CreateAndSetAndSignalOffer();
6448 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6449 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6450 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6451 caller()->pc()->Close();
6452 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
6453}
6454
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006455#endif // HAVE_SCTP
6456
deadbeef1dcb1642017-03-29 21:08:16 -07006457} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01006458} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07006459
6460#endif // if !defined(THREAD_SANITIZER)