blob: 9ecb8b2ab695217c3f72b15ac9e41646fa926190 [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 Kron3e983682020-03-29 22:17:00 +0200217 /*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 }
Eldar Rellod9ebe012020-03-18 20:41:45 +0200597 bool Rollback() {
598 return SetRemoteDescription(
599 webrtc::CreateSessionDescription(SdpType::kRollback, ""));
600 }
Eldar Rello5ab79e62019-10-09 18:29:44 +0300601
deadbeef1dcb1642017-03-29 21:08:16 -0700602 private:
603 explicit PeerConnectionWrapper(const std::string& debug_name)
604 : debug_name_(debug_name) {}
605
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800606 bool Init(
607 const PeerConnectionFactory::Options* options,
608 const PeerConnectionInterface::RTCConfiguration* config,
609 webrtc::PeerConnectionDependencies dependencies,
610 rtc::Thread* network_thread,
611 rtc::Thread* worker_thread,
612 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron3e983682020-03-29 22:17:00 +0200613 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory,
614 bool reset_encoder_factory,
615 bool reset_decoder_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700616 // There's an error in this test code if Init ends up being called twice.
617 RTC_DCHECK(!peer_connection_);
618 RTC_DCHECK(!peer_connection_factory_);
619
620 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700621 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700622
623 std::unique_ptr<cricket::PortAllocator> port_allocator(
624 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700625 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700626 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
627 if (!fake_audio_capture_module_) {
628 return false;
629 }
deadbeef1dcb1642017-03-29 21:08:16 -0700630 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700631
632 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
633 pc_factory_dependencies.network_thread = network_thread;
634 pc_factory_dependencies.worker_thread = worker_thread;
635 pc_factory_dependencies.signaling_thread = signaling_thread;
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200636 pc_factory_dependencies.task_queue_factory =
637 webrtc::CreateDefaultTaskQueueFactory();
638 cricket::MediaEngineDependencies media_deps;
639 media_deps.task_queue_factory =
640 pc_factory_dependencies.task_queue_factory.get();
641 media_deps.adm = fake_audio_capture_module_;
642 webrtc::SetMediaEngineDefaults(&media_deps);
Johannes Kron3e983682020-03-29 22:17:00 +0200643
644 if (reset_encoder_factory) {
645 media_deps.video_encoder_factory.reset();
646 }
647 if (reset_decoder_factory) {
648 media_deps.video_decoder_factory.reset();
649 }
650
Qingsi Wang7685e862018-06-11 20:15:46 -0700651 pc_factory_dependencies.media_engine =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200652 cricket::CreateMediaEngine(std::move(media_deps));
Qingsi Wang7685e862018-06-11 20:15:46 -0700653 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
654 if (event_log_factory) {
655 event_log_factory_ = event_log_factory.get();
656 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
657 } else {
658 pc_factory_dependencies.event_log_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200659 std::make_unique<webrtc::RtcEventLogFactory>(
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200660 pc_factory_dependencies.task_queue_factory.get());
Qingsi Wang7685e862018-06-11 20:15:46 -0700661 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800662 if (media_transport_factory) {
663 pc_factory_dependencies.media_transport_factory =
664 std::move(media_transport_factory);
665 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700666 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
667 std::move(pc_factory_dependencies));
668
deadbeef1dcb1642017-03-29 21:08:16 -0700669 if (!peer_connection_factory_) {
670 return false;
671 }
672 if (options) {
673 peer_connection_factory_->SetOptions(*options);
674 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800675 if (config) {
676 sdp_semantics_ = config->sdp_semantics;
677 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700678
679 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200680 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700681 return peer_connection_.get() != nullptr;
682 }
683
684 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700685 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700686 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700687 PeerConnectionInterface::RTCConfiguration modified_config;
688 // If |config| is null, this will result in a default configuration being
689 // used.
690 if (config) {
691 modified_config = *config;
692 }
693 // Disable resolution adaptation; we don't want it interfering with the
694 // test results.
695 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
696 // ratios and not specific resolutions, is this even necessary?
697 modified_config.set_cpu_adaptation(false);
698
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700699 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700700 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700701 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700702 }
703
704 void set_signaling_message_receiver(
705 SignalingMessageReceiver* signaling_message_receiver) {
706 signaling_message_receiver_ = signaling_message_receiver;
707 }
708
709 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
710
Steve Antonede9ca52017-10-16 13:04:27 -0700711 void set_signal_ice_candidates(bool signal) {
712 signal_ice_candidates_ = signal;
713 }
714
deadbeef1dcb1642017-03-29 21:08:16 -0700715 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200716 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700717 // Set max frame rate to 10fps to reduce the risk of test flakiness.
718 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200719 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700720
Niels Möller5c7efe72018-05-11 10:34:46 +0200721 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200722 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
723 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700724 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200725 peer_connection_factory_->CreateVideoTrack(
726 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700727 if (!local_video_renderer_) {
728 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
729 }
730 return track;
731 }
732
733 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100734 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800735 std::unique_ptr<SessionDescriptionInterface> desc =
736 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700737 if (received_sdp_munger_) {
738 received_sdp_munger_(desc->description());
739 }
740
741 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
742 // Setting a remote description may have changed the number of receivers,
743 // so reset the receiver observers.
744 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800745 if (remote_offer_handler_) {
746 remote_offer_handler_();
747 }
deadbeef1dcb1642017-03-29 21:08:16 -0700748 auto answer = CreateAnswer();
749 ASSERT_NE(nullptr, answer);
750 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
751 }
752
753 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100754 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800755 std::unique_ptr<SessionDescriptionInterface> desc =
756 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700757 if (received_sdp_munger_) {
758 received_sdp_munger_(desc->description());
759 }
760
761 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
762 // Set the RtpReceiverObserver after receivers are created.
763 ResetRtpReceiverObservers();
764 }
765
766 // Returns null on failure.
deadbeef1dcb1642017-03-29 21:08:16 -0700767 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
768 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
769 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
770 pc()->CreateAnswer(observer, offer_answer_options_);
771 return WaitForDescriptionFromObserver(observer);
772 }
773
774 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100775 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700776 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
777 if (!observer->result()) {
778 return nullptr;
779 }
780 auto description = observer->MoveDescription();
781 if (generated_sdp_munger_) {
782 generated_sdp_munger_(description->description());
783 }
784 return description;
785 }
786
787 // Setting the local description and sending the SDP message over the fake
788 // signaling channel are combined into the same method because the SDP
789 // message needs to be sent as soon as SetLocalDescription finishes, without
790 // waiting for the observer to be called. This ensures that ICE candidates
791 // don't outrace the description.
792 bool SetLocalDescriptionAndSendSdpMessage(
793 std::unique_ptr<SessionDescriptionInterface> desc) {
794 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
795 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100796 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800797 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700798 std::string sdp;
799 EXPECT_TRUE(desc->ToString(&sdp));
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700800 RTC_LOG(LS_INFO) << debug_name_ << ": local SDP contents=\n" << sdp;
deadbeef1dcb1642017-03-29 21:08:16 -0700801 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800802 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
803 RemoveUnusedVideoRenderers();
804 }
deadbeef1dcb1642017-03-29 21:08:16 -0700805 // As mentioned above, we need to send the message immediately after
806 // SetLocalDescription.
807 SendSdpMessage(type, sdp);
808 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
809 return true;
810 }
811
812 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
813 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
814 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100815 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700816 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800817 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
818 RemoveUnusedVideoRenderers();
819 }
deadbeef1dcb1642017-03-29 21:08:16 -0700820 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
821 return observer->result();
822 }
823
Seth Hampson2f0d7022018-02-20 11:54:42 -0800824 // This is a work around to remove unused fake_video_renderers from
825 // transceivers that have either stopped or are no longer receiving.
826 void RemoveUnusedVideoRenderers() {
827 auto transceivers = pc()->GetTransceivers();
828 for (auto& transceiver : transceivers) {
829 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
830 continue;
831 }
832 // Remove fake video renderers from any stopped transceivers.
833 if (transceiver->stopped()) {
834 auto it =
835 fake_video_renderers_.find(transceiver->receiver()->track()->id());
836 if (it != fake_video_renderers_.end()) {
837 fake_video_renderers_.erase(it);
838 }
839 }
840 // Remove fake video renderers from any transceivers that are no longer
841 // receiving.
842 if ((transceiver->current_direction() &&
843 !webrtc::RtpTransceiverDirectionHasRecv(
844 *transceiver->current_direction()))) {
845 auto it =
846 fake_video_renderers_.find(transceiver->receiver()->track()->id());
847 if (it != fake_video_renderers_.end()) {
848 fake_video_renderers_.erase(it);
849 }
850 }
851 }
852 }
853
deadbeef1dcb1642017-03-29 21:08:16 -0700854 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
855 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800856 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700857 if (signaling_delay_ms_ == 0) {
858 RelaySdpMessageIfReceiverExists(type, msg);
859 } else {
860 invoker_.AsyncInvokeDelayed<void>(
861 RTC_FROM_HERE, rtc::Thread::Current(),
862 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
863 this, type, msg),
864 signaling_delay_ms_);
865 }
866 }
867
Steve Antona3a92c22017-12-07 10:27:41 -0800868 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700869 if (signaling_message_receiver_) {
870 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
871 }
872 }
873
874 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
875 // default).
876 void SendIceMessage(const std::string& sdp_mid,
877 int sdp_mline_index,
878 const std::string& msg) {
879 if (signaling_delay_ms_ == 0) {
880 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
881 } else {
882 invoker_.AsyncInvokeDelayed<void>(
883 RTC_FROM_HERE, rtc::Thread::Current(),
884 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
885 this, sdp_mid, sdp_mline_index, msg),
886 signaling_delay_ms_);
887 }
888 }
889
890 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
891 int sdp_mline_index,
892 const std::string& msg) {
893 if (signaling_message_receiver_) {
894 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
895 msg);
896 }
897 }
898
899 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800900 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
901 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700902 HandleIncomingOffer(msg);
903 } else {
904 HandleIncomingAnswer(msg);
905 }
906 }
907
908 void ReceiveIceMessage(const std::string& sdp_mid,
909 int sdp_mline_index,
910 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100911 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700912 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
913 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
914 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
915 }
916
917 // PeerConnectionObserver callbacks.
918 void OnSignalingChange(
919 webrtc::PeerConnectionInterface::SignalingState new_state) override {
920 EXPECT_EQ(pc()->signaling_state(), new_state);
Eldar Rello5ab79e62019-10-09 18:29:44 +0300921 peer_connection_signaling_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700922 }
Steve Anton15324772018-01-16 10:26:49 -0800923 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
924 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
925 streams) override {
926 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
927 rtc::scoped_refptr<VideoTrackInterface> video_track(
928 static_cast<VideoTrackInterface*>(receiver->track().get()));
929 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700930 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800931 fake_video_renderers_[video_track->id()] =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200932 std::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700933 }
934 }
Steve Anton15324772018-01-16 10:26:49 -0800935 void OnRemoveTrack(
936 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
937 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
938 auto it = fake_video_renderers_.find(receiver->track()->id());
939 RTC_DCHECK(it != fake_video_renderers_.end());
940 fake_video_renderers_.erase(it);
941 }
942 }
deadbeef1dcb1642017-03-29 21:08:16 -0700943 void OnRenegotiationNeeded() override {}
944 void OnIceConnectionChange(
945 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
946 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700947 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700948 }
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100949 void OnStandardizedIceConnectionChange(
950 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
951 standardized_ice_connection_state_history_.push_back(new_state);
952 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200953 void OnConnectionChange(
954 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
955 peer_connection_state_history_.push_back(new_state);
956 }
957
deadbeef1dcb1642017-03-29 21:08:16 -0700958 void OnIceGatheringChange(
959 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700960 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700961 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700962 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700963
964 void OnIceSelectedCandidatePairChanged(
965 const cricket::CandidatePairChangeEvent& event) {
966 ice_candidate_pair_change_history_.push_back(event);
967 }
Alex Drake43faee02019-08-12 16:27:34 -0700968
deadbeef1dcb1642017-03-29 21:08:16 -0700969 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100970 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700971
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800972 if (remote_async_resolver_) {
973 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800974 if (local_candidate.address().IsUnresolvedIP()) {
975 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
976 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700977 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800978 local_candidate.address().hostname());
979 RTC_DCHECK(!resolved_ip.IsNil());
980 resolved_addr.SetResolvedIP(resolved_ip);
981 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
982 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
983 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700984 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700985 }
986
deadbeef1dcb1642017-03-29 21:08:16 -0700987 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800988 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700989 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700990 // Remote party may be deleted.
991 return;
992 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800993 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700994 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700995 }
Eldar Rello0095d372019-12-02 22:22:07 +0200996 void OnIceCandidateError(const std::string& address,
997 int port,
Eldar Relloda13ea22019-06-01 12:23:43 +0300998 const std::string& url,
999 int error_code,
1000 const std::string& error_text) override {
Eldar Rello0095d372019-12-02 22:22:07 +02001001 error_event_ = cricket::IceCandidateErrorEvent(address, port, url,
Eldar Relloda13ea22019-06-01 12:23:43 +03001002 error_code, error_text);
1003 }
deadbeef1dcb1642017-03-29 21:08:16 -07001004 void OnDataChannel(
1005 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001006 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -07001007 data_channel_ = data_channel;
1008 data_observer_.reset(new MockDataChannelObserver(data_channel));
1009 }
1010
deadbeef1dcb1642017-03-29 21:08:16 -07001011 std::string debug_name_;
1012
1013 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -07001014 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
1015 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001016
1017 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
1018 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
1019 peer_connection_factory_;
1020
Steve Antonede9ca52017-10-16 13:04:27 -07001021 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -07001022 // Needed to keep track of number of frames sent.
1023 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1024 // Needed to keep track of number of frames received.
1025 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1026 fake_video_renderers_;
1027 // Needed to ensure frames aren't received for removed tracks.
1028 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1029 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001030
1031 // For remote peer communication.
1032 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1033 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001034 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001035 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001036 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001037
Niels Möller5c7efe72018-05-11 10:34:46 +02001038 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001039 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001040 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1041 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001042 // |local_video_renderer_| attached to the first created local video track.
1043 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1044
Seth Hampson2f0d7022018-02-20 11:54:42 -08001045 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001046 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1047 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1048 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001049 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001050 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001051 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1052 std::unique_ptr<MockDataChannelObserver> data_observer_;
1053
1054 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1055
Steve Antonede9ca52017-10-16 13:04:27 -07001056 std::vector<PeerConnectionInterface::IceConnectionState>
1057 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001058 std::vector<PeerConnectionInterface::IceConnectionState>
1059 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001060 std::vector<PeerConnectionInterface::PeerConnectionState>
1061 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001062 std::vector<PeerConnectionInterface::IceGatheringState>
1063 ice_gathering_state_history_;
Alex Drake00c7ecf2019-08-06 10:54:47 -07001064 std::vector<cricket::CandidatePairChangeEvent>
1065 ice_candidate_pair_change_history_;
Eldar Rello5ab79e62019-10-09 18:29:44 +03001066 std::vector<PeerConnectionInterface::SignalingState>
1067 peer_connection_signaling_state_history_;
Qingsi Wang7685e862018-06-11 20:15:46 -07001068 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1069
deadbeef1dcb1642017-03-29 21:08:16 -07001070 rtc::AsyncInvoker invoker_;
1071
Seth Hampson2f0d7022018-02-20 11:54:42 -08001072 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001073};
1074
Elad Alon99c3fe52017-10-13 16:29:40 +02001075class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1076 public:
1077 virtual ~MockRtcEventLogOutput() = default;
1078 MOCK_CONST_METHOD0(IsActive, bool());
1079 MOCK_METHOD1(Write, bool(const std::string&));
1080};
1081
Seth Hampson2f0d7022018-02-20 11:54:42 -08001082// This helper object is used for both specifying how many audio/video frames
1083// are expected to be received for a caller/callee. It provides helper functions
1084// to specify these expectations. The object initially starts in a state of no
1085// expectations.
1086class MediaExpectations {
1087 public:
1088 enum ExpectFrames {
1089 kExpectSomeFrames,
1090 kExpectNoFrames,
1091 kNoExpectation,
1092 };
1093
1094 void ExpectBidirectionalAudioAndVideo() {
1095 ExpectBidirectionalAudio();
1096 ExpectBidirectionalVideo();
1097 }
1098
1099 void ExpectBidirectionalAudio() {
1100 CallerExpectsSomeAudio();
1101 CalleeExpectsSomeAudio();
1102 }
1103
1104 void ExpectNoAudio() {
1105 CallerExpectsNoAudio();
1106 CalleeExpectsNoAudio();
1107 }
1108
1109 void ExpectBidirectionalVideo() {
1110 CallerExpectsSomeVideo();
1111 CalleeExpectsSomeVideo();
1112 }
1113
1114 void ExpectNoVideo() {
1115 CallerExpectsNoVideo();
1116 CalleeExpectsNoVideo();
1117 }
1118
1119 void CallerExpectsSomeAudioAndVideo() {
1120 CallerExpectsSomeAudio();
1121 CallerExpectsSomeVideo();
1122 }
1123
1124 void CalleeExpectsSomeAudioAndVideo() {
1125 CalleeExpectsSomeAudio();
1126 CalleeExpectsSomeVideo();
1127 }
1128
1129 // Caller's audio functions.
1130 void CallerExpectsSomeAudio(
1131 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1132 caller_audio_expectation_ = kExpectSomeFrames;
1133 caller_audio_frames_expected_ = expected_audio_frames;
1134 }
1135
1136 void CallerExpectsNoAudio() {
1137 caller_audio_expectation_ = kExpectNoFrames;
1138 caller_audio_frames_expected_ = 0;
1139 }
1140
1141 // Caller's video functions.
1142 void CallerExpectsSomeVideo(
1143 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1144 caller_video_expectation_ = kExpectSomeFrames;
1145 caller_video_frames_expected_ = expected_video_frames;
1146 }
1147
1148 void CallerExpectsNoVideo() {
1149 caller_video_expectation_ = kExpectNoFrames;
1150 caller_video_frames_expected_ = 0;
1151 }
1152
1153 // Callee's audio functions.
1154 void CalleeExpectsSomeAudio(
1155 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1156 callee_audio_expectation_ = kExpectSomeFrames;
1157 callee_audio_frames_expected_ = expected_audio_frames;
1158 }
1159
1160 void CalleeExpectsNoAudio() {
1161 callee_audio_expectation_ = kExpectNoFrames;
1162 callee_audio_frames_expected_ = 0;
1163 }
1164
1165 // Callee's video functions.
1166 void CalleeExpectsSomeVideo(
1167 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1168 callee_video_expectation_ = kExpectSomeFrames;
1169 callee_video_frames_expected_ = expected_video_frames;
1170 }
1171
1172 void CalleeExpectsNoVideo() {
1173 callee_video_expectation_ = kExpectNoFrames;
1174 callee_video_frames_expected_ = 0;
1175 }
1176
1177 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1178 ExpectFrames caller_video_expectation_ = kNoExpectation;
1179 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1180 ExpectFrames callee_video_expectation_ = kNoExpectation;
1181 int caller_audio_frames_expected_ = 0;
1182 int caller_video_frames_expected_ = 0;
1183 int callee_audio_frames_expected_ = 0;
1184 int callee_video_frames_expected_ = 0;
1185};
1186
Qingsi Wang25ec8882019-11-15 12:33:05 -08001187class MockIceTransport : public webrtc::IceTransportInterface {
1188 public:
1189 MockIceTransport(const std::string& name, int component)
1190 : internal_(std::make_unique<cricket::FakeIceTransport>(
1191 name,
1192 component,
1193 nullptr /* network_thread */)) {}
1194 ~MockIceTransport() = default;
1195 cricket::IceTransportInternal* internal() { return internal_.get(); }
1196
1197 private:
1198 std::unique_ptr<cricket::FakeIceTransport> internal_;
1199};
1200
1201class MockIceTransportFactory : public IceTransportFactory {
1202 public:
1203 ~MockIceTransportFactory() override = default;
1204 rtc::scoped_refptr<IceTransportInterface> CreateIceTransport(
1205 const std::string& transport_name,
1206 int component,
1207 IceTransportInit init) {
1208 RecordIceTransportCreated();
1209 return new rtc::RefCountedObject<MockIceTransport>(transport_name,
1210 component);
1211 }
1212 MOCK_METHOD0(RecordIceTransportCreated, void());
1213};
1214
deadbeef1dcb1642017-03-29 21:08:16 -07001215// Tests two PeerConnections connecting to each other end-to-end, using a
1216// virtual network, fake A/V capture and fake encoder/decoders. The
1217// PeerConnections share the threads/socket servers, but use separate versions
1218// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001219class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001220 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001221 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1222 : sdp_semantics_(sdp_semantics),
1223 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001224 fss_(new rtc::FirewallSocketServer(ss_.get())),
1225 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001226 worker_thread_(rtc::Thread::Create()),
1227 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001228 network_thread_->SetName("PCNetworkThread", this);
1229 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001230 RTC_CHECK(network_thread_->Start());
1231 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001232 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001233 }
1234
Seth Hampson2f0d7022018-02-20 11:54:42 -08001235 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001236 // The PeerConnections should deleted before the TurnCustomizers.
1237 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1238 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1239 // that the TurnCustomizer outlives the life of the PeerConnection or else
1240 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001241 if (caller_) {
1242 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001243 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001244 }
1245 if (callee_) {
1246 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001247 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001248 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001249
1250 // If turn servers were created for the test they need to be destroyed on
1251 // the network thread.
1252 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1253 turn_servers_.clear();
1254 turn_customizers_.clear();
1255 });
deadbeef1dcb1642017-03-29 21:08:16 -07001256 }
1257
1258 bool SignalingStateStable() {
1259 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1260 }
1261
deadbeef71452802017-05-07 17:21:01 -07001262 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001263 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1264 // are connected. This is an important distinction. Once we have separate
1265 // ICE and DTLS state, this check needs to use the DTLS state.
1266 return (callee()->ice_connection_state() ==
1267 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1268 callee()->ice_connection_state() ==
1269 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1270 (caller()->ice_connection_state() ==
1271 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1272 caller()->ice_connection_state() ==
1273 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001274 }
1275
Qingsi Wang7685e862018-06-11 20:15:46 -07001276 // When |event_log_factory| is null, the default implementation of the event
1277 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001278 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1279 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001280 const PeerConnectionFactory::Options* options,
1281 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001282 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001283 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron3e983682020-03-29 22:17:00 +02001284 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory,
1285 bool reset_encoder_factory,
1286 bool reset_decoder_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001287 RTCConfiguration modified_config;
1288 if (config) {
1289 modified_config = *config;
1290 }
Steve Anton3acffc32018-04-12 17:21:03 -07001291 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001292 if (!dependencies.cert_generator) {
1293 dependencies.cert_generator =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001294 std::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001295 }
1296 std::unique_ptr<PeerConnectionWrapper> client(
1297 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001298
Niels Möllerf06f9232018-08-07 12:32:18 +02001299 if (!client->Init(options, &modified_config, std::move(dependencies),
1300 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001301 std::move(event_log_factory),
Johannes Kron3e983682020-03-29 22:17:00 +02001302 std::move(media_transport_factory), reset_encoder_factory,
1303 reset_decoder_factory)) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001304 return nullptr;
1305 }
1306 return client;
1307 }
1308
Qingsi Wang7685e862018-06-11 20:15:46 -07001309 std::unique_ptr<PeerConnectionWrapper>
1310 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1311 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001312 const PeerConnectionFactory::Options* options,
1313 const RTCConfiguration* config,
1314 webrtc::PeerConnectionDependencies dependencies) {
1315 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1316 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Johannes Kron3e983682020-03-29 22:17:00 +02001317 return CreatePeerConnectionWrapper(
1318 debug_name, options, config, std::move(dependencies),
1319 std::move(event_log_factory),
1320 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1321 /*reset_decoder_factory=*/false);
Qingsi Wang7685e862018-06-11 20:15:46 -07001322 }
1323
deadbeef1dcb1642017-03-29 21:08:16 -07001324 bool CreatePeerConnectionWrappers() {
1325 return CreatePeerConnectionWrappersWithConfig(
1326 PeerConnectionInterface::RTCConfiguration(),
1327 PeerConnectionInterface::RTCConfiguration());
1328 }
1329
Steve Anton3acffc32018-04-12 17:21:03 -07001330 bool CreatePeerConnectionWrappersWithSdpSemantics(
1331 SdpSemantics caller_semantics,
1332 SdpSemantics callee_semantics) {
1333 // Can't specify the sdp_semantics in the passed-in configuration since it
1334 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1335 // stored in sdp_semantics_. So get around this by modifying the instance
1336 // variable before calling CreatePeerConnectionWrapper for the caller and
1337 // callee PeerConnections.
1338 SdpSemantics original_semantics = sdp_semantics_;
1339 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001340 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001341 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Johannes Kron3e983682020-03-29 22:17:00 +02001342 nullptr, /*media_transport_factory=*/nullptr,
1343 /*reset_encoder_factory=*/false,
1344 /*reset_decoder_factory=*/false);
Steve Anton3acffc32018-04-12 17:21:03 -07001345 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001346 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001347 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Johannes Kron3e983682020-03-29 22:17:00 +02001348 nullptr, /*media_transport_factory=*/nullptr,
1349 /*reset_encoder_factory=*/false,
1350 /*reset_decoder_factory=*/false);
Steve Anton3acffc32018-04-12 17:21:03 -07001351 sdp_semantics_ = original_semantics;
1352 return caller_ && callee_;
1353 }
1354
deadbeef1dcb1642017-03-29 21:08:16 -07001355 bool CreatePeerConnectionWrappersWithConfig(
1356 const PeerConnectionInterface::RTCConfiguration& caller_config,
1357 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001358 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001359 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001360 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001361 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1362 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001363 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001364 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001365 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001366 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1367 /*reset_decoder_factory=*/false);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001368 return caller_ && callee_;
1369 }
1370
1371 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1372 const PeerConnectionInterface::RTCConfiguration& caller_config,
1373 const PeerConnectionInterface::RTCConfiguration& callee_config,
1374 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1375 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
Johannes Kron3e983682020-03-29 22:17:00 +02001376 caller_ = CreatePeerConnectionWrapper(
1377 "Caller", nullptr, &caller_config,
1378 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1379 std::move(caller_factory), /*reset_encoder_factory=*/false,
1380 /*reset_decoder_factory=*/false);
1381 callee_ = CreatePeerConnectionWrapper(
1382 "Callee", nullptr, &callee_config,
1383 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1384 std::move(callee_factory), /*reset_encoder_factory=*/false,
1385 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001386 return caller_ && callee_;
1387 }
1388
1389 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1390 const PeerConnectionInterface::RTCConfiguration& caller_config,
1391 webrtc::PeerConnectionDependencies caller_dependencies,
1392 const PeerConnectionInterface::RTCConfiguration& callee_config,
1393 webrtc::PeerConnectionDependencies callee_dependencies) {
Johannes Kron3e983682020-03-29 22:17:00 +02001394 caller_ = CreatePeerConnectionWrapper(
1395 "Caller", nullptr, &caller_config, std::move(caller_dependencies),
1396 nullptr,
1397 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1398 /*reset_decoder_factory=*/false);
1399 callee_ = CreatePeerConnectionWrapper(
1400 "Callee", nullptr, &callee_config, std::move(callee_dependencies),
1401 nullptr,
1402 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1403 /*reset_decoder_factory=*/false);
deadbeef1dcb1642017-03-29 21:08:16 -07001404 return caller_ && callee_;
1405 }
1406
1407 bool CreatePeerConnectionWrappersWithOptions(
1408 const PeerConnectionFactory::Options& caller_options,
1409 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001410 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001411 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001412 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001413 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1414 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001415 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001416 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001417 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001418 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1419 /*reset_decoder_factory=*/false);
Qingsi Wang7685e862018-06-11 20:15:46 -07001420 return caller_ && callee_;
1421 }
1422
1423 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1424 PeerConnectionInterface::RTCConfiguration default_config;
1425 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001426 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001427 webrtc::PeerConnectionDependencies(nullptr));
1428 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001429 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001430 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001431 return caller_ && callee_;
1432 }
1433
Seth Hampson2f0d7022018-02-20 11:54:42 -08001434 std::unique_ptr<PeerConnectionWrapper>
1435 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001436 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1437 new FakeRTCCertificateGenerator());
1438 cert_generator->use_alternate_key();
1439
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001440 webrtc::PeerConnectionDependencies dependencies(nullptr);
1441 dependencies.cert_generator = std::move(cert_generator);
Johannes Kron3e983682020-03-29 22:17:00 +02001442 return CreatePeerConnectionWrapper(
1443 "New Peer", nullptr, nullptr, std::move(dependencies), nullptr,
1444 /*media_transport_factory=*/nullptr, /*reset_encoder_factory=*/false,
1445 /*reset_decoder_factory=*/false);
1446 }
1447
1448 bool CreateOneDirectionalPeerConnectionWrappers(bool caller_to_callee) {
1449 caller_ = CreatePeerConnectionWrapper(
1450 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1451 nullptr, /*media_transport_factory=*/nullptr,
1452 /*reset_encoder_factory=*/!caller_to_callee,
1453 /*reset_decoder_factory=*/caller_to_callee);
1454 callee_ = CreatePeerConnectionWrapper(
1455 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
1456 nullptr, /*media_transport_factory=*/nullptr,
1457 /*reset_encoder_factory=*/caller_to_callee,
1458 /*reset_decoder_factory=*/!caller_to_callee);
1459 return caller_ && callee_;
deadbeef1dcb1642017-03-29 21:08:16 -07001460 }
1461
Seth Hampsonaed71642018-06-11 07:41:32 -07001462 cricket::TestTurnServer* CreateTurnServer(
1463 rtc::SocketAddress internal_address,
1464 rtc::SocketAddress external_address,
1465 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1466 const std::string& common_name = "test turn server") {
1467 rtc::Thread* thread = network_thread();
1468 std::unique_ptr<cricket::TestTurnServer> turn_server =
1469 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1470 RTC_FROM_HERE,
1471 [thread, internal_address, external_address, type, common_name] {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001472 return std::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001473 thread, internal_address, external_address, type,
1474 /*ignore_bad_certs=*/true, common_name);
1475 });
1476 turn_servers_.push_back(std::move(turn_server));
1477 // Interactions with the turn server should be done on the network thread.
1478 return turn_servers_.back().get();
1479 }
1480
1481 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1482 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1483 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1484 RTC_FROM_HERE,
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001485 [] { return std::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001486 turn_customizers_.push_back(std::move(turn_customizer));
1487 // Interactions with the turn customizer should be done on the network
1488 // thread.
1489 return turn_customizers_.back().get();
1490 }
1491
1492 // Checks that the function counters for a TestTurnCustomizer are greater than
1493 // 0.
1494 void ExpectTurnCustomizerCountersIncremented(
1495 cricket::TestTurnCustomizer* turn_customizer) {
1496 unsigned int allow_channel_data_counter =
1497 network_thread()->Invoke<unsigned int>(
1498 RTC_FROM_HERE, [turn_customizer] {
1499 return turn_customizer->allow_channel_data_cnt_;
1500 });
1501 EXPECT_GT(allow_channel_data_counter, 0u);
1502 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1503 RTC_FROM_HERE,
1504 [turn_customizer] { return turn_customizer->modify_cnt_; });
1505 EXPECT_GT(modify_counter, 0u);
1506 }
1507
deadbeef1dcb1642017-03-29 21:08:16 -07001508 // Once called, SDP blobs and ICE candidates will be automatically signaled
1509 // between PeerConnections.
1510 void ConnectFakeSignaling() {
1511 caller_->set_signaling_message_receiver(callee_.get());
1512 callee_->set_signaling_message_receiver(caller_.get());
1513 }
1514
Steve Antonede9ca52017-10-16 13:04:27 -07001515 // Once called, SDP blobs will be automatically signaled between
1516 // PeerConnections. Note that ICE candidates will not be signaled unless they
1517 // are in the exchanged SDP blobs.
1518 void ConnectFakeSignalingForSdpOnly() {
1519 ConnectFakeSignaling();
1520 SetSignalIceCandidates(false);
1521 }
1522
deadbeef1dcb1642017-03-29 21:08:16 -07001523 void SetSignalingDelayMs(int delay_ms) {
1524 caller_->set_signaling_delay_ms(delay_ms);
1525 callee_->set_signaling_delay_ms(delay_ms);
1526 }
1527
Steve Antonede9ca52017-10-16 13:04:27 -07001528 void SetSignalIceCandidates(bool signal) {
1529 caller_->set_signal_ice_candidates(signal);
1530 callee_->set_signal_ice_candidates(signal);
1531 }
1532
deadbeef1dcb1642017-03-29 21:08:16 -07001533 // Messages may get lost on the unreliable DataChannel, so we send multiple
1534 // times to avoid test flakiness.
1535 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1536 const std::string& data,
1537 int retries) {
1538 for (int i = 0; i < retries; ++i) {
1539 dc->Send(DataBuffer(data));
1540 }
1541 }
1542
1543 rtc::Thread* network_thread() { return network_thread_.get(); }
1544
1545 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1546
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001547 webrtc::MediaTransportPair* loopback_media_transports() {
1548 return &loopback_media_transports_;
1549 }
1550
deadbeef1dcb1642017-03-29 21:08:16 -07001551 PeerConnectionWrapper* caller() { return caller_.get(); }
1552
1553 // Set the |caller_| to the |wrapper| passed in and return the
1554 // original |caller_|.
1555 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1556 PeerConnectionWrapper* wrapper) {
1557 PeerConnectionWrapper* old = caller_.release();
1558 caller_.reset(wrapper);
1559 return old;
1560 }
1561
1562 PeerConnectionWrapper* callee() { return callee_.get(); }
1563
1564 // Set the |callee_| to the |wrapper| passed in and return the
1565 // original |callee_|.
1566 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1567 PeerConnectionWrapper* wrapper) {
1568 PeerConnectionWrapper* old = callee_.release();
1569 callee_.reset(wrapper);
1570 return old;
1571 }
1572
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001573 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1574 network_thread()->Invoke<void>(
1575 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1576 caller()->port_allocator(), caller_flags));
1577 network_thread()->Invoke<void>(
1578 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1579 callee()->port_allocator(), callee_flags));
1580 }
1581
Steve Antonede9ca52017-10-16 13:04:27 -07001582 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1583
Seth Hampson2f0d7022018-02-20 11:54:42 -08001584 // Expects the provided number of new frames to be received within
1585 // kMaxWaitForFramesMs. The new expected frames are specified in
1586 // |media_expectations|. Returns false if any of the expectations were
1587 // not met.
1588 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1589 // First initialize the expected frame counts based upon the current
1590 // frame count.
1591 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1592 if (media_expectations.caller_audio_expectation_ ==
1593 MediaExpectations::kExpectSomeFrames) {
1594 total_caller_audio_frames_expected +=
1595 media_expectations.caller_audio_frames_expected_;
1596 }
1597 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001598 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001599 if (media_expectations.caller_video_expectation_ ==
1600 MediaExpectations::kExpectSomeFrames) {
1601 total_caller_video_frames_expected +=
1602 media_expectations.caller_video_frames_expected_;
1603 }
1604 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1605 if (media_expectations.callee_audio_expectation_ ==
1606 MediaExpectations::kExpectSomeFrames) {
1607 total_callee_audio_frames_expected +=
1608 media_expectations.callee_audio_frames_expected_;
1609 }
1610 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001611 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001612 if (media_expectations.callee_video_expectation_ ==
1613 MediaExpectations::kExpectSomeFrames) {
1614 total_callee_video_frames_expected +=
1615 media_expectations.callee_video_frames_expected_;
1616 }
deadbeef1dcb1642017-03-29 21:08:16 -07001617
Seth Hampson2f0d7022018-02-20 11:54:42 -08001618 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001619 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001620 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001621 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001622 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001623 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001624 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001625 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001626 total_callee_video_frames_expected,
1627 kMaxWaitForFramesMs);
1628 bool expectations_correct =
1629 caller()->audio_frames_received() >=
1630 total_caller_audio_frames_expected &&
1631 caller()->min_video_frames_received_per_track() >=
1632 total_caller_video_frames_expected &&
1633 callee()->audio_frames_received() >=
1634 total_callee_audio_frames_expected &&
1635 callee()->min_video_frames_received_per_track() >=
1636 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001637
Seth Hampson2f0d7022018-02-20 11:54:42 -08001638 // After the combined wait, print out a more detailed message upon
1639 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001640 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001641 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001642 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001643 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001644 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001645 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001646 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001647 total_callee_video_frames_expected);
1648
1649 // We want to make sure nothing unexpected was received.
1650 if (media_expectations.caller_audio_expectation_ ==
1651 MediaExpectations::kExpectNoFrames) {
1652 EXPECT_EQ(caller()->audio_frames_received(),
1653 total_caller_audio_frames_expected);
1654 if (caller()->audio_frames_received() !=
1655 total_caller_audio_frames_expected) {
1656 expectations_correct = false;
1657 }
1658 }
1659 if (media_expectations.caller_video_expectation_ ==
1660 MediaExpectations::kExpectNoFrames) {
1661 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1662 total_caller_video_frames_expected);
1663 if (caller()->min_video_frames_received_per_track() !=
1664 total_caller_video_frames_expected) {
1665 expectations_correct = false;
1666 }
1667 }
1668 if (media_expectations.callee_audio_expectation_ ==
1669 MediaExpectations::kExpectNoFrames) {
1670 EXPECT_EQ(callee()->audio_frames_received(),
1671 total_callee_audio_frames_expected);
1672 if (callee()->audio_frames_received() !=
1673 total_callee_audio_frames_expected) {
1674 expectations_correct = false;
1675 }
1676 }
1677 if (media_expectations.callee_video_expectation_ ==
1678 MediaExpectations::kExpectNoFrames) {
1679 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1680 total_callee_video_frames_expected);
1681 if (callee()->min_video_frames_received_per_track() !=
1682 total_callee_video_frames_expected) {
1683 expectations_correct = false;
1684 }
1685 }
1686 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001687 }
1688
Steve Antond91969e2019-05-30 12:27:03 -07001689 void ClosePeerConnections() {
1690 caller()->pc()->Close();
1691 callee()->pc()->Close();
1692 }
1693
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001694 void TestNegotiatedCipherSuite(
1695 const PeerConnectionFactory::Options& caller_options,
1696 const PeerConnectionFactory::Options& callee_options,
1697 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001698 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1699 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001700 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001701 caller()->AddAudioVideoTracks();
1702 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001703 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001704 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001705 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001706 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001707 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01001708 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
1709 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1710 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001711 }
1712
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001713 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1714 bool remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001715 bool aes_ctr_enabled,
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001716 int expected_cipher_suite) {
1717 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001718 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1719 local_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001720 caller_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1721 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001722 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001723 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1724 remote_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001725 callee_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1726 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001727 TestNegotiatedCipherSuite(caller_options, callee_options,
1728 expected_cipher_suite);
1729 }
1730
Seth Hampson2f0d7022018-02-20 11:54:42 -08001731 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001732 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001733
deadbeef1dcb1642017-03-29 21:08:16 -07001734 private:
1735 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001736 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001737 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001738 // |network_thread_| and |worker_thread_| are used by both
1739 // |caller_| and |callee_| so they must be destroyed
1740 // later.
1741 std::unique_ptr<rtc::Thread> network_thread_;
1742 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001743 // The turn servers and turn customizers should be accessed & deleted on the
1744 // network thread to avoid a race with the socket read/write that occurs
1745 // on the network thread.
1746 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1747 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001748 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001749 std::unique_ptr<PeerConnectionWrapper> caller_;
1750 std::unique_ptr<PeerConnectionWrapper> callee_;
1751};
1752
Seth Hampson2f0d7022018-02-20 11:54:42 -08001753class PeerConnectionIntegrationTest
1754 : public PeerConnectionIntegrationBaseTest,
1755 public ::testing::WithParamInterface<SdpSemantics> {
1756 protected:
1757 PeerConnectionIntegrationTest()
1758 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1759};
1760
Yves Gerey100fe632020-01-17 19:15:53 +01001761// Fake clock must be set before threads are started to prevent race on
1762// Set/GetClockForTesting().
1763// To achieve that, multiple inheritance is used as a mixin pattern
1764// where order of construction is finely controlled.
1765// This also ensures peerconnection is closed before switching back to non-fake
1766// clock, avoiding other races and DCHECK failures such as in rtp_sender.cc.
1767class FakeClockForTest : public rtc::ScopedFakeClock {
1768 protected:
1769 FakeClockForTest() {
1770 // Some things use a time of "0" as a special value, so we need to start out
1771 // the fake clock at a nonzero time.
1772 // TODO(deadbeef): Fix this.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001773 AdvanceTime(webrtc::TimeDelta::Seconds(1));
Yves Gerey100fe632020-01-17 19:15:53 +01001774 }
1775
1776 // Explicit handle.
1777 ScopedFakeClock& FakeClock() { return *this; }
1778};
1779
1780// Ensure FakeClockForTest is constructed first (see class for rationale).
1781class PeerConnectionIntegrationTestWithFakeClock
1782 : public FakeClockForTest,
1783 public PeerConnectionIntegrationTest {};
1784
Seth Hampson2f0d7022018-02-20 11:54:42 -08001785class PeerConnectionIntegrationTestPlanB
1786 : public PeerConnectionIntegrationBaseTest {
1787 protected:
1788 PeerConnectionIntegrationTestPlanB()
1789 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1790};
1791
1792class PeerConnectionIntegrationTestUnifiedPlan
1793 : public PeerConnectionIntegrationBaseTest {
1794 protected:
1795 PeerConnectionIntegrationTestUnifiedPlan()
1796 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1797};
1798
deadbeef1dcb1642017-03-29 21:08:16 -07001799// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1800// includes testing that the callback is invoked if an observer is connected
1801// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001802TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001803 RtpReceiverObserverOnFirstPacketReceived) {
1804 ASSERT_TRUE(CreatePeerConnectionWrappers());
1805 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001806 caller()->AddAudioVideoTracks();
1807 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001808 // Start offer/answer exchange and wait for it to complete.
1809 caller()->CreateAndSetAndSignalOffer();
1810 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1811 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001812 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1813 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001814 // Wait for all "first packet received" callbacks to be fired.
1815 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001816 absl::c_all_of(caller()->rtp_receiver_observers(),
1817 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1818 return o->first_packet_received();
1819 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001820 kMaxWaitForFramesMs);
1821 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001822 absl::c_all_of(callee()->rtp_receiver_observers(),
1823 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1824 return o->first_packet_received();
1825 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001826 kMaxWaitForFramesMs);
1827 // If new observers are set after the first packet was already received, the
1828 // callback should still be invoked.
1829 caller()->ResetRtpReceiverObservers();
1830 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001831 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1832 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001833 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001834 absl::c_all_of(caller()->rtp_receiver_observers(),
1835 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1836 return o->first_packet_received();
1837 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001838 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001839 absl::c_all_of(callee()->rtp_receiver_observers(),
1840 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1841 return o->first_packet_received();
1842 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001843}
1844
1845class DummyDtmfObserver : public DtmfSenderObserverInterface {
1846 public:
1847 DummyDtmfObserver() : completed_(false) {}
1848
1849 // Implements DtmfSenderObserverInterface.
1850 void OnToneChange(const std::string& tone) override {
1851 tones_.push_back(tone);
1852 if (tone.empty()) {
1853 completed_ = true;
1854 }
1855 }
1856
1857 const std::vector<std::string>& tones() const { return tones_; }
1858 bool completed() const { return completed_; }
1859
1860 private:
1861 bool completed_;
1862 std::vector<std::string> tones_;
1863};
1864
1865// Assumes |sender| already has an audio track added and the offer/answer
1866// exchange is done.
1867void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1868 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001869 // We should be able to get a DTMF sender from the local sender.
1870 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1871 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1872 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001873 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001874 dtmf_sender->RegisterObserver(&observer);
1875
1876 // Test the DtmfSender object just created.
1877 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1878 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1879
1880 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1881 std::vector<std::string> tones = {"1", "a", ""};
1882 EXPECT_EQ(tones, observer.tones());
1883 dtmf_sender->UnregisterObserver();
1884 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1885}
1886
1887// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1888// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001889TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001890 ASSERT_TRUE(CreatePeerConnectionWrappers());
1891 ConnectFakeSignaling();
1892 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001893 caller()->AddAudioTrack();
1894 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001895 caller()->CreateAndSetAndSignalOffer();
1896 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001897 // DTLS must finish before the DTMF sender can be used reliably.
1898 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001899 TestDtmfFromSenderToReceiver(caller(), callee());
1900 TestDtmfFromSenderToReceiver(callee(), caller());
1901}
1902
1903// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1904// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001905TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001906 ASSERT_TRUE(CreatePeerConnectionWrappers());
1907 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001908
deadbeef1dcb1642017-03-29 21:08:16 -07001909 // Do normal offer/answer and wait for some frames to be received in each
1910 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001911 caller()->AddAudioVideoTracks();
1912 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001913 caller()->CreateAndSetAndSignalOffer();
1914 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001915 MediaExpectations media_expectations;
1916 media_expectations.ExpectBidirectionalAudioAndVideo();
1917 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001918 EXPECT_METRIC_LE(
1919 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1920 webrtc::kEnumCounterKeyProtocolDtls));
1921 EXPECT_METRIC_EQ(
1922 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1923 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001924}
1925
1926// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001927TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001928 PeerConnectionInterface::RTCConfiguration sdes_config;
1929 sdes_config.enable_dtls_srtp.emplace(false);
1930 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1931 ConnectFakeSignaling();
1932
1933 // Do normal offer/answer and wait for some frames to be received in each
1934 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001935 caller()->AddAudioVideoTracks();
1936 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001937 caller()->CreateAndSetAndSignalOffer();
1938 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001939 MediaExpectations media_expectations;
1940 media_expectations.ExpectBidirectionalAudioAndVideo();
1941 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001942 EXPECT_METRIC_LE(
1943 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1944 webrtc::kEnumCounterKeyProtocolSdes));
1945 EXPECT_METRIC_EQ(
1946 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1947 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001948}
1949
Steve Anton9a44b2d2019-07-12 12:58:30 -07001950// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1951// option to offer encrypted versions of all header extensions alongside the
1952// unencrypted versions.
1953TEST_P(PeerConnectionIntegrationTest,
1954 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1955 CryptoOptions crypto_options;
1956 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1957 PeerConnectionInterface::RTCConfiguration config;
1958 config.crypto_options = crypto_options;
1959 // Note: This allows offering >14 RTP header extensions.
1960 config.offer_extmap_allow_mixed = true;
1961 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1962 ConnectFakeSignaling();
1963
1964 // Do normal offer/answer and wait for some frames to be received in each
1965 // direction.
1966 caller()->AddAudioVideoTracks();
1967 callee()->AddAudioVideoTracks();
1968 caller()->CreateAndSetAndSignalOffer();
1969 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1970 MediaExpectations media_expectations;
1971 media_expectations.ExpectBidirectionalAudioAndVideo();
1972 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1973}
1974
Steve Anton8c0f7a72017-10-03 10:03:10 -07001975// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1976// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001977TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001978 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1979 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1980 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1981 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1982 return pc->GetRemoteAudioSSLCertificate();
1983 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001984 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1985 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1986 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1987 return pc->GetRemoteAudioSSLCertChain();
1988 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001989
1990 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1991 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1992
1993 // Configure each side with a known certificate so they can be compared later.
1994 PeerConnectionInterface::RTCConfiguration caller_config;
1995 caller_config.enable_dtls_srtp.emplace(true);
1996 caller_config.certificates.push_back(caller_cert);
1997 PeerConnectionInterface::RTCConfiguration callee_config;
1998 callee_config.enable_dtls_srtp.emplace(true);
1999 callee_config.certificates.push_back(callee_cert);
2000 ASSERT_TRUE(
2001 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
2002 ConnectFakeSignaling();
2003
2004 // When first initialized, there should not be a remote SSL certificate (and
2005 // calling this method should not crash).
2006 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
2007 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08002008 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
2009 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07002010
Steve Anton15324772018-01-16 10:26:49 -08002011 caller()->AddAudioTrack();
2012 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07002013 caller()->CreateAndSetAndSignalOffer();
2014 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2015 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
2016
2017 // Once DTLS has been connected, each side should return the other's SSL
2018 // certificate when calling GetRemoteAudioSSLCertificate.
2019
2020 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
2021 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002022 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07002023 caller_remote_cert->ToPEMString());
2024
2025 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
2026 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002027 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07002028 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08002029
2030 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
2031 ASSERT_TRUE(caller_remote_cert_chain);
2032 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
2033 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002034 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08002035 remote_cert->ToPEMString());
2036
2037 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
2038 ASSERT_TRUE(callee_remote_cert_chain);
2039 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
2040 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002041 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08002042 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002043}
2044
deadbeef1dcb1642017-03-29 21:08:16 -07002045// This test sets up a call between two parties with a source resolution of
2046// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002047TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002048 Send1280By720ResolutionAndReceive16To9AspectRatio) {
2049 ASSERT_TRUE(CreatePeerConnectionWrappers());
2050 ConnectFakeSignaling();
2051
Niels Möller5c7efe72018-05-11 10:34:46 +02002052 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
2053 webrtc::FakePeriodicVideoSource::Config config;
2054 config.width = 1280;
2055 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02002056 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02002057 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
2058 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07002059
2060 // Do normal offer/answer and wait for at least one frame to be received in
2061 // each direction.
2062 caller()->CreateAndSetAndSignalOffer();
2063 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2064 callee()->min_video_frames_received_per_track() > 0,
2065 kMaxWaitForFramesMs);
2066
2067 // Check rendered aspect ratio.
2068 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
2069 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
2070 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
2071 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
2072}
2073
2074// This test sets up an one-way call, with media only from caller to
2075// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002076TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07002077 ASSERT_TRUE(CreatePeerConnectionWrappers());
2078 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002079 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002080 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002081 MediaExpectations media_expectations;
2082 media_expectations.CalleeExpectsSomeAudioAndVideo();
2083 media_expectations.CallerExpectsNoAudio();
2084 media_expectations.CallerExpectsNoVideo();
2085 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002086}
2087
Johannes Kron3e983682020-03-29 22:17:00 +02002088// Tests that send only works without the caller having a decoder factory and
2089// the callee having an encoder factory.
2090TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSendOnlyVideo) {
2091 ASSERT_TRUE(
2092 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/true));
2093 ConnectFakeSignaling();
2094 // Add one-directional video, from caller to callee.
2095 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2096 caller()->CreateLocalVideoTrack();
2097 caller()->AddTrack(caller_track);
2098 PeerConnectionInterface::RTCOfferAnswerOptions options;
2099 options.offer_to_receive_video = 0;
2100 caller()->SetOfferAnswerOptions(options);
2101 caller()->CreateAndSetAndSignalOffer();
2102 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2103 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
2104
2105 // Expect video to be received in one direction.
2106 MediaExpectations media_expectations;
2107 media_expectations.CallerExpectsNoVideo();
2108 media_expectations.CalleeExpectsSomeVideo();
2109
2110 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2111}
2112
2113// Tests that receive only works without the caller having an encoder factory
2114// and the callee having a decoder factory.
2115TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithReceiveOnlyVideo) {
2116 ASSERT_TRUE(
2117 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/false));
2118 ConnectFakeSignaling();
2119 // Add one-directional video, from callee to caller.
2120 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2121 callee()->CreateLocalVideoTrack();
2122 callee()->AddTrack(callee_track);
2123 PeerConnectionInterface::RTCOfferAnswerOptions options;
2124 options.offer_to_receive_video = 1;
2125 caller()->SetOfferAnswerOptions(options);
2126 caller()->CreateAndSetAndSignalOffer();
2127 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2128 ASSERT_EQ(caller()->pc()->GetReceivers().size(), 1u);
2129
2130 // Expect video to be received in one direction.
2131 MediaExpectations media_expectations;
2132 media_expectations.CallerExpectsSomeVideo();
2133 media_expectations.CalleeExpectsNoVideo();
2134
2135 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2136}
2137
2138TEST_P(PeerConnectionIntegrationTest,
2139 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2140 ASSERT_TRUE(CreatePeerConnectionWrappers());
2141 ConnectFakeSignaling();
2142 // Add one-directional video, from caller to callee.
2143 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2144 caller()->CreateLocalVideoTrack();
2145 caller()->AddTrack(caller_track);
2146 caller()->CreateAndSetAndSignalOffer();
2147 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2148
2149 // Add receive video.
2150 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2151 callee()->CreateLocalVideoTrack();
2152 callee()->AddTrack(callee_track);
2153 caller()->CreateAndSetAndSignalOffer();
2154 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2155
2156 // Ensure that video frames are received end-to-end.
2157 MediaExpectations media_expectations;
2158 media_expectations.ExpectBidirectionalVideo();
2159 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2160}
2161
2162TEST_P(PeerConnectionIntegrationTest,
2163 EndToEndCallAddSendVideoToReceiveOnlyCall) {
2164 ASSERT_TRUE(CreatePeerConnectionWrappers());
2165 ConnectFakeSignaling();
2166 // Add one-directional video, from callee to caller.
2167 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2168 callee()->CreateLocalVideoTrack();
2169 callee()->AddTrack(callee_track);
2170 caller()->CreateAndSetAndSignalOffer();
2171 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2172
2173 // Add send video.
2174 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2175 caller()->CreateLocalVideoTrack();
2176 caller()->AddTrack(caller_track);
2177 caller()->CreateAndSetAndSignalOffer();
2178 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2179
2180 // Expect video to be received in one direction.
2181 MediaExpectations media_expectations;
2182 media_expectations.ExpectBidirectionalVideo();
2183 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2184}
2185
2186TEST_P(PeerConnectionIntegrationTest,
2187 EndToEndCallRemoveReceiveVideoFromSendReceiveCall) {
2188 ASSERT_TRUE(CreatePeerConnectionWrappers());
2189 ConnectFakeSignaling();
2190 // Add send video, from caller to callee.
2191 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2192 caller()->CreateLocalVideoTrack();
2193 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2194 caller()->AddTrack(caller_track);
2195 // Add receive video, from callee to caller.
2196 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2197 callee()->CreateLocalVideoTrack();
2198
2199 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2200 callee()->AddTrack(callee_track);
2201 caller()->CreateAndSetAndSignalOffer();
2202 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2203
2204 // Remove receive video (i.e., callee sender track).
2205 callee()->pc()->RemoveTrack(callee_sender);
2206
2207 caller()->CreateAndSetAndSignalOffer();
2208 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2209
2210 // Expect one-directional video.
2211 MediaExpectations media_expectations;
2212 media_expectations.CallerExpectsNoVideo();
2213 media_expectations.CalleeExpectsSomeVideo();
2214
2215 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2216}
2217
2218TEST_P(PeerConnectionIntegrationTest,
2219 EndToEndCallRemoveSendVideoFromSendReceiveCall) {
2220 ASSERT_TRUE(CreatePeerConnectionWrappers());
2221 ConnectFakeSignaling();
2222 // Add send video, from caller to callee.
2223 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2224 caller()->CreateLocalVideoTrack();
2225 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2226 caller()->AddTrack(caller_track);
2227 // Add receive video, from callee to caller.
2228 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2229 callee()->CreateLocalVideoTrack();
2230
2231 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2232 callee()->AddTrack(callee_track);
2233 caller()->CreateAndSetAndSignalOffer();
2234 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2235
2236 // Remove send video (i.e., caller sender track).
2237 caller()->pc()->RemoveTrack(caller_sender);
2238
2239 caller()->CreateAndSetAndSignalOffer();
2240 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2241
2242 // Expect one-directional video.
2243 MediaExpectations media_expectations;
2244 media_expectations.CalleeExpectsNoVideo();
2245 media_expectations.CallerExpectsSomeVideo();
2246
2247 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2248}
2249
deadbeef1dcb1642017-03-29 21:08:16 -07002250// This test sets up a audio call initially, with the callee rejecting video
2251// initially. Then later the callee decides to upgrade to audio/video, and
2252// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002253TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07002254 ASSERT_TRUE(CreatePeerConnectionWrappers());
2255 ConnectFakeSignaling();
2256 // Initially, offer an audio/video stream from the caller, but refuse to
2257 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08002258 caller()->AddAudioVideoTracks();
2259 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002260 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2261 PeerConnectionInterface::RTCOfferAnswerOptions options;
2262 options.offer_to_receive_video = 0;
2263 callee()->SetOfferAnswerOptions(options);
2264 } else {
2265 callee()->SetRemoteOfferHandler([this] {
2266 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2267 });
2268 }
deadbeef1dcb1642017-03-29 21:08:16 -07002269 // Do offer/answer and make sure audio is still received end-to-end.
2270 caller()->CreateAndSetAndSignalOffer();
2271 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002272 {
2273 MediaExpectations media_expectations;
2274 media_expectations.ExpectBidirectionalAudio();
2275 media_expectations.ExpectNoVideo();
2276 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2277 }
deadbeef1dcb1642017-03-29 21:08:16 -07002278 // Sanity check that the callee's description has a rejected video section.
2279 ASSERT_NE(nullptr, callee()->pc()->local_description());
2280 const ContentInfo* callee_video_content =
2281 GetFirstVideoContent(callee()->pc()->local_description()->description());
2282 ASSERT_NE(nullptr, callee_video_content);
2283 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002284
deadbeef1dcb1642017-03-29 21:08:16 -07002285 // Now negotiate with video and ensure negotiation succeeds, with video
2286 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002287 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002288 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2289 PeerConnectionInterface::RTCOfferAnswerOptions options;
2290 options.offer_to_receive_video = 1;
2291 callee()->SetOfferAnswerOptions(options);
2292 } else {
2293 callee()->SetRemoteOfferHandler(nullptr);
2294 caller()->SetRemoteOfferHandler([this] {
2295 // The caller creates a new transceiver to receive video on when receiving
2296 // the offer, but by default it is send only.
2297 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002298 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002299 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
2300 transceivers[2]->receiver()->media_type());
2301 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2302 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
2303 });
2304 }
deadbeef1dcb1642017-03-29 21:08:16 -07002305 callee()->CreateAndSetAndSignalOffer();
2306 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002307 {
2308 // Expect additional audio frames to be received after the upgrade.
2309 MediaExpectations media_expectations;
2310 media_expectations.ExpectBidirectionalAudioAndVideo();
2311 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2312 }
deadbeef1dcb1642017-03-29 21:08:16 -07002313}
2314
deadbeef4389b4d2017-09-07 09:07:36 -07002315// Simpler than the above test; just add an audio track to an established
2316// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002317TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002318 ASSERT_TRUE(CreatePeerConnectionWrappers());
2319 ConnectFakeSignaling();
2320 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002321 caller()->AddVideoTrack();
2322 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002323 caller()->CreateAndSetAndSignalOffer();
2324 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2325 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002326 caller()->AddAudioTrack();
2327 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002328 caller()->CreateAndSetAndSignalOffer();
2329 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2330 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002331 MediaExpectations media_expectations;
2332 media_expectations.ExpectBidirectionalAudioAndVideo();
2333 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002334}
2335
deadbeef1dcb1642017-03-29 21:08:16 -07002336// This test sets up a call that's transferred to a new caller with a different
2337// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002338TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002339 ASSERT_TRUE(CreatePeerConnectionWrappers());
2340 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002341 caller()->AddAudioVideoTracks();
2342 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002343 caller()->CreateAndSetAndSignalOffer();
2344 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2345
2346 // Keep the original peer around which will still send packets to the
2347 // receiving client. These SRTP packets will be dropped.
2348 std::unique_ptr<PeerConnectionWrapper> original_peer(
2349 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002350 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002351 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2352 // directly above.
2353 original_peer->pc()->Close();
2354
2355 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002356 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002357 caller()->CreateAndSetAndSignalOffer();
2358 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2359 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002360 MediaExpectations media_expectations;
2361 media_expectations.ExpectBidirectionalAudioAndVideo();
2362 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002363}
2364
2365// This test sets up a call that's transferred to a new callee with a different
2366// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002367TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002368 ASSERT_TRUE(CreatePeerConnectionWrappers());
2369 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002370 caller()->AddAudioVideoTracks();
2371 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002372 caller()->CreateAndSetAndSignalOffer();
2373 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2374
2375 // Keep the original peer around which will still send packets to the
2376 // receiving client. These SRTP packets will be dropped.
2377 std::unique_ptr<PeerConnectionWrapper> original_peer(
2378 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002379 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002380 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2381 // directly above.
2382 original_peer->pc()->Close();
2383
2384 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002385 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002386 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2387 caller()->CreateAndSetAndSignalOffer();
2388 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2389 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002390 MediaExpectations media_expectations;
2391 media_expectations.ExpectBidirectionalAudioAndVideo();
2392 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002393}
2394
2395// This test sets up a non-bundled call and negotiates bundling at the same
2396// time as starting an ICE restart. When bundling is in effect in the restart,
2397// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002398TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002399 ASSERT_TRUE(CreatePeerConnectionWrappers());
2400 ConnectFakeSignaling();
2401
Steve Anton15324772018-01-16 10:26:49 -08002402 caller()->AddAudioVideoTracks();
2403 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002404 // Remove the bundle group from the SDP received by the callee.
2405 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2406 desc->RemoveGroupByName("BUNDLE");
2407 });
2408 caller()->CreateAndSetAndSignalOffer();
2409 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002410 {
2411 MediaExpectations media_expectations;
2412 media_expectations.ExpectBidirectionalAudioAndVideo();
2413 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2414 }
deadbeef1dcb1642017-03-29 21:08:16 -07002415 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2416 callee()->SetReceivedSdpMunger(nullptr);
2417 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2418 caller()->CreateAndSetAndSignalOffer();
2419 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2420
2421 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002422 {
2423 MediaExpectations media_expectations;
2424 media_expectations.ExpectBidirectionalAudioAndVideo();
2425 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2426 }
deadbeef1dcb1642017-03-29 21:08:16 -07002427}
2428
2429// Test CVO (Coordination of Video Orientation). If a video source is rotated
2430// and both peers support the CVO RTP header extension, the actual video frames
2431// don't need to be encoded in different resolutions, since the rotation is
2432// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002433TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002434 ASSERT_TRUE(CreatePeerConnectionWrappers());
2435 ConnectFakeSignaling();
2436 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002437 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002438 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002439 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002440 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2441
2442 // Wait for video frames to be received by both sides.
2443 caller()->CreateAndSetAndSignalOffer();
2444 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2445 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2446 callee()->min_video_frames_received_per_track() > 0,
2447 kMaxWaitForFramesMs);
2448
2449 // Ensure that the aspect ratio is unmodified.
2450 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2451 // not just assumed.
2452 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2453 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2454 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2455 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2456 // Ensure that the CVO bits were surfaced to the renderer.
2457 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2458 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2459}
2460
2461// Test that when the CVO extension isn't supported, video is rotated the
2462// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002463TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002464 ASSERT_TRUE(CreatePeerConnectionWrappers());
2465 ConnectFakeSignaling();
2466 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002467 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002468 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002469 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002470 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2471
2472 // Remove the CVO extension from the offered SDP.
2473 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2474 cricket::VideoContentDescription* video =
2475 GetFirstVideoContentDescription(desc);
2476 video->ClearRtpHeaderExtensions();
2477 });
2478 // Wait for video frames to be received by both sides.
2479 caller()->CreateAndSetAndSignalOffer();
2480 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2481 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2482 callee()->min_video_frames_received_per_track() > 0,
2483 kMaxWaitForFramesMs);
2484
2485 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2486 // rotation.
2487 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2488 // not just assumed.
2489 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2490 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2491 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2492 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2493 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2494 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2495 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2496}
2497
deadbeef1dcb1642017-03-29 21:08:16 -07002498// Test that if the answerer rejects the audio m= section, no audio is sent or
2499// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002500TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002501 ASSERT_TRUE(CreatePeerConnectionWrappers());
2502 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002503 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002504 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2505 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2506 // it will reject the audio m= section completely.
2507 PeerConnectionInterface::RTCOfferAnswerOptions options;
2508 options.offer_to_receive_audio = 0;
2509 callee()->SetOfferAnswerOptions(options);
2510 } else {
2511 // Stopping the audio RtpTransceiver will cause the media section to be
2512 // rejected in the answer.
2513 callee()->SetRemoteOfferHandler([this] {
2514 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2515 });
2516 }
Steve Anton15324772018-01-16 10:26:49 -08002517 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002518 // Do offer/answer and wait for successful end-to-end video frames.
2519 caller()->CreateAndSetAndSignalOffer();
2520 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002521 MediaExpectations media_expectations;
2522 media_expectations.ExpectBidirectionalVideo();
2523 media_expectations.ExpectNoAudio();
2524 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2525
deadbeef1dcb1642017-03-29 21:08:16 -07002526 // Sanity check that the callee's description has a rejected audio section.
2527 ASSERT_NE(nullptr, callee()->pc()->local_description());
2528 const ContentInfo* callee_audio_content =
2529 GetFirstAudioContent(callee()->pc()->local_description()->description());
2530 ASSERT_NE(nullptr, callee_audio_content);
2531 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002532 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2533 // The caller's transceiver should have stopped after receiving the answer.
2534 EXPECT_TRUE(caller()
2535 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2536 ->stopped());
2537 }
deadbeef1dcb1642017-03-29 21:08:16 -07002538}
2539
2540// Test that if the answerer rejects the video m= section, no video is sent or
2541// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002542TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002543 ASSERT_TRUE(CreatePeerConnectionWrappers());
2544 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002545 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002546 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2547 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2548 // it will reject the video m= section completely.
2549 PeerConnectionInterface::RTCOfferAnswerOptions options;
2550 options.offer_to_receive_video = 0;
2551 callee()->SetOfferAnswerOptions(options);
2552 } else {
2553 // Stopping the video RtpTransceiver will cause the media section to be
2554 // rejected in the answer.
2555 callee()->SetRemoteOfferHandler([this] {
2556 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2557 });
2558 }
Steve Anton15324772018-01-16 10:26:49 -08002559 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002560 // Do offer/answer and wait for successful end-to-end audio frames.
2561 caller()->CreateAndSetAndSignalOffer();
2562 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002563 MediaExpectations media_expectations;
2564 media_expectations.ExpectBidirectionalAudio();
2565 media_expectations.ExpectNoVideo();
2566 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2567
deadbeef1dcb1642017-03-29 21:08:16 -07002568 // Sanity check that the callee's description has a rejected video section.
2569 ASSERT_NE(nullptr, callee()->pc()->local_description());
2570 const ContentInfo* callee_video_content =
2571 GetFirstVideoContent(callee()->pc()->local_description()->description());
2572 ASSERT_NE(nullptr, callee_video_content);
2573 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002574 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2575 // The caller's transceiver should have stopped after receiving the answer.
2576 EXPECT_TRUE(caller()
2577 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2578 ->stopped());
2579 }
deadbeef1dcb1642017-03-29 21:08:16 -07002580}
2581
2582// Test that if the answerer rejects both audio and video m= sections, nothing
2583// bad happens.
2584// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2585// test anything but the fact that negotiation succeeds, which doesn't mean
2586// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002587TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002588 ASSERT_TRUE(CreatePeerConnectionWrappers());
2589 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002590 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002591 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2592 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2593 // will reject both audio and video m= sections.
2594 PeerConnectionInterface::RTCOfferAnswerOptions options;
2595 options.offer_to_receive_audio = 0;
2596 options.offer_to_receive_video = 0;
2597 callee()->SetOfferAnswerOptions(options);
2598 } else {
2599 callee()->SetRemoteOfferHandler([this] {
2600 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002601 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002602 transceiver->Stop();
2603 }
2604 });
2605 }
deadbeef1dcb1642017-03-29 21:08:16 -07002606 // Do offer/answer and wait for stable signaling state.
2607 caller()->CreateAndSetAndSignalOffer();
2608 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002609
deadbeef1dcb1642017-03-29 21:08:16 -07002610 // Sanity check that the callee's description has rejected m= sections.
2611 ASSERT_NE(nullptr, callee()->pc()->local_description());
2612 const ContentInfo* callee_audio_content =
2613 GetFirstAudioContent(callee()->pc()->local_description()->description());
2614 ASSERT_NE(nullptr, callee_audio_content);
2615 EXPECT_TRUE(callee_audio_content->rejected);
2616 const ContentInfo* callee_video_content =
2617 GetFirstVideoContent(callee()->pc()->local_description()->description());
2618 ASSERT_NE(nullptr, callee_video_content);
2619 EXPECT_TRUE(callee_video_content->rejected);
2620}
2621
2622// This test sets up an audio and video call between two parties. After the
2623// call runs for a while, the caller sends an updated offer with video being
2624// rejected. Once the re-negotiation is done, the video flow should stop and
2625// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002626TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002627 ASSERT_TRUE(CreatePeerConnectionWrappers());
2628 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002629 caller()->AddAudioVideoTracks();
2630 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002631 caller()->CreateAndSetAndSignalOffer();
2632 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002633 {
2634 MediaExpectations media_expectations;
2635 media_expectations.ExpectBidirectionalAudioAndVideo();
2636 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2637 }
deadbeef1dcb1642017-03-29 21:08:16 -07002638 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002639 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2640 caller()->SetGeneratedSdpMunger(
2641 [](cricket::SessionDescription* description) {
2642 for (cricket::ContentInfo& content : description->contents()) {
2643 if (cricket::IsVideoContent(&content)) {
2644 content.rejected = true;
2645 }
2646 }
2647 });
2648 } else {
2649 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2650 }
deadbeef1dcb1642017-03-29 21:08:16 -07002651 caller()->CreateAndSetAndSignalOffer();
2652 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2653
2654 // Sanity check that the caller's description has a rejected video section.
2655 ASSERT_NE(nullptr, caller()->pc()->local_description());
2656 const ContentInfo* caller_video_content =
2657 GetFirstVideoContent(caller()->pc()->local_description()->description());
2658 ASSERT_NE(nullptr, caller_video_content);
2659 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002660 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002661 {
2662 MediaExpectations media_expectations;
2663 media_expectations.ExpectBidirectionalAudio();
2664 media_expectations.ExpectNoVideo();
2665 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2666 }
deadbeef1dcb1642017-03-29 21:08:16 -07002667}
2668
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002669// Do one offer/answer with audio, another that disables it (rejecting the m=
2670// section), and another that re-enables it. Regression test for:
2671// bugs.webrtc.org/6023
2672TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2673 ASSERT_TRUE(CreatePeerConnectionWrappers());
2674 ConnectFakeSignaling();
2675
2676 // Add audio track, do normal offer/answer.
2677 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2678 caller()->CreateLocalAudioTrack();
2679 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2680 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2681 caller()->CreateAndSetAndSignalOffer();
2682 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2683
2684 // Remove audio track, and set offer_to_receive_audio to false to cause the
2685 // m= section to be completely disabled, not just "recvonly".
2686 caller()->pc()->RemoveTrack(sender);
2687 PeerConnectionInterface::RTCOfferAnswerOptions options;
2688 options.offer_to_receive_audio = 0;
2689 caller()->SetOfferAnswerOptions(options);
2690 caller()->CreateAndSetAndSignalOffer();
2691 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2692
2693 // Add the audio track again, expecting negotiation to succeed and frames to
2694 // flow.
2695 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2696 options.offer_to_receive_audio = 1;
2697 caller()->SetOfferAnswerOptions(options);
2698 caller()->CreateAndSetAndSignalOffer();
2699 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2700
2701 MediaExpectations media_expectations;
2702 media_expectations.CalleeExpectsSomeAudio();
2703 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2704}
2705
deadbeef1dcb1642017-03-29 21:08:16 -07002706// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2707// is needed to support legacy endpoints.
2708// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2709// add a test for an end-to-end test without MID signaling either (basically,
2710// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002711TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002712 ASSERT_TRUE(CreatePeerConnectionWrappers());
2713 ConnectFakeSignaling();
2714 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002715 caller()->AddAudioVideoTracks();
2716 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002717 // Remove SSRCs and MSIDs from the received offer SDP.
2718 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002719 caller()->CreateAndSetAndSignalOffer();
2720 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002721 MediaExpectations media_expectations;
2722 media_expectations.ExpectBidirectionalAudioAndVideo();
2723 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002724}
2725
Seth Hampson5897a6e2018-04-03 11:16:33 -07002726// Basic end-to-end test, without SSRC signaling. This means that the track
2727// was created properly and frames are delivered when the MSIDs are communicated
2728// with a=msid lines and no a=ssrc lines.
2729TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2730 EndToEndCallWithoutSsrcSignaling) {
2731 const char kStreamId[] = "streamId";
2732 ASSERT_TRUE(CreatePeerConnectionWrappers());
2733 ConnectFakeSignaling();
2734 // Add just audio tracks.
2735 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2736 callee()->AddAudioTrack();
2737
2738 // Remove SSRCs from the received offer SDP.
2739 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2740 caller()->CreateAndSetAndSignalOffer();
2741 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2742 MediaExpectations media_expectations;
2743 media_expectations.ExpectBidirectionalAudio();
2744 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2745}
2746
Johannes Kron3e983682020-03-29 22:17:00 +02002747TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2748 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2749 ASSERT_TRUE(CreatePeerConnectionWrappers());
2750 ConnectFakeSignaling();
2751 // Add one-directional video, from caller to callee.
2752 rtc::scoped_refptr<webrtc::VideoTrackInterface> track =
2753 caller()->CreateLocalVideoTrack();
2754
2755 RtpTransceiverInit video_transceiver_init;
2756 video_transceiver_init.stream_ids = {"video1"};
2757 video_transceiver_init.direction = RtpTransceiverDirection::kSendOnly;
2758 auto video_sender =
2759 caller()->pc()->AddTransceiver(track, video_transceiver_init).MoveValue();
2760 caller()->CreateAndSetAndSignalOffer();
2761 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2762
2763 // Add receive direction.
2764 video_sender->SetDirection(RtpTransceiverDirection::kSendRecv);
2765
2766 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2767 callee()->CreateLocalVideoTrack();
2768
2769 callee()->AddTrack(callee_track);
2770 caller()->CreateAndSetAndSignalOffer();
2771 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2772 // Ensure that video frames are received end-to-end.
2773 MediaExpectations media_expectations;
2774 media_expectations.ExpectBidirectionalVideo();
2775 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2776}
2777
Steve Antondf527fd2018-04-27 15:52:03 -07002778// Tests that video flows between multiple video tracks when SSRCs are not
2779// signaled. This exercises the MID RTP header extension which is needed to
2780// demux the incoming video tracks.
2781TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2782 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2783 ASSERT_TRUE(CreatePeerConnectionWrappers());
2784 ConnectFakeSignaling();
2785 caller()->AddVideoTrack();
2786 caller()->AddVideoTrack();
2787 callee()->AddVideoTrack();
2788 callee()->AddVideoTrack();
2789
2790 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2791 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2792 caller()->CreateAndSetAndSignalOffer();
2793 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2794 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2795 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2796
2797 // Expect video to be received in both directions on both tracks.
2798 MediaExpectations media_expectations;
2799 media_expectations.ExpectBidirectionalVideo();
2800 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2801}
2802
Henrik Boström5b147782018-12-04 11:25:05 +01002803TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2804 ASSERT_TRUE(CreatePeerConnectionWrappers());
2805 ConnectFakeSignaling();
2806 caller()->AddAudioTrack();
2807 caller()->AddVideoTrack();
2808 caller()->CreateAndSetAndSignalOffer();
2809 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2810 auto callee_receivers = callee()->pc()->GetReceivers();
2811 ASSERT_EQ(2u, callee_receivers.size());
2812 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2813 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2814}
2815
2816TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2817 ASSERT_TRUE(CreatePeerConnectionWrappers());
2818 ConnectFakeSignaling();
2819 caller()->AddAudioTrack();
2820 caller()->AddVideoTrack();
2821 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2822 caller()->CreateAndSetAndSignalOffer();
2823 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2824 auto callee_receivers = callee()->pc()->GetReceivers();
2825 ASSERT_EQ(2u, callee_receivers.size());
2826 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2827 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2828 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2829 callee_receivers[1]->stream_ids()[0]);
2830 EXPECT_EQ(callee_receivers[0]->streams()[0],
2831 callee_receivers[1]->streams()[0]);
2832}
2833
deadbeef1dcb1642017-03-29 21:08:16 -07002834// Test that if two video tracks are sent (from caller to callee, in this test),
2835// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002836TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002837 ASSERT_TRUE(CreatePeerConnectionWrappers());
2838 ConnectFakeSignaling();
2839 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002840 caller()->AddAudioVideoTracks();
2841 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002842 caller()->CreateAndSetAndSignalOffer();
2843 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002844 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002845
2846 MediaExpectations media_expectations;
2847 media_expectations.CalleeExpectsSomeAudioAndVideo();
2848 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002849}
2850
2851static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2852 bool first = true;
2853 for (cricket::ContentInfo& content : desc->contents()) {
2854 if (first) {
2855 first = false;
2856 continue;
2857 }
2858 content.bundle_only = true;
2859 }
2860 first = true;
2861 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2862 if (first) {
2863 first = false;
2864 continue;
2865 }
2866 transport.description.ice_ufrag.clear();
2867 transport.description.ice_pwd.clear();
2868 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2869 transport.description.identity_fingerprint.reset(nullptr);
2870 }
2871}
2872
2873// Test that if applying a true "max bundle" offer, which uses ports of 0,
2874// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2875// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2876// successfully and media flows.
2877// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2878// TODO(deadbeef): Won't need this test once we start generating actual
2879// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002880TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002881 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2882 ASSERT_TRUE(CreatePeerConnectionWrappers());
2883 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002884 caller()->AddAudioVideoTracks();
2885 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002886 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2887 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2888 // but the first m= section.
2889 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2890 caller()->CreateAndSetAndSignalOffer();
2891 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002892 MediaExpectations media_expectations;
2893 media_expectations.ExpectBidirectionalAudioAndVideo();
2894 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002895}
2896
2897// Test that we can receive the audio output level from a remote audio track.
2898// TODO(deadbeef): Use a fake audio source and verify that the output level is
2899// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002900TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002901 ASSERT_TRUE(CreatePeerConnectionWrappers());
2902 ConnectFakeSignaling();
2903 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002904 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002905 caller()->CreateAndSetAndSignalOffer();
2906 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2907
2908 // Get the audio output level stats. Note that the level is not available
2909 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002910 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002911 kMaxWaitForFramesMs);
2912}
2913
2914// Test that an audio input level is reported.
2915// TODO(deadbeef): Use a fake audio source and verify that the input level is
2916// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002917TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002918 ASSERT_TRUE(CreatePeerConnectionWrappers());
2919 ConnectFakeSignaling();
2920 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002921 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002922 caller()->CreateAndSetAndSignalOffer();
2923 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2924
2925 // Get the audio input level stats. The level should be available very
2926 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002927 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002928 kMaxWaitForStatsMs);
2929}
2930
2931// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002932TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002933 ASSERT_TRUE(CreatePeerConnectionWrappers());
2934 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002935 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002936 // Do offer/answer, wait for the callee to receive some frames.
2937 caller()->CreateAndSetAndSignalOffer();
2938 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002939
2940 MediaExpectations media_expectations;
2941 media_expectations.CalleeExpectsSomeAudioAndVideo();
2942 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002943
2944 // Get a handle to the remote tracks created, so they can be used as GetStats
2945 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002946 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002947 // We received frames, so we definitely should have nonzero "received bytes"
2948 // stats at this point.
2949 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2950 0);
2951 }
deadbeef1dcb1642017-03-29 21:08:16 -07002952}
2953
2954// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002955TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002956 ASSERT_TRUE(CreatePeerConnectionWrappers());
2957 ConnectFakeSignaling();
2958 auto audio_track = caller()->CreateLocalAudioTrack();
2959 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002960 caller()->AddTrack(audio_track);
2961 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002962 // Do offer/answer, wait for the callee to receive some frames.
2963 caller()->CreateAndSetAndSignalOffer();
2964 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002965 MediaExpectations media_expectations;
2966 media_expectations.CalleeExpectsSomeAudioAndVideo();
2967 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002968
2969 // The callee received frames, so we definitely should have nonzero "sent
2970 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002971 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2972 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2973}
2974
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002975// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002976TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002977 ASSERT_TRUE(CreatePeerConnectionWrappers());
2978 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002979 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002980
Steve Anton15324772018-01-16 10:26:49 -08002981 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002982
2983 // Do offer/answer, wait for the callee to receive some frames.
2984 caller()->CreateAndSetAndSignalOffer();
2985 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2986
2987 // Get the remote audio track created on the receiver, so they can be used as
2988 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002989 auto receivers = callee()->pc()->GetReceivers();
2990 ASSERT_EQ(1u, receivers.size());
2991 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002992
2993 // Get the audio output level stats. Note that the level is not available
2994 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002995 EXPECT_TRUE_WAIT(
2996 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2997 0,
2998 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002999}
3000
Steve Antona41959e2018-11-28 11:15:33 -08003001// Test that the track ID is associated with all local and remote SSRC stats
3002// using the old GetStats() and more than 1 audio and more than 1 video track.
3003// This is a regression test for crbug.com/906988
3004TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
3005 OldGetStatsAssociatesTrackIdForManyMediaSections) {
3006 ASSERT_TRUE(CreatePeerConnectionWrappers());
3007 ConnectFakeSignaling();
3008 auto audio_sender_1 = caller()->AddAudioTrack();
3009 auto video_sender_1 = caller()->AddVideoTrack();
3010 auto audio_sender_2 = caller()->AddAudioTrack();
3011 auto video_sender_2 = caller()->AddVideoTrack();
3012 caller()->CreateAndSetAndSignalOffer();
3013 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3014
3015 MediaExpectations media_expectations;
3016 media_expectations.CalleeExpectsSomeAudioAndVideo();
3017 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3018
3019 std::vector<std::string> track_ids = {
3020 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3021 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3022
3023 auto caller_stats = caller()->OldGetStats();
3024 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3025 auto callee_stats = callee()->OldGetStats();
3026 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3027}
3028
Steve Antonffa6ce42018-11-30 09:26:08 -08003029// Test that the new GetStats() returns stats for all outgoing/incoming streams
3030// with the correct track IDs if there are more than one audio and more than one
3031// video senders/receivers.
3032TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
3033 ASSERT_TRUE(CreatePeerConnectionWrappers());
3034 ConnectFakeSignaling();
3035 auto audio_sender_1 = caller()->AddAudioTrack();
3036 auto video_sender_1 = caller()->AddVideoTrack();
3037 auto audio_sender_2 = caller()->AddAudioTrack();
3038 auto video_sender_2 = caller()->AddVideoTrack();
3039 caller()->CreateAndSetAndSignalOffer();
3040 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3041
3042 MediaExpectations media_expectations;
3043 media_expectations.CalleeExpectsSomeAudioAndVideo();
3044 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3045
3046 std::vector<std::string> track_ids = {
3047 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3048 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3049
3050 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
3051 caller()->NewGetStats();
3052 ASSERT_TRUE(caller_report);
3053 auto outbound_stream_stats =
3054 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
3055 ASSERT_EQ(4u, outbound_stream_stats.size());
3056 std::vector<std::string> outbound_track_ids;
3057 for (const auto& stat : outbound_stream_stats) {
3058 ASSERT_TRUE(stat->bytes_sent.is_defined());
3059 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02003060 if (*stat->kind == "video") {
3061 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
3062 EXPECT_GT(*stat->key_frames_encoded, 0u);
3063 ASSERT_TRUE(stat->frames_encoded.is_defined());
3064 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
3065 }
Steve Antonffa6ce42018-11-30 09:26:08 -08003066 ASSERT_TRUE(stat->track_id.is_defined());
3067 const auto* track_stat =
3068 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3069 ASSERT_TRUE(track_stat);
3070 outbound_track_ids.push_back(*track_stat->track_identifier);
3071 }
3072 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
3073
3074 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
3075 callee()->NewGetStats();
3076 ASSERT_TRUE(callee_report);
3077 auto inbound_stream_stats =
3078 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3079 ASSERT_EQ(4u, inbound_stream_stats.size());
3080 std::vector<std::string> inbound_track_ids;
3081 for (const auto& stat : inbound_stream_stats) {
3082 ASSERT_TRUE(stat->bytes_received.is_defined());
3083 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02003084 if (*stat->kind == "video") {
3085 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
3086 EXPECT_GT(*stat->key_frames_decoded, 0u);
3087 ASSERT_TRUE(stat->frames_decoded.is_defined());
3088 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
3089 }
Steve Antonffa6ce42018-11-30 09:26:08 -08003090 ASSERT_TRUE(stat->track_id.is_defined());
3091 const auto* track_stat =
3092 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3093 ASSERT_TRUE(track_stat);
3094 inbound_track_ids.push_back(*track_stat->track_identifier);
3095 }
3096 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
3097}
3098
3099// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07003100// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
3101// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003102TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07003103 GetStatsForUnsignaledStreamWithNewStatsApi) {
3104 ASSERT_TRUE(CreatePeerConnectionWrappers());
3105 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003106 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07003107 // Remove SSRCs and MSIDs from the received offer SDP.
3108 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3109 caller()->CreateAndSetAndSignalOffer();
3110 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003111 MediaExpectations media_expectations;
3112 media_expectations.CalleeExpectsSomeAudio(1);
3113 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07003114
3115 // We received a frame, so we should have nonzero "bytes received" stats for
3116 // the unsignaled stream, if stats are working for it.
3117 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3118 callee()->NewGetStats();
3119 ASSERT_NE(nullptr, report);
3120 auto inbound_stream_stats =
3121 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3122 ASSERT_EQ(1U, inbound_stream_stats.size());
3123 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
3124 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07003125 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
3126}
3127
Taylor Brandstettera4653442018-06-19 09:44:26 -07003128// Same as above but for the legacy stats implementation.
3129TEST_P(PeerConnectionIntegrationTest,
3130 GetStatsForUnsignaledStreamWithOldStatsApi) {
3131 ASSERT_TRUE(CreatePeerConnectionWrappers());
3132 ConnectFakeSignaling();
3133 caller()->AddAudioTrack();
3134 // Remove SSRCs and MSIDs from the received offer SDP.
3135 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3136 caller()->CreateAndSetAndSignalOffer();
3137 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3138
3139 // Note that, since the old stats implementation associates SSRCs with tracks
3140 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
3141 // associated track ID. So we can't use the track "selector" argument.
3142 //
3143 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
3144 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003145 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07003146 kDefaultTimeout);
3147}
3148
zhihuangf8164932017-05-19 13:09:47 -07003149// Test that we can successfully get the media related stats (audio level
3150// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003151TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07003152 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
3153 ASSERT_TRUE(CreatePeerConnectionWrappers());
3154 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003155 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07003156 // Remove SSRCs and MSIDs from the received offer SDP.
3157 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3158 caller()->CreateAndSetAndSignalOffer();
3159 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003160 MediaExpectations media_expectations;
3161 media_expectations.CalleeExpectsSomeAudio(1);
3162 media_expectations.CalleeExpectsSomeVideo(1);
3163 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07003164
3165 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3166 callee()->NewGetStats();
3167 ASSERT_NE(nullptr, report);
3168
3169 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3170 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
3171 ASSERT_GE(audio_index, 0);
3172 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07003173}
3174
deadbeef4e2deab2017-09-20 13:56:21 -07003175// Helper for test below.
3176void ModifySsrcs(cricket::SessionDescription* desc) {
3177 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07003178 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08003179 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07003180 for (uint32_t& ssrc : stream.ssrcs) {
3181 ssrc = rtc::CreateRandomId();
3182 }
3183 }
3184 }
3185}
3186
3187// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
3188// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
3189// This should result in two "RTCInboundRTPStreamStats", but only one
3190// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
3191// being reset to 0 once the SSRC change occurs.
3192//
3193// Regression test for this bug:
3194// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
3195//
3196// The bug causes the track stats to only represent one of the two streams:
3197// whichever one has the higher SSRC. So with this bug, there was a 50% chance
3198// that the track stat counters would reset to 0 when the new stream is
3199// received, and a 50% chance that they'll stop updating (while
3200// "concealed_samples" continues increasing, due to silence being generated for
3201// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003202TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003203 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07003204 ASSERT_TRUE(CreatePeerConnectionWrappers());
3205 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003206 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07003207 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
3208 // that doesn't signal SSRCs (from the callee's perspective).
3209 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3210 caller()->CreateAndSetAndSignalOffer();
3211 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3212 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003213 {
3214 MediaExpectations media_expectations;
3215 media_expectations.CalleeExpectsSomeAudio(50);
3216 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3217 }
deadbeef4e2deab2017-09-20 13:56:21 -07003218 // Some audio frames were received, so we should have nonzero "samples
3219 // received" for the track.
3220 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3221 callee()->NewGetStats();
3222 ASSERT_NE(nullptr, report);
3223 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3224 ASSERT_EQ(1U, track_stats.size());
3225 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3226 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
3227 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
3228
3229 // Create a new offer and munge it to cause the caller to use a new SSRC.
3230 caller()->SetGeneratedSdpMunger(ModifySsrcs);
3231 caller()->CreateAndSetAndSignalOffer();
3232 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3233 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
3234 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003235 {
3236 MediaExpectations media_expectations;
3237 media_expectations.CalleeExpectsSomeAudio(25);
3238 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3239 }
deadbeef4e2deab2017-09-20 13:56:21 -07003240
3241 report = callee()->NewGetStats();
3242 ASSERT_NE(nullptr, report);
3243 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3244 ASSERT_EQ(1U, track_stats.size());
3245 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3246 // The "total samples received" stat should only be greater than it was
3247 // before.
3248 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
3249 // Right now, the new SSRC will cause the counters to reset to 0.
3250 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
3251
3252 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08003253 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07003254 // good sign that we're seeing stats from the old stream that's no longer
3255 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08003256 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07003257 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
3258 EXPECT_LT(*track_stats[0]->concealed_samples,
3259 *track_stats[0]->total_samples_received *
3260 kAcceptableConcealedSamplesPercentage);
3261
3262 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
3263 // sanity check that the SSRC really changed.
3264 // TODO(deadbeef): This isn't working right now, because we're not returning
3265 // *any* stats for the inactive stream. Uncomment when the bug is completely
3266 // fixed.
3267 // auto inbound_stream_stats =
3268 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3269 // ASSERT_EQ(2U, inbound_stream_stats.size());
3270}
3271
deadbeef1dcb1642017-03-29 21:08:16 -07003272// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003273TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003274 PeerConnectionFactory::Options dtls_10_options;
3275 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3276 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3277 dtls_10_options));
3278 ConnectFakeSignaling();
3279 // Do normal offer/answer and wait for some frames to be received in each
3280 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003281 caller()->AddAudioVideoTracks();
3282 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003283 caller()->CreateAndSetAndSignalOffer();
3284 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003285 MediaExpectations media_expectations;
3286 media_expectations.ExpectBidirectionalAudioAndVideo();
3287 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003288}
3289
3290// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003291TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003292 PeerConnectionFactory::Options dtls_10_options;
3293 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3294 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3295 dtls_10_options));
3296 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003297 caller()->AddAudioVideoTracks();
3298 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003299 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003300 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003301 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003302 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003303 kDefaultTimeout);
3304 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003305 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003306 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003307 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3308 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3309 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003310}
3311
3312// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003313TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003314 PeerConnectionFactory::Options dtls_12_options;
3315 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3316 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3317 dtls_12_options));
3318 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003319 caller()->AddAudioVideoTracks();
3320 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003321 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003322 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003323 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003324 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003325 kDefaultTimeout);
3326 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003327 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003328 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003329 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3330 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3331 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003332}
3333
3334// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3335// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003336TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003337 PeerConnectionFactory::Options caller_options;
3338 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3339 PeerConnectionFactory::Options callee_options;
3340 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3341 ASSERT_TRUE(
3342 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3343 ConnectFakeSignaling();
3344 // Do normal offer/answer and wait for some frames to be received in each
3345 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003346 caller()->AddAudioVideoTracks();
3347 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003348 caller()->CreateAndSetAndSignalOffer();
3349 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003350 MediaExpectations media_expectations;
3351 media_expectations.ExpectBidirectionalAudioAndVideo();
3352 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003353}
3354
3355// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3356// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003357TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003358 PeerConnectionFactory::Options caller_options;
3359 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3360 PeerConnectionFactory::Options callee_options;
3361 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3362 ASSERT_TRUE(
3363 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3364 ConnectFakeSignaling();
3365 // Do normal offer/answer and wait for some frames to be received in each
3366 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003367 caller()->AddAudioVideoTracks();
3368 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003369 caller()->CreateAndSetAndSignalOffer();
3370 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003371 MediaExpectations media_expectations;
3372 media_expectations.ExpectBidirectionalAudioAndVideo();
3373 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003374}
3375
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003376// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3377// works as expected; the cipher should only be used if enabled by both sides.
3378TEST_P(PeerConnectionIntegrationTest,
3379 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3380 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003381 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003382 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003383 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3384 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003385 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3386 TestNegotiatedCipherSuite(caller_options, callee_options,
3387 expected_cipher_suite);
3388}
3389
3390TEST_P(PeerConnectionIntegrationTest,
3391 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3392 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003393 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3394 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003395 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003396 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003397 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3398 TestNegotiatedCipherSuite(caller_options, callee_options,
3399 expected_cipher_suite);
3400}
3401
3402TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3403 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003404 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003405 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003406 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003407 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3408 TestNegotiatedCipherSuite(caller_options, callee_options,
3409 expected_cipher_suite);
3410}
3411
deadbeef1dcb1642017-03-29 21:08:16 -07003412// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003413TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003414 bool local_gcm_enabled = false;
3415 bool remote_gcm_enabled = false;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003416 bool aes_ctr_enabled = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003417 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3418 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003419 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003420}
3421
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003422// Test that a GCM cipher is used if both ends support it and non-GCM is
3423// disabled.
3424TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenOnlyGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003425 bool local_gcm_enabled = true;
3426 bool remote_gcm_enabled = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003427 bool aes_ctr_enabled = false;
deadbeef1dcb1642017-03-29 21:08:16 -07003428 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3429 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003430 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003431}
3432
deadbeef7914b8c2017-04-21 03:23:33 -07003433// Verify that media can be transmitted end-to-end when GCM crypto suites are
3434// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3435// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3436// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003437TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003438 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003439 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003440 gcm_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher = false;
deadbeef7914b8c2017-04-21 03:23:33 -07003441 ASSERT_TRUE(
3442 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3443 ConnectFakeSignaling();
3444 // Do normal offer/answer and wait for some frames to be received in each
3445 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003446 caller()->AddAudioVideoTracks();
3447 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003448 caller()->CreateAndSetAndSignalOffer();
3449 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003450 MediaExpectations media_expectations;
3451 media_expectations.ExpectBidirectionalAudioAndVideo();
3452 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003453}
3454
deadbeef1dcb1642017-03-29 21:08:16 -07003455// This test sets up a call between two parties with audio, video and an RTP
3456// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003457TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003458 PeerConnectionInterface::RTCConfiguration rtc_config;
3459 rtc_config.enable_rtp_data_channel = true;
3460 rtc_config.enable_dtls_srtp = false;
3461 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003462 ConnectFakeSignaling();
3463 // Expect that data channel created on caller side will show up for callee as
3464 // well.
3465 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003466 caller()->AddAudioVideoTracks();
3467 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003468 caller()->CreateAndSetAndSignalOffer();
3469 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3470 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003471 MediaExpectations media_expectations;
3472 media_expectations.ExpectBidirectionalAudioAndVideo();
3473 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003474 ASSERT_NE(nullptr, caller()->data_channel());
3475 ASSERT_NE(nullptr, callee()->data_channel());
3476 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3477 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3478
3479 // Ensure data can be sent in both directions.
3480 std::string data = "hello world";
3481 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3482 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3483 kDefaultTimeout);
3484 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3485 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3486 kDefaultTimeout);
3487}
3488
Eldar Rellod9ebe012020-03-18 20:41:45 +02003489TEST_P(PeerConnectionIntegrationTest, RtpDataChannelWorksAfterRollback) {
3490 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));
3494 ConnectFakeSignaling();
3495 auto data_channel = caller()->pc()->CreateDataChannel("label_1", nullptr);
3496 ASSERT_TRUE(data_channel.get() != nullptr);
3497 caller()->CreateAndSetAndSignalOffer();
3498 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3499
3500 caller()->CreateDataChannel("label_2", nullptr);
3501 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
3502 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
3503 caller()->pc()->SetLocalDescription(observer,
3504 caller()->CreateOfferAndWait().release());
3505 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
3506 caller()->Rollback();
3507
3508 std::string data = "hello world";
3509 SendRtpDataWithRetries(data_channel, data, 5);
3510 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3511 kDefaultTimeout);
3512}
3513
deadbeef1dcb1642017-03-29 21:08:16 -07003514// Ensure that an RTP data channel is signaled as closed for the caller when
3515// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003516TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003517 RtpDataChannelSignaledClosedInCalleeOffer) {
3518 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003519 PeerConnectionInterface::RTCConfiguration rtc_config;
3520 rtc_config.enable_rtp_data_channel = true;
3521 rtc_config.enable_dtls_srtp = false;
3522 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003523 ConnectFakeSignaling();
3524 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003525 caller()->AddAudioVideoTracks();
3526 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003527 caller()->CreateAndSetAndSignalOffer();
3528 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3529 ASSERT_NE(nullptr, caller()->data_channel());
3530 ASSERT_NE(nullptr, callee()->data_channel());
3531 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3532 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3533
3534 // Close the data channel on the callee, and do an updated offer/answer.
3535 callee()->data_channel()->Close();
3536 callee()->CreateAndSetAndSignalOffer();
3537 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3538 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3539 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3540}
3541
3542// Tests that data is buffered in an RTP data channel until an observer is
3543// registered for it.
3544//
3545// NOTE: RTP data channels can receive data before the underlying
3546// transport has detected that a channel is writable and thus data can be
3547// received before the data channel state changes to open. That is hard to test
3548// but the same buffering is expected to be used in that case.
Yves Gerey100fe632020-01-17 19:15:53 +01003549//
3550// Use fake clock and simulated network delay so that we predictably can wait
3551// until an SCTP message has been delivered without "sleep()"ing.
3552TEST_P(PeerConnectionIntegrationTestWithFakeClock,
deadbeef1dcb1642017-03-29 21:08:16 -07003553 DataBufferedUntilRtpDataChannelObserverRegistered) {
deadbeef1dcb1642017-03-29 21:08:16 -07003554 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3555 virtual_socket_server()->UpdateDelayDistribution();
3556
Niels Möllerf06f9232018-08-07 12:32:18 +02003557 PeerConnectionInterface::RTCConfiguration rtc_config;
3558 rtc_config.enable_rtp_data_channel = true;
3559 rtc_config.enable_dtls_srtp = false;
3560 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003561 ConnectFakeSignaling();
3562 caller()->CreateDataChannel();
3563 caller()->CreateAndSetAndSignalOffer();
3564 ASSERT_TRUE(caller()->data_channel() != nullptr);
3565 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
Yves Gerey100fe632020-01-17 19:15:53 +01003566 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003567 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
Yves Gerey100fe632020-01-17 19:15:53 +01003568 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003569 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3570 callee()->data_channel()->state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003571 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003572
3573 // Unregister the observer which is normally automatically registered.
3574 callee()->data_channel()->UnregisterObserver();
3575 // Send data and advance fake clock until it should have been received.
3576 std::string data = "hello world";
3577 caller()->data_channel()->Send(DataBuffer(data));
Yves Gerey100fe632020-01-17 19:15:53 +01003578 SIMULATED_WAIT(false, 50, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003579
3580 // Attach data channel and expect data to be received immediately. Note that
3581 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3582 // further, but data can be received even if the callback is asynchronous.
3583 MockDataChannelObserver new_observer(callee()->data_channel());
3584 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003585 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003586}
3587
3588// This test sets up a call between two parties with audio, video and but only
3589// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003590TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003591 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3592 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003593 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003594 rtc_config_1.enable_dtls_srtp = false;
3595 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3596 rtc_config_2.enable_dtls_srtp = false;
3597 rtc_config_2.enable_dtls_srtp = false;
3598 ASSERT_TRUE(
3599 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003600 ConnectFakeSignaling();
3601 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003602 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003603 caller()->AddAudioVideoTracks();
3604 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003605 caller()->CreateAndSetAndSignalOffer();
3606 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3607 // The caller should still have a data channel, but it should be closed, and
3608 // one should ever have been created for the callee.
3609 EXPECT_TRUE(caller()->data_channel() != nullptr);
3610 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3611 EXPECT_EQ(nullptr, callee()->data_channel());
3612}
3613
3614// This test sets up a call between two parties with audio, and video. When
3615// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003616TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003617 PeerConnectionInterface::RTCConfiguration rtc_config;
3618 rtc_config.enable_rtp_data_channel = true;
3619 rtc_config.enable_dtls_srtp = false;
3620 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003621 ConnectFakeSignaling();
3622 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003623 caller()->AddAudioVideoTracks();
3624 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003625 caller()->CreateAndSetAndSignalOffer();
3626 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3627 // Create data channel and do new offer and answer.
3628 caller()->CreateDataChannel();
3629 caller()->CreateAndSetAndSignalOffer();
3630 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3631 ASSERT_NE(nullptr, caller()->data_channel());
3632 ASSERT_NE(nullptr, callee()->data_channel());
3633 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3634 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3635 // Ensure data can be sent in both directions.
3636 std::string data = "hello world";
3637 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3638 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3639 kDefaultTimeout);
3640 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3641 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3642 kDefaultTimeout);
3643}
3644
3645#ifdef HAVE_SCTP
3646
3647// This test sets up a call between two parties with audio, video and an SCTP
3648// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003649TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003650 ASSERT_TRUE(CreatePeerConnectionWrappers());
3651 ConnectFakeSignaling();
3652 // Expect that data channel created on caller side will show up for callee as
3653 // well.
3654 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003655 caller()->AddAudioVideoTracks();
3656 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003657 caller()->CreateAndSetAndSignalOffer();
3658 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3659 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003660 MediaExpectations media_expectations;
3661 media_expectations.ExpectBidirectionalAudioAndVideo();
3662 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003663 // Caller data channel should already exist (it created one). Callee data
3664 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3665 ASSERT_NE(nullptr, caller()->data_channel());
3666 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3667 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3668 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3669
3670 // Ensure data can be sent in both directions.
3671 std::string data = "hello world";
3672 caller()->data_channel()->Send(DataBuffer(data));
3673 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3674 kDefaultTimeout);
3675 callee()->data_channel()->Send(DataBuffer(data));
3676 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3677 kDefaultTimeout);
3678}
3679
3680// Ensure that when the callee closes an SCTP data channel, the closing
3681// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003682TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003683 // Same procedure as above test.
3684 ASSERT_TRUE(CreatePeerConnectionWrappers());
3685 ConnectFakeSignaling();
3686 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003687 caller()->AddAudioVideoTracks();
3688 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003689 caller()->CreateAndSetAndSignalOffer();
3690 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3691 ASSERT_NE(nullptr, caller()->data_channel());
3692 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3693 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3694 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3695
3696 // Close the data channel on the callee side, and wait for it to reach the
3697 // "closed" state on both sides.
3698 callee()->data_channel()->Close();
3699 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3700 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3701}
3702
Seth Hampson2f0d7022018-02-20 11:54:42 -08003703TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003704 ASSERT_TRUE(CreatePeerConnectionWrappers());
3705 ConnectFakeSignaling();
3706 webrtc::DataChannelInit init;
3707 init.id = 53;
3708 init.maxRetransmits = 52;
3709 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003710 caller()->AddAudioVideoTracks();
3711 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003712 caller()->CreateAndSetAndSignalOffer();
3713 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003714 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3715 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003716 // Since "negotiated" is false, the "id" parameter should be ignored.
3717 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003718 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3719 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3720 EXPECT_FALSE(callee()->data_channel()->negotiated());
3721}
3722
deadbeef1dcb1642017-03-29 21:08:16 -07003723// Test usrsctp's ability to process unordered data stream, where data actually
3724// arrives out of order using simulated delays. Previously there have been some
3725// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003726TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003727 // Introduce random network delays.
3728 // Otherwise it's not a true "unordered" test.
3729 virtual_socket_server()->set_delay_mean(20);
3730 virtual_socket_server()->set_delay_stddev(5);
3731 virtual_socket_server()->UpdateDelayDistribution();
3732 // Normal procedure, but with unordered data channel config.
3733 ASSERT_TRUE(CreatePeerConnectionWrappers());
3734 ConnectFakeSignaling();
3735 webrtc::DataChannelInit init;
3736 init.ordered = false;
3737 caller()->CreateDataChannel(&init);
3738 caller()->CreateAndSetAndSignalOffer();
3739 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3740 ASSERT_NE(nullptr, caller()->data_channel());
3741 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3742 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3743 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3744
3745 static constexpr int kNumMessages = 100;
3746 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3747 static constexpr size_t kMaxMessageSize = 4096;
3748 // Create and send random messages.
3749 std::vector<std::string> sent_messages;
3750 for (int i = 0; i < kNumMessages; ++i) {
3751 size_t length =
3752 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3753 std::string message;
3754 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3755 caller()->data_channel()->Send(DataBuffer(message));
3756 callee()->data_channel()->Send(DataBuffer(message));
3757 sent_messages.push_back(message);
3758 }
3759
3760 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003761 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003762 caller()->data_observer()->received_message_count(),
3763 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003764 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003765 callee()->data_observer()->received_message_count(),
3766 kDefaultTimeout);
3767
3768 // Sort and compare to make sure none of the messages were corrupted.
3769 std::vector<std::string> caller_received_messages =
3770 caller()->data_observer()->messages();
3771 std::vector<std::string> callee_received_messages =
3772 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003773 absl::c_sort(sent_messages);
3774 absl::c_sort(caller_received_messages);
3775 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003776 EXPECT_EQ(sent_messages, caller_received_messages);
3777 EXPECT_EQ(sent_messages, callee_received_messages);
3778}
3779
3780// This test sets up a call between two parties with audio, and video. When
3781// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003782TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003783 ASSERT_TRUE(CreatePeerConnectionWrappers());
3784 ConnectFakeSignaling();
3785 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003786 caller()->AddAudioVideoTracks();
3787 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003788 caller()->CreateAndSetAndSignalOffer();
3789 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3790 // Create data channel and do new offer and answer.
3791 caller()->CreateDataChannel();
3792 caller()->CreateAndSetAndSignalOffer();
3793 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3794 // Caller data channel should already exist (it created one). Callee data
3795 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3796 ASSERT_NE(nullptr, caller()->data_channel());
3797 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3798 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3799 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3800 // Ensure data can be sent in both directions.
3801 std::string data = "hello world";
3802 caller()->data_channel()->Send(DataBuffer(data));
3803 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3804 kDefaultTimeout);
3805 callee()->data_channel()->Send(DataBuffer(data));
3806 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3807 kDefaultTimeout);
3808}
3809
deadbeef7914b8c2017-04-21 03:23:33 -07003810// Set up a connection initially just using SCTP data channels, later upgrading
3811// to audio/video, ensuring frames are received end-to-end. Effectively the
3812// inverse of the test above.
3813// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003814TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003815 ASSERT_TRUE(CreatePeerConnectionWrappers());
3816 ConnectFakeSignaling();
3817 // Do initial offer/answer with just data channel.
3818 caller()->CreateDataChannel();
3819 caller()->CreateAndSetAndSignalOffer();
3820 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3821 // Wait until data can be sent over the data channel.
3822 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3823 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3824 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3825
3826 // Do subsequent offer/answer with two-way audio and video. Audio and video
3827 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003828 caller()->AddAudioVideoTracks();
3829 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003830 caller()->CreateAndSetAndSignalOffer();
3831 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003832 MediaExpectations media_expectations;
3833 media_expectations.ExpectBidirectionalAudioAndVideo();
3834 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003835}
3836
deadbeef8b7e9ad2017-05-25 09:38:55 -07003837static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003838 cricket::SctpDataContentDescription* dcd_offer =
3839 GetFirstSctpDataContentDescription(desc);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01003840 // See https://crbug.com/webrtc/11211 - this function is a no-op
Steve Antonb1c1de12017-12-21 15:14:30 -08003841 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003842 dcd_offer->set_use_sctpmap(false);
3843 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3844}
3845
3846// Test that the data channel works when a spec-compliant SCTP m= section is
3847// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3848// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003849TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003850 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3851 ASSERT_TRUE(CreatePeerConnectionWrappers());
3852 ConnectFakeSignaling();
3853 caller()->CreateDataChannel();
3854 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3855 caller()->CreateAndSetAndSignalOffer();
3856 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3857 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3858 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3859 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3860
3861 // Ensure data can be sent in both directions.
3862 std::string data = "hello world";
3863 caller()->data_channel()->Send(DataBuffer(data));
3864 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3865 kDefaultTimeout);
3866 callee()->data_channel()->Send(DataBuffer(data));
3867 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3868 kDefaultTimeout);
3869}
3870
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003871// Tests that the datagram transport to SCTP fallback works correctly when
3872// datagram transport negotiation fails.
3873TEST_P(PeerConnectionIntegrationTest,
3874 DatagramTransportDataChannelFallbackToSctp) {
3875 PeerConnectionInterface::RTCConfiguration rtc_config;
3876 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3877 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3878 rtc_config.use_datagram_transport_for_data_channels = true;
3879
3880 // Configure one endpoint to use datagram transport for data channels while
3881 // the other does not.
3882 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3883 rtc_config, RTCConfiguration(),
3884 loopback_media_transports()->first_factory(), nullptr));
3885 ConnectFakeSignaling();
3886
3887 // The caller offers a data channel using either datagram transport or SCTP.
3888 caller()->CreateDataChannel();
3889 caller()->AddAudioVideoTracks();
3890 callee()->AddAudioVideoTracks();
3891 caller()->CreateAndSetAndSignalOffer();
3892 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3893
3894 // Negotiation should fallback to SCTP, allowing the data channel to be
3895 // established.
3896 ASSERT_NE(nullptr, caller()->data_channel());
3897 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3898 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3899 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3900
3901 // Ensure data can be sent in both directions.
3902 std::string data = "hello world";
3903 caller()->data_channel()->Send(DataBuffer(data));
3904 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3905 kDefaultTimeout);
3906 callee()->data_channel()->Send(DataBuffer(data));
3907 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3908 kDefaultTimeout);
3909
3910 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3911 MediaExpectations media_expectations;
3912 media_expectations.ExpectBidirectionalAudioAndVideo();
3913 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3914}
3915
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07003916// Tests that the data channel transport works correctly when datagram transport
3917// negotiation succeeds and does not fall back to SCTP.
3918TEST_P(PeerConnectionIntegrationTest,
3919 DatagramTransportDataChannelDoesNotFallbackToSctp) {
3920 PeerConnectionInterface::RTCConfiguration rtc_config;
3921 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3922 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3923 rtc_config.use_datagram_transport_for_data_channels = true;
3924
3925 // Configure one endpoint to use datagram transport for data channels while
3926 // the other does not.
3927 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3928 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3929 loopback_media_transports()->second_factory()));
3930 ConnectFakeSignaling();
3931
3932 // The caller offers a data channel using either datagram transport or SCTP.
3933 caller()->CreateDataChannel();
3934 caller()->AddAudioVideoTracks();
3935 callee()->AddAudioVideoTracks();
3936 caller()->CreateAndSetAndSignalOffer();
3937 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3938
3939 // Ensure that the data channel transport is ready.
3940 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3941 loopback_media_transports()->FlushAsyncInvokes();
3942
3943 // Negotiation should succeed, allowing the data channel to be established.
3944 ASSERT_NE(nullptr, caller()->data_channel());
3945 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3946 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3947 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3948
3949 // Ensure data can be sent in both directions.
3950 std::string data = "hello world";
3951 caller()->data_channel()->Send(DataBuffer(data));
3952 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3953 kDefaultTimeout);
3954 callee()->data_channel()->Send(DataBuffer(data));
3955 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3956 kDefaultTimeout);
3957
3958 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3959 MediaExpectations media_expectations;
3960 media_expectations.ExpectBidirectionalAudioAndVideo();
3961 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3962}
3963
Bjorn A Mellem0cda7b82020-01-28 17:06:55 -08003964// Tests that the datagram transport to SCTP fallback works correctly when
3965// datagram transports do not advertise compatible transport parameters.
3966TEST_P(PeerConnectionIntegrationTest,
3967 DatagramTransportIncompatibleParametersFallsBackToSctp) {
3968 PeerConnectionInterface::RTCConfiguration rtc_config;
3969 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3970 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3971 rtc_config.use_datagram_transport_for_data_channels = true;
3972
3973 // By default, only equal parameters are compatible.
3974 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
3975 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
3976
3977 // Configure one endpoint to use datagram transport for data channels while
3978 // the other does not.
3979 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3980 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3981 loopback_media_transports()->second_factory()));
3982 ConnectFakeSignaling();
3983
3984 // The caller offers a data channel using either datagram transport or SCTP.
3985 caller()->CreateDataChannel();
3986 caller()->AddAudioVideoTracks();
3987 callee()->AddAudioVideoTracks();
3988 caller()->CreateAndSetAndSignalOffer();
3989 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3990
3991 // Negotiation should fallback to SCTP, allowing the data channel to be
3992 // established.
3993 ASSERT_NE(nullptr, caller()->data_channel());
3994 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3995 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3996 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3997
3998 // Both endpoints should agree to use SCTP for data channels.
3999 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4000 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4001
4002 // Ensure data can be sent in both directions.
4003 std::string data = "hello world";
4004 caller()->data_channel()->Send(DataBuffer(data));
4005 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4006 kDefaultTimeout);
4007 callee()->data_channel()->Send(DataBuffer(data));
4008 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4009 kDefaultTimeout);
4010
4011 // Ensure that failure of the datagram negotiation doesn't impede media flow.
4012 MediaExpectations media_expectations;
4013 media_expectations.ExpectBidirectionalAudioAndVideo();
4014 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4015}
4016
4017// Tests that the datagram transport to SCTP fallback works correctly when
4018// only the answerer believes datagram transport parameters are incompatible.
4019TEST_P(PeerConnectionIntegrationTest,
4020 DatagramTransportIncompatibleParametersOnAnswererFallsBackToSctp) {
4021 PeerConnectionInterface::RTCConfiguration rtc_config;
4022 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4023 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4024 rtc_config.use_datagram_transport_for_data_channels = true;
4025
4026 // By default, only equal parameters are compatible.
4027 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
4028 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
4029
4030 // Set the offerer to accept different parameters, while the answerer rejects
4031 // them.
4032 loopback_media_transports()->SetFirstDatagramTransportParametersComparison(
4033 [](absl::string_view a, absl::string_view b) { return true; });
4034 loopback_media_transports()->SetSecondDatagramTransportParametersComparison(
4035 [](absl::string_view a, absl::string_view b) { return false; });
4036
4037 // Configure one endpoint to use datagram transport for data channels while
4038 // the other does not.
4039 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4040 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4041 loopback_media_transports()->second_factory()));
4042 ConnectFakeSignaling();
4043
4044 // The caller offers a data channel using either datagram transport or SCTP.
4045 caller()->CreateDataChannel();
4046 caller()->AddAudioVideoTracks();
4047 callee()->AddAudioVideoTracks();
4048 caller()->CreateAndSetAndSignalOffer();
4049 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4050
4051 // Negotiation should fallback to SCTP, allowing the data channel to be
4052 // established.
4053 ASSERT_NE(nullptr, caller()->data_channel());
4054 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4055 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4056 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4057
4058 // Both endpoints should agree to use SCTP for data channels.
4059 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4060 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4061
4062 // Ensure data can be sent in both directions.
4063 std::string data = "hello world";
4064 caller()->data_channel()->Send(DataBuffer(data));
4065 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4066 kDefaultTimeout);
4067 callee()->data_channel()->Send(DataBuffer(data));
4068 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4069 kDefaultTimeout);
4070
4071 // Ensure that failure of the datagram negotiation doesn't impede media flow.
4072 MediaExpectations media_expectations;
4073 media_expectations.ExpectBidirectionalAudioAndVideo();
4074 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4075}
4076
4077// Tests that the data channel transport works correctly when datagram
4078// transports provide different, but compatible, transport parameters.
4079TEST_P(PeerConnectionIntegrationTest,
4080 DatagramTransportCompatibleParametersDoNotFallbackToSctp) {
4081 PeerConnectionInterface::RTCConfiguration rtc_config;
4082 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4083 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4084 rtc_config.use_datagram_transport_for_data_channels = true;
4085
4086 // By default, only equal parameters are compatible.
4087 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
4088 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
4089
4090 // Change the comparison used to treat these transport parameters are
4091 // compatible (on both sides).
4092 loopback_media_transports()->SetFirstDatagramTransportParametersComparison(
4093 [](absl::string_view a, absl::string_view b) { return true; });
4094 loopback_media_transports()->SetSecondDatagramTransportParametersComparison(
4095 [](absl::string_view a, absl::string_view b) { return true; });
4096
4097 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4098 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4099 loopback_media_transports()->second_factory()));
4100 ConnectFakeSignaling();
4101
4102 // The caller offers a data channel using either datagram transport or SCTP.
4103 caller()->CreateDataChannel();
4104 caller()->AddAudioVideoTracks();
4105 callee()->AddAudioVideoTracks();
4106 caller()->CreateAndSetAndSignalOffer();
4107 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4108
4109 // Ensure that the data channel transport is ready.
4110 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4111 loopback_media_transports()->FlushAsyncInvokes();
4112
4113 // Negotiation should succeed, allowing the data channel to be established.
4114 ASSERT_NE(nullptr, caller()->data_channel());
4115 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4116 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4117 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4118
4119 // Both endpoints should agree to use datagram transport for data channels.
4120 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4121 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4122
4123 // Ensure data can be sent in both directions.
4124 std::string data = "hello world";
4125 caller()->data_channel()->Send(DataBuffer(data));
4126 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4127 kDefaultTimeout);
4128 callee()->data_channel()->Send(DataBuffer(data));
4129 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4130 kDefaultTimeout);
4131
4132 // Ensure that failure of the datagram negotiation doesn't impede media flow.
4133 MediaExpectations media_expectations;
4134 media_expectations.ExpectBidirectionalAudioAndVideo();
4135 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4136}
4137
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07004138TEST_P(PeerConnectionIntegrationTest,
4139 DatagramTransportDataChannelWithMediaOnCaller) {
4140 // Configure the caller to attempt use of datagram transport for media and
4141 // data channels.
4142 PeerConnectionInterface::RTCConfiguration offerer_config;
4143 offerer_config.rtcp_mux_policy =
4144 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4145 offerer_config.bundle_policy =
4146 PeerConnectionInterface::kBundlePolicyMaxBundle;
4147 offerer_config.use_datagram_transport_for_data_channels = true;
4148 offerer_config.use_datagram_transport = true;
4149
4150 // Configure the callee to only use datagram transport for data channels.
4151 PeerConnectionInterface::RTCConfiguration answerer_config;
4152 answerer_config.rtcp_mux_policy =
4153 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4154 answerer_config.bundle_policy =
4155 PeerConnectionInterface::kBundlePolicyMaxBundle;
4156 answerer_config.use_datagram_transport_for_data_channels = true;
4157
4158 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4159 offerer_config, answerer_config,
4160 loopback_media_transports()->first_factory(),
4161 loopback_media_transports()->second_factory()));
4162 ConnectFakeSignaling();
4163
4164 // Offer both media and data.
4165 caller()->AddAudioVideoTracks();
4166 callee()->AddAudioVideoTracks();
4167 caller()->CreateDataChannel();
4168 caller()->CreateAndSetAndSignalOffer();
4169 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4170
4171 // Ensure that the data channel transport is ready.
4172 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4173 loopback_media_transports()->FlushAsyncInvokes();
4174
4175 ASSERT_NE(nullptr, caller()->data_channel());
4176 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4177 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4178 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4179
4180 // Both endpoints should agree to use datagram transport for data channels.
4181 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4182 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4183
4184 // Ensure data can be sent in both directions.
4185 std::string data = "hello world";
4186 caller()->data_channel()->Send(DataBuffer(data));
4187 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4188 kDefaultTimeout);
4189 callee()->data_channel()->Send(DataBuffer(data));
4190 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4191 kDefaultTimeout);
4192
4193 // Media flow should not be impacted.
4194 MediaExpectations media_expectations;
4195 media_expectations.ExpectBidirectionalAudioAndVideo();
4196 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4197}
4198
4199TEST_P(PeerConnectionIntegrationTest,
4200 DatagramTransportMediaWithDataChannelOnCaller) {
4201 // Configure the caller to attempt use of datagram transport for media and
4202 // data channels.
4203 PeerConnectionInterface::RTCConfiguration offerer_config;
4204 offerer_config.rtcp_mux_policy =
4205 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4206 offerer_config.bundle_policy =
4207 PeerConnectionInterface::kBundlePolicyMaxBundle;
4208 offerer_config.use_datagram_transport_for_data_channels = true;
4209 offerer_config.use_datagram_transport = true;
4210
4211 // Configure the callee to only use datagram transport for media.
4212 PeerConnectionInterface::RTCConfiguration answerer_config;
4213 answerer_config.rtcp_mux_policy =
4214 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4215 answerer_config.bundle_policy =
4216 PeerConnectionInterface::kBundlePolicyMaxBundle;
4217 answerer_config.use_datagram_transport = true;
4218
4219 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4220 offerer_config, answerer_config,
4221 loopback_media_transports()->first_factory(),
4222 loopback_media_transports()->second_factory()));
4223 ConnectFakeSignaling();
4224
4225 // Offer both media and data.
4226 caller()->AddAudioVideoTracks();
4227 callee()->AddAudioVideoTracks();
4228 caller()->CreateDataChannel();
4229 caller()->CreateAndSetAndSignalOffer();
4230 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4231
4232 // Ensure that the data channel transport is ready.
4233 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4234 loopback_media_transports()->FlushAsyncInvokes();
4235
4236 ASSERT_NE(nullptr, caller()->data_channel());
4237 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4238 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4239 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4240
4241 // Both endpoints should agree to use SCTP for data channels.
4242 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4243 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4244
4245 // Ensure data can be sent in both directions.
4246 std::string data = "hello world";
4247 caller()->data_channel()->Send(DataBuffer(data));
4248 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4249 kDefaultTimeout);
4250 callee()->data_channel()->Send(DataBuffer(data));
4251 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4252 kDefaultTimeout);
4253
4254 // Media flow should not be impacted.
4255 MediaExpectations media_expectations;
4256 media_expectations.ExpectBidirectionalAudioAndVideo();
4257 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4258}
4259
4260TEST_P(PeerConnectionIntegrationTest,
4261 DatagramTransportDataChannelWithMediaOnCallee) {
4262 // Configure the caller to attempt use of datagram transport for data
4263 // channels.
4264 PeerConnectionInterface::RTCConfiguration offerer_config;
4265 offerer_config.rtcp_mux_policy =
4266 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4267 offerer_config.bundle_policy =
4268 PeerConnectionInterface::kBundlePolicyMaxBundle;
4269 offerer_config.use_datagram_transport_for_data_channels = true;
4270
4271 // Configure the callee to use datagram transport for data channels and media.
4272 PeerConnectionInterface::RTCConfiguration answerer_config;
4273 answerer_config.rtcp_mux_policy =
4274 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4275 answerer_config.bundle_policy =
4276 PeerConnectionInterface::kBundlePolicyMaxBundle;
4277 answerer_config.use_datagram_transport_for_data_channels = true;
4278 answerer_config.use_datagram_transport = true;
4279
4280 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4281 offerer_config, answerer_config,
4282 loopback_media_transports()->first_factory(),
4283 loopback_media_transports()->second_factory()));
4284 ConnectFakeSignaling();
4285
4286 // Offer both media and data.
4287 caller()->AddAudioVideoTracks();
4288 callee()->AddAudioVideoTracks();
4289 caller()->CreateDataChannel();
4290 caller()->CreateAndSetAndSignalOffer();
4291 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4292
4293 // Ensure that the data channel transport is ready.
4294 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4295 loopback_media_transports()->FlushAsyncInvokes();
4296
4297 ASSERT_NE(nullptr, caller()->data_channel());
4298 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4299 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4300 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4301
4302 // Both endpoints should agree to use datagram transport for data channels.
4303 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4304 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4305
4306 // Ensure data can be sent in both directions.
4307 std::string data = "hello world";
4308 caller()->data_channel()->Send(DataBuffer(data));
4309 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4310 kDefaultTimeout);
4311 callee()->data_channel()->Send(DataBuffer(data));
4312 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4313 kDefaultTimeout);
4314
4315 // Media flow should not be impacted.
4316 MediaExpectations media_expectations;
4317 media_expectations.ExpectBidirectionalAudioAndVideo();
4318 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4319}
4320
4321TEST_P(PeerConnectionIntegrationTest,
4322 DatagramTransportMediaWithDataChannelOnCallee) {
4323 // Configure the caller to attempt use of datagram transport for media.
4324 PeerConnectionInterface::RTCConfiguration offerer_config;
4325 offerer_config.rtcp_mux_policy =
4326 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4327 offerer_config.bundle_policy =
4328 PeerConnectionInterface::kBundlePolicyMaxBundle;
4329 offerer_config.use_datagram_transport = true;
4330
4331 // Configure the callee to only use datagram transport for media and data
4332 // channels.
4333 PeerConnectionInterface::RTCConfiguration answerer_config;
4334 answerer_config.rtcp_mux_policy =
4335 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4336 answerer_config.bundle_policy =
4337 PeerConnectionInterface::kBundlePolicyMaxBundle;
4338 answerer_config.use_datagram_transport = true;
4339 answerer_config.use_datagram_transport_for_data_channels = true;
4340
4341 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4342 offerer_config, answerer_config,
4343 loopback_media_transports()->first_factory(),
4344 loopback_media_transports()->second_factory()));
4345 ConnectFakeSignaling();
4346
4347 // Offer both media and data.
4348 caller()->AddAudioVideoTracks();
4349 callee()->AddAudioVideoTracks();
4350 caller()->CreateDataChannel();
4351 caller()->CreateAndSetAndSignalOffer();
4352 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4353
4354 // Ensure that the data channel transport is ready.
4355 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4356 loopback_media_transports()->FlushAsyncInvokes();
4357
4358 ASSERT_NE(nullptr, caller()->data_channel());
4359 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4360 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4361 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4362
4363 // Both endpoints should agree to use SCTP for data channels.
4364 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4365 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4366
4367 // Ensure data can be sent in both directions.
4368 std::string data = "hello world";
4369 caller()->data_channel()->Send(DataBuffer(data));
4370 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4371 kDefaultTimeout);
4372 callee()->data_channel()->Send(DataBuffer(data));
4373 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4374 kDefaultTimeout);
4375
4376 // Media flow should not be impacted.
4377 MediaExpectations media_expectations;
4378 media_expectations.ExpectBidirectionalAudioAndVideo();
4379 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4380}
4381
4382TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelAndMedia) {
4383 // Configure the caller to use datagram transport for data channels and media.
4384 PeerConnectionInterface::RTCConfiguration offerer_config;
4385 offerer_config.rtcp_mux_policy =
4386 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4387 offerer_config.bundle_policy =
4388 PeerConnectionInterface::kBundlePolicyMaxBundle;
4389 offerer_config.use_datagram_transport_for_data_channels = true;
4390 offerer_config.use_datagram_transport = true;
4391
4392 // Configure the callee to use datagram transport for data channels and media.
4393 PeerConnectionInterface::RTCConfiguration answerer_config;
4394 answerer_config.rtcp_mux_policy =
4395 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4396 answerer_config.bundle_policy =
4397 PeerConnectionInterface::kBundlePolicyMaxBundle;
4398 answerer_config.use_datagram_transport_for_data_channels = true;
4399 answerer_config.use_datagram_transport = true;
4400
4401 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4402 offerer_config, answerer_config,
4403 loopback_media_transports()->first_factory(),
4404 loopback_media_transports()->second_factory()));
4405 ConnectFakeSignaling();
4406
4407 // Offer both media and data.
4408 caller()->AddAudioVideoTracks();
4409 callee()->AddAudioVideoTracks();
4410 caller()->CreateDataChannel();
4411 caller()->CreateAndSetAndSignalOffer();
4412 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4413
4414 // Ensure that the data channel transport is ready.
4415 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4416 loopback_media_transports()->FlushAsyncInvokes();
4417
4418 ASSERT_NE(nullptr, caller()->data_channel());
4419 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4420 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4421 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4422
4423 // Both endpoints should agree to use datagram transport for data channels.
4424 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4425 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4426
4427 // Ensure data can be sent in both directions.
4428 std::string data = "hello world";
4429 caller()->data_channel()->Send(DataBuffer(data));
4430 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4431 kDefaultTimeout);
4432 callee()->data_channel()->Send(DataBuffer(data));
4433 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4434 kDefaultTimeout);
4435
4436 // Media flow should not be impacted.
4437 MediaExpectations media_expectations;
4438 media_expectations.ExpectBidirectionalAudioAndVideo();
4439 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4440}
4441
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004442// Tests that data channels use SCTP instead of datagram transport if datagram
4443// transport is configured in receive-only mode on the caller.
4444TEST_P(PeerConnectionIntegrationTest,
4445 DatagramTransportDataChannelReceiveOnlyOnCallerUsesSctp) {
4446 PeerConnectionInterface::RTCConfiguration rtc_config;
4447 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4448 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4449 rtc_config.use_datagram_transport_for_data_channels = true;
4450 rtc_config.use_datagram_transport_for_data_channels_receive_only = true;
4451
4452 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4453 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4454 loopback_media_transports()->second_factory()));
4455 ConnectFakeSignaling();
4456
4457 // The caller should offer a data channel using SCTP.
4458 caller()->CreateDataChannel();
4459 caller()->AddAudioVideoTracks();
4460 callee()->AddAudioVideoTracks();
4461 caller()->CreateAndSetAndSignalOffer();
4462 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4463
4464 ASSERT_NE(nullptr, caller()->data_channel());
4465 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4466 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4467 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4468
4469 // SCTP transports should be present, since they are in use.
4470 EXPECT_NE(caller()->pc()->GetSctpTransport(), nullptr);
4471 EXPECT_NE(callee()->pc()->GetSctpTransport(), nullptr);
4472
4473 // Ensure data can be sent in both directions.
4474 std::string data = "hello world";
4475 caller()->data_channel()->Send(DataBuffer(data));
4476 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4477 kDefaultTimeout);
4478 callee()->data_channel()->Send(DataBuffer(data));
4479 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4480 kDefaultTimeout);
4481}
4482
deadbeef1dcb1642017-03-29 21:08:16 -07004483#endif // HAVE_SCTP
4484
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004485// Tests that a callee configured for receive-only use of datagram transport
4486// data channels accepts them on incoming calls.
4487TEST_P(PeerConnectionIntegrationTest,
4488 DatagramTransportDataChannelReceiveOnlyOnCallee) {
4489 PeerConnectionInterface::RTCConfiguration offerer_config;
4490 offerer_config.rtcp_mux_policy =
4491 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4492 offerer_config.bundle_policy =
4493 PeerConnectionInterface::kBundlePolicyMaxBundle;
4494 offerer_config.use_datagram_transport_for_data_channels = true;
4495
4496 PeerConnectionInterface::RTCConfiguration answerer_config;
4497 answerer_config.rtcp_mux_policy =
4498 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4499 answerer_config.bundle_policy =
4500 PeerConnectionInterface::kBundlePolicyMaxBundle;
4501 answerer_config.use_datagram_transport_for_data_channels = true;
4502 answerer_config.use_datagram_transport_for_data_channels_receive_only = true;
4503
4504 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4505 offerer_config, answerer_config,
4506 loopback_media_transports()->first_factory(),
4507 loopback_media_transports()->second_factory()));
4508 ConnectFakeSignaling();
4509
4510 caller()->CreateDataChannel();
4511 caller()->CreateAndSetAndSignalOffer();
4512 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4513
4514 // Ensure that the data channel transport is ready.
4515 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4516 loopback_media_transports()->FlushAsyncInvokes();
4517
4518 ASSERT_NE(nullptr, caller()->data_channel());
4519 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4520 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4521 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4522
4523 // SCTP transports should not be present, since datagram transport is used.
4524 EXPECT_EQ(caller()->pc()->GetSctpTransport(), nullptr);
4525 EXPECT_EQ(callee()->pc()->GetSctpTransport(), nullptr);
4526
4527 // Ensure data can be sent in both directions.
4528 std::string data = "hello world";
4529 caller()->data_channel()->Send(DataBuffer(data));
4530 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4531 kDefaultTimeout);
4532 callee()->data_channel()->Send(DataBuffer(data));
4533 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4534 kDefaultTimeout);
4535}
4536
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004537// This test sets up a call between two parties with a datagram transport data
4538// channel.
4539TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelEndToEnd) {
4540 PeerConnectionInterface::RTCConfiguration rtc_config;
4541 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4542 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4543 rtc_config.use_datagram_transport_for_data_channels = true;
4544 rtc_config.enable_dtls_srtp = false;
4545 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4546 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4547 loopback_media_transports()->second_factory()));
4548 ConnectFakeSignaling();
4549
4550 // Expect that data channel created on caller side will show up for callee as
4551 // well.
4552 caller()->CreateDataChannel();
4553 caller()->CreateAndSetAndSignalOffer();
4554 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4555
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004556 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004557 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4558 loopback_media_transports()->FlushAsyncInvokes();
4559
4560 // Caller data channel should already exist (it created one). Callee data
4561 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4562 ASSERT_NE(nullptr, caller()->data_channel());
4563 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4564 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4565 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4566
4567 // Ensure data can be sent in both directions.
4568 std::string data = "hello world";
4569 caller()->data_channel()->Send(DataBuffer(data));
4570 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4571 kDefaultTimeout);
4572 callee()->data_channel()->Send(DataBuffer(data));
4573 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4574 kDefaultTimeout);
4575}
4576
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004577// Tests that 'zero-rtt' data channel transports (which are ready-to-send as
4578// soon as they're created) work correctly.
4579TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelZeroRtt) {
4580 PeerConnectionInterface::RTCConfiguration rtc_config;
4581 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4582 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4583 rtc_config.use_datagram_transport_for_data_channels = true;
4584 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
4585 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4586 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4587 loopback_media_transports()->second_factory()));
4588 ConnectFakeSignaling();
4589
4590 // Ensure that the callee's media transport is ready-to-send immediately.
4591 // Note that only the callee can become writable in zero RTTs. The caller
4592 // must wait for the callee's answer.
4593 loopback_media_transports()->SetSecondStateAfterConnect(
4594 webrtc::MediaTransportState::kWritable);
4595 loopback_media_transports()->FlushAsyncInvokes();
4596
4597 // Expect that data channel created on caller side will show up for callee as
4598 // well.
4599 caller()->CreateDataChannel();
4600 caller()->CreateAndSetAndSignalOffer();
4601 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4602
4603 loopback_media_transports()->SetFirstState(
4604 webrtc::MediaTransportState::kWritable);
4605 loopback_media_transports()->FlushAsyncInvokes();
4606
4607 // Caller data channel should already exist (it created one). Callee data
4608 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4609 ASSERT_NE(nullptr, caller()->data_channel());
4610 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4611 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4612 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4613
4614 // Ensure data can be sent in both directions.
4615 std::string data = "hello world";
4616 caller()->data_channel()->Send(DataBuffer(data));
4617 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4618 kDefaultTimeout);
4619 callee()->data_channel()->Send(DataBuffer(data));
4620 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4621 kDefaultTimeout);
4622}
4623
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004624// Ensures that when the callee closes a datagram transport data channel, the
4625// closing procedure results in the data channel being closed for the caller
4626// as well.
4627TEST_P(PeerConnectionIntegrationTest,
4628 DatagramTransportDataChannelCalleeCloses) {
4629 PeerConnectionInterface::RTCConfiguration rtc_config;
4630 rtc_config.use_datagram_transport_for_data_channels = true;
4631 rtc_config.enable_dtls_srtp = false;
4632 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4633 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4634 loopback_media_transports()->second_factory()));
4635 ConnectFakeSignaling();
4636
4637 // Create a data channel on the caller and signal it to the callee.
4638 caller()->CreateDataChannel();
4639 caller()->CreateAndSetAndSignalOffer();
4640 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4641
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004642 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004643 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4644 loopback_media_transports()->FlushAsyncInvokes();
4645
4646 // Data channels exist and open on both ends of the connection.
4647 ASSERT_NE(nullptr, caller()->data_channel());
4648 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4649 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4650 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4651
4652 // Close the data channel on the callee side, and wait for it to reach the
4653 // "closed" state on both sides.
4654 callee()->data_channel()->Close();
4655 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
4656 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
4657}
4658
4659// Tests that datagram transport data channels can do in-band negotiation.
4660TEST_P(PeerConnectionIntegrationTest,
4661 DatagramTransportDataChannelConfigSentToOtherSide) {
4662 PeerConnectionInterface::RTCConfiguration rtc_config;
4663 rtc_config.use_datagram_transport_for_data_channels = true;
4664 rtc_config.enable_dtls_srtp = false;
4665 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4666 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4667 loopback_media_transports()->second_factory()));
4668 ConnectFakeSignaling();
4669
4670 // Create a data channel with a non-default configuration and signal it to the
4671 // callee.
4672 webrtc::DataChannelInit init;
4673 init.id = 53;
4674 init.maxRetransmits = 52;
4675 caller()->CreateDataChannel("data-channel", &init);
4676 caller()->CreateAndSetAndSignalOffer();
4677 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4678
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004679 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004680 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4681 loopback_media_transports()->FlushAsyncInvokes();
4682
4683 // Ensure that the data channel exists on the callee with the correct
4684 // configuration.
4685 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4686 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4687 // Since "negotiate" is false, the "id" parameter is ignored.
4688 EXPECT_NE(init.id, callee()->data_channel()->id());
4689 EXPECT_EQ("data-channel", callee()->data_channel()->label());
4690 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
4691 EXPECT_FALSE(callee()->data_channel()->negotiated());
4692}
4693
4694TEST_P(PeerConnectionIntegrationTest,
4695 DatagramTransportDataChannelRejectedWithNoFallback) {
4696 PeerConnectionInterface::RTCConfiguration offerer_config;
4697 offerer_config.rtcp_mux_policy =
4698 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4699 offerer_config.bundle_policy =
4700 PeerConnectionInterface::kBundlePolicyMaxBundle;
4701 offerer_config.use_datagram_transport_for_data_channels = true;
4702 // Disabling DTLS precludes a fallback to SCTP.
4703 offerer_config.enable_dtls_srtp = false;
4704
4705 PeerConnectionInterface::RTCConfiguration answerer_config;
4706 answerer_config.rtcp_mux_policy =
4707 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4708 answerer_config.bundle_policy =
4709 PeerConnectionInterface::kBundlePolicyMaxBundle;
4710 // Both endpoints must disable DTLS or SetRemoteDescription will fail.
4711 answerer_config.enable_dtls_srtp = false;
4712
4713 // Configure one endpoint to use datagram transport for data channels while
4714 // the other does not.
4715 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4716 offerer_config, answerer_config,
4717 loopback_media_transports()->first_factory(), nullptr));
4718 ConnectFakeSignaling();
4719
4720 // The caller offers a data channel using either datagram transport or SCTP.
4721 caller()->CreateDataChannel();
4722 caller()->AddAudioVideoTracks();
4723 callee()->AddAudioVideoTracks();
4724 caller()->CreateAndSetAndSignalOffer();
4725 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4726
4727 // Caller data channel should already exist (it created one). Callee data
4728 // channel should not exist, since negotiation happens in-band, not in SDP.
4729 EXPECT_NE(nullptr, caller()->data_channel());
4730 EXPECT_EQ(nullptr, callee()->data_channel());
4731
4732 // The caller's data channel should close when the datagram transport is
4733 // rejected.
4734 EXPECT_FALSE(caller()->data_observer()->IsOpen());
4735
4736 // Media flow should not be impacted by the failed data channel.
4737 MediaExpectations media_expectations;
4738 media_expectations.ExpectBidirectionalAudioAndVideo();
4739 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4740}
4741
deadbeef1dcb1642017-03-29 21:08:16 -07004742// Test that the ICE connection and gathering states eventually reach
4743// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08004744TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07004745 ASSERT_TRUE(CreatePeerConnectionWrappers());
4746 ConnectFakeSignaling();
4747 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08004748 caller()->AddAudioVideoTracks();
4749 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004750 caller()->CreateAndSetAndSignalOffer();
4751 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4752 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4753 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
4754 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4755 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
4756 // After the best candidate pair is selected and all candidates are signaled,
4757 // the ICE connection state should reach "complete".
4758 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
4759 // answerer/"callee" by default) only reaches "connected". When this is
4760 // fixed, this test should be updated.
4761 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4762 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00004763 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4764 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07004765}
4766
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004767constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
4768 cricket::PORTALLOCATOR_DISABLE_RELAY |
4769 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004770
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004771// Use a mock resolver to resolve the hostname back to the original IP on both
4772// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004773TEST_P(PeerConnectionIntegrationTest,
4774 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004775 auto caller_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004776 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004777 auto callee_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004778 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004779 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
4780 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004781
4782 // This also verifies that the injected AsyncResolverFactory is used by
4783 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004784 EXPECT_CALL(*caller_resolver_factory, Create())
4785 .WillOnce(Return(&caller_async_resolver));
4786 webrtc::PeerConnectionDependencies caller_deps(nullptr);
4787 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
4788
4789 EXPECT_CALL(*callee_resolver_factory, Create())
4790 .WillOnce(Return(&callee_async_resolver));
4791 webrtc::PeerConnectionDependencies callee_deps(nullptr);
4792 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
4793
4794 PeerConnectionInterface::RTCConfiguration config;
4795 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4796 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4797
4798 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4799 config, std::move(caller_deps), config, std::move(callee_deps)));
4800
4801 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
4802 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
4803
4804 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07004805 caller()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004806 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wangecd30542019-05-22 14:34:56 -07004807 callee()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004808 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004809
4810 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004811
4812 ConnectFakeSignaling();
4813 caller()->AddAudioVideoTracks();
4814 callee()->AddAudioVideoTracks();
4815 caller()->CreateAndSetAndSignalOffer();
4816 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4817 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4818 caller()->ice_connection_state(), kDefaultTimeout);
4819 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4820 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08004821
Ying Wangef3998f2019-12-09 13:06:53 +01004822 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
4823 "WebRTC.PeerConnection.CandidatePairType_UDP",
4824 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004825}
4826
Steve Antonede9ca52017-10-16 13:04:27 -07004827// Test that firewalling the ICE connection causes the clients to identify the
4828// disconnected state and then removing the firewall causes them to reconnect.
4829class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004830 : public PeerConnectionIntegrationBaseTest,
4831 public ::testing::WithParamInterface<
4832 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07004833 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004834 PeerConnectionIntegrationIceStatesTest()
4835 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
4836 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07004837 }
4838
4839 void StartStunServer(const SocketAddress& server_address) {
4840 stun_server_.reset(
4841 cricket::TestStunServer::Create(network_thread(), server_address));
4842 }
4843
4844 bool TestIPv6() {
4845 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
4846 }
4847
4848 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004849 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
4850 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07004851 }
4852
4853 std::vector<SocketAddress> CallerAddresses() {
4854 std::vector<SocketAddress> addresses;
4855 addresses.push_back(SocketAddress("1.1.1.1", 0));
4856 if (TestIPv6()) {
4857 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
4858 }
4859 return addresses;
4860 }
4861
4862 std::vector<SocketAddress> CalleeAddresses() {
4863 std::vector<SocketAddress> addresses;
4864 addresses.push_back(SocketAddress("2.2.2.2", 0));
4865 if (TestIPv6()) {
4866 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
4867 }
4868 return addresses;
4869 }
4870
4871 void SetUpNetworkInterfaces() {
4872 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07004873 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
4874 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07004875
4876 // Add network addresses for test.
4877 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004878 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004879 }
4880 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004881 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004882 }
4883 }
4884
4885 private:
4886 uint32_t port_allocator_flags_;
4887 std::unique_ptr<cricket::TestStunServer> stun_server_;
4888};
4889
Yves Gerey100fe632020-01-17 19:15:53 +01004890// Ensure FakeClockForTest is constructed first (see class for rationale).
4891class PeerConnectionIntegrationIceStatesTestWithFakeClock
4892 : public FakeClockForTest,
4893 public PeerConnectionIntegrationIceStatesTest {};
4894
Steve Antonede9ca52017-10-16 13:04:27 -07004895// Tests that the PeerConnection goes through all the ICE gathering/connection
4896// states over the duration of the call. This includes Disconnected and Failed
4897// states, induced by putting a firewall between the peers and waiting for them
4898// to time out.
Yves Gerey100fe632020-01-17 19:15:53 +01004899TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock, VerifyIceStates) {
Steve Antonede9ca52017-10-16 13:04:27 -07004900 const SocketAddress kStunServerAddress =
4901 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
4902 StartStunServer(kStunServerAddress);
4903
4904 PeerConnectionInterface::RTCConfiguration config;
4905 PeerConnectionInterface::IceServer ice_stun_server;
4906 ice_stun_server.urls.push_back(
4907 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4908 kStunServerAddress.PortAsString());
4909 config.servers.push_back(ice_stun_server);
4910
4911 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4912 ConnectFakeSignaling();
4913 SetPortAllocatorFlags();
4914 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004915 caller()->AddAudioVideoTracks();
4916 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004917
4918 // Initial state before anything happens.
4919 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4920 caller()->ice_gathering_state());
4921 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4922 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004923 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4924 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004925
4926 // Start the call by creating the offer, setting it as the local description,
4927 // then sending it to the peer who will respond with an answer. This happens
4928 // asynchronously so that we can watch the states as it runs in the
4929 // background.
4930 caller()->CreateAndSetAndSignalOffer();
4931
Steve Antona9b67ce2020-01-16 14:00:44 -08004932 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4933 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004934 FakeClock());
Steve Antona9b67ce2020-01-16 14:00:44 -08004935 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4936 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004937 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004938
4939 // Verify that the observer was notified of the intermediate transitions.
4940 EXPECT_THAT(caller()->ice_connection_state_history(),
4941 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4942 PeerConnectionInterface::kIceConnectionConnected,
4943 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004944 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4945 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4946 PeerConnectionInterface::kIceConnectionConnected,
4947 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004948 EXPECT_THAT(
4949 caller()->peer_connection_state_history(),
4950 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004951 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004952 EXPECT_THAT(caller()->ice_gathering_state_history(),
4953 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4954 PeerConnectionInterface::kIceGatheringComplete));
4955
4956 // Block connections to/from the caller and wait for ICE to become
4957 // disconnected.
4958 for (const auto& caller_address : CallerAddresses()) {
4959 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4960 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004961 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004962 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4963 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004964 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004965 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4966 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004967 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004968
4969 // Let ICE re-establish by removing the firewall rules.
4970 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004971 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004972 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4973 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004974 FakeClock());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004975 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004976 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004977 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004978
4979 // According to RFC7675, if there is no response within 30 seconds then the
4980 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004981 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004982 constexpr int kConsentTimeout = 30000;
4983 for (const auto& caller_address : CallerAddresses()) {
4984 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4985 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004986 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004987 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4988 caller()->ice_connection_state(), kConsentTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004989 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004990 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4991 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004992 kConsentTimeout, FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004993}
4994
4995// Tests that if the connection doesn't get set up properly we eventually reach
4996// the "failed" iceConnectionState.
Yves Gerey100fe632020-01-17 19:15:53 +01004997TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock,
4998 IceStateSetupFailure) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004999 // Block connections to/from the caller and wait for ICE to become
5000 // disconnected.
5001 for (const auto& caller_address : CallerAddresses()) {
5002 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
5003 }
5004
5005 ASSERT_TRUE(CreatePeerConnectionWrappers());
5006 ConnectFakeSignaling();
5007 SetPortAllocatorFlags();
5008 SetUpNetworkInterfaces();
5009 caller()->AddAudioVideoTracks();
5010 caller()->CreateAndSetAndSignalOffer();
5011
5012 // According to RFC7675, if there is no response within 30 seconds then the
5013 // peer should consider the other side to have rejected the connection. This
5014 // is signaled by the state transitioning to "failed".
5015 constexpr int kConsentTimeout = 30000;
5016 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
5017 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01005018 kConsentTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07005019}
5020
5021// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
5022// and that the statistics in the metric observers are updated correctly.
5023TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
5024 ASSERT_TRUE(CreatePeerConnectionWrappers());
5025 ConnectFakeSignaling();
5026 SetPortAllocatorFlags();
5027 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08005028 caller()->AddAudioVideoTracks();
5029 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07005030 caller()->CreateAndSetAndSignalOffer();
5031
5032 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton692f3c72020-01-16 14:12:31 -08005033 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5034 caller()->ice_connection_state(), kDefaultTimeout);
5035 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5036 callee()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07005037
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005038 // TODO(bugs.webrtc.org/9456): Fix it.
5039 const int num_best_ipv4 = webrtc::metrics::NumEvents(
5040 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
5041 const int num_best_ipv6 = webrtc::metrics::NumEvents(
5042 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07005043 if (TestIPv6()) {
5044 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
5045 // connection.
Ying Wangef3998f2019-12-09 13:06:53 +01005046 EXPECT_METRIC_EQ(0, num_best_ipv4);
5047 EXPECT_METRIC_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07005048 } else {
Ying Wangef3998f2019-12-09 13:06:53 +01005049 EXPECT_METRIC_EQ(1, num_best_ipv4);
5050 EXPECT_METRIC_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07005051 }
5052
Ying Wangef3998f2019-12-09 13:06:53 +01005053 EXPECT_METRIC_EQ(0, webrtc::metrics::NumEvents(
5054 "WebRTC.PeerConnection.CandidatePairType_UDP",
5055 webrtc::kIceCandidatePairHostHost));
5056 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
5057 "WebRTC.PeerConnection.CandidatePairType_UDP",
5058 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07005059}
5060
5061constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
5062 cricket::PORTALLOCATOR_DISABLE_STUN |
5063 cricket::PORTALLOCATOR_DISABLE_RELAY;
5064constexpr uint32_t kFlagsIPv6NoStun =
5065 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
5066 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
5067constexpr uint32_t kFlagsIPv4Stun =
5068 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
5069
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005070INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08005071 PeerConnectionIntegrationTest,
5072 PeerConnectionIntegrationIceStatesTest,
5073 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5074 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
5075 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
5076 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07005077
Yves Gerey100fe632020-01-17 19:15:53 +01005078INSTANTIATE_TEST_SUITE_P(
5079 PeerConnectionIntegrationTest,
5080 PeerConnectionIntegrationIceStatesTestWithFakeClock,
5081 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5082 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
5083 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
5084 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
5085
deadbeef1dcb1642017-03-29 21:08:16 -07005086// This test sets up a call between two parties with audio and video.
5087// During the call, the caller restarts ICE and the test verifies that
5088// new ICE candidates are generated and audio and video still can flow, and the
5089// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005090TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07005091 ASSERT_TRUE(CreatePeerConnectionWrappers());
5092 ConnectFakeSignaling();
5093 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08005094 caller()->AddAudioVideoTracks();
5095 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07005096 caller()->CreateAndSetAndSignalOffer();
5097 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5098 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5099 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00005100 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5101 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07005102
5103 // To verify that the ICE restart actually occurs, get
5104 // ufrag/password/candidates before and after restart.
5105 // Create an SDP string of the first audio candidate for both clients.
5106 const webrtc::IceCandidateCollection* audio_candidates_caller =
5107 caller()->pc()->local_description()->candidates(0);
5108 const webrtc::IceCandidateCollection* audio_candidates_callee =
5109 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_pre_restart;
5113 ASSERT_TRUE(
5114 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
5115 std::string callee_candidate_pre_restart;
5116 ASSERT_TRUE(
5117 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
5118 const cricket::SessionDescription* desc =
5119 caller()->pc()->local_description()->description();
5120 std::string caller_ufrag_pre_restart =
5121 desc->transport_infos()[0].description.ice_ufrag;
5122 desc = callee()->pc()->local_description()->description();
5123 std::string callee_ufrag_pre_restart =
5124 desc->transport_infos()[0].description.ice_ufrag;
5125
Alex Drake00c7ecf2019-08-06 10:54:47 -07005126 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07005127 // Have the caller initiate an ICE restart.
5128 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
5129 caller()->CreateAndSetAndSignalOffer();
5130 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5131 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5132 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00005133 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07005134 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5135
5136 // Grab the ufrags/candidates again.
5137 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
5138 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
5139 ASSERT_GT(audio_candidates_caller->count(), 0u);
5140 ASSERT_GT(audio_candidates_callee->count(), 0u);
5141 std::string caller_candidate_post_restart;
5142 ASSERT_TRUE(
5143 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
5144 std::string callee_candidate_post_restart;
5145 ASSERT_TRUE(
5146 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
5147 desc = caller()->pc()->local_description()->description();
5148 std::string caller_ufrag_post_restart =
5149 desc->transport_infos()[0].description.ice_ufrag;
5150 desc = callee()->pc()->local_description()->description();
5151 std::string callee_ufrag_post_restart =
5152 desc->transport_infos()[0].description.ice_ufrag;
5153 // Sanity check that an ICE restart was actually negotiated in SDP.
5154 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
5155 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
5156 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
5157 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07005158 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07005159
5160 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005161 MediaExpectations media_expectations;
5162 media_expectations.ExpectBidirectionalAudioAndVideo();
5163 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005164}
5165
5166// Verify that audio/video can be received end-to-end when ICE renomination is
5167// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005168TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07005169 PeerConnectionInterface::RTCConfiguration config;
5170 config.enable_ice_renomination = true;
5171 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5172 ConnectFakeSignaling();
5173 // Do normal offer/answer and wait for some frames to be received in each
5174 // direction.
Steve Anton15324772018-01-16 10:26:49 -08005175 caller()->AddAudioVideoTracks();
5176 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07005177 caller()->CreateAndSetAndSignalOffer();
5178 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5179 // Sanity check that ICE renomination was actually negotiated.
5180 const cricket::SessionDescription* desc =
5181 caller()->pc()->local_description()->description();
5182 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08005183 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07005184 }
5185 desc = callee()->pc()->local_description()->description();
5186 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08005187 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07005188 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08005189 MediaExpectations media_expectations;
5190 media_expectations.ExpectBidirectionalAudioAndVideo();
5191 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005192}
5193
Steve Anton6f25b092017-10-23 09:39:20 -07005194// With a max bundle policy and RTCP muxing, adding a new media description to
5195// the connection should not affect ICE at all because the new media will use
5196// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005197TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08005198 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07005199 PeerConnectionInterface::RTCConfiguration config;
5200 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5201 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
5202 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
5203 config, PeerConnectionInterface::RTCConfiguration()));
5204 ConnectFakeSignaling();
5205
Steve Anton15324772018-01-16 10:26:49 -08005206 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07005207 caller()->CreateAndSetAndSignalOffer();
5208 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07005209 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
5210 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07005211
5212 caller()->clear_ice_connection_state_history();
5213
Steve Anton15324772018-01-16 10:26:49 -08005214 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07005215 caller()->CreateAndSetAndSignalOffer();
5216 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5217
5218 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
5219}
5220
deadbeef1dcb1642017-03-29 21:08:16 -07005221// This test sets up a call between two parties with audio and video. It then
5222// renegotiates setting the video m-line to "port 0", then later renegotiates
5223// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005224TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07005225 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
5226 ASSERT_TRUE(CreatePeerConnectionWrappers());
5227 ConnectFakeSignaling();
5228
5229 // Do initial negotiation, only sending media from the caller. Will result in
5230 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08005231 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07005232 caller()->CreateAndSetAndSignalOffer();
5233 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5234
5235 // Negotiate again, disabling the video "m=" section (the callee will set the
5236 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005237 if (sdp_semantics_ == SdpSemantics::kPlanB) {
5238 PeerConnectionInterface::RTCOfferAnswerOptions options;
5239 options.offer_to_receive_video = 0;
5240 callee()->SetOfferAnswerOptions(options);
5241 } else {
5242 callee()->SetRemoteOfferHandler([this] {
5243 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
5244 });
5245 }
deadbeef1dcb1642017-03-29 21:08:16 -07005246 caller()->CreateAndSetAndSignalOffer();
5247 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5248 // Sanity check that video "m=" section was actually rejected.
5249 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
5250 callee()->pc()->local_description()->description());
5251 ASSERT_NE(nullptr, answer_video_content);
5252 ASSERT_TRUE(answer_video_content->rejected);
5253
5254 // Enable video and do negotiation again, making sure video is received
5255 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005256 if (sdp_semantics_ == SdpSemantics::kPlanB) {
5257 PeerConnectionInterface::RTCOfferAnswerOptions options;
5258 options.offer_to_receive_video = 1;
5259 callee()->SetOfferAnswerOptions(options);
5260 } else {
5261 // The caller's transceiver is stopped, so we need to add another track.
5262 auto caller_transceiver =
5263 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
5264 EXPECT_TRUE(caller_transceiver->stopped());
5265 caller()->AddVideoTrack();
5266 }
5267 callee()->AddVideoTrack();
5268 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07005269 caller()->CreateAndSetAndSignalOffer();
5270 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005271
deadbeef1dcb1642017-03-29 21:08:16 -07005272 // Verify the caller receives frames from the newly added stream, and the
5273 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005274 MediaExpectations media_expectations;
5275 media_expectations.CalleeExpectsSomeAudio();
5276 media_expectations.ExpectBidirectionalVideo();
5277 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005278}
5279
deadbeef1dcb1642017-03-29 21:08:16 -07005280// This tests that if we negotiate after calling CreateSender but before we
5281// have a track, then set a track later, frames from the newly-set track are
5282// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005283TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07005284 MediaFlowsAfterEarlyWarmupWithCreateSender) {
5285 ASSERT_TRUE(CreatePeerConnectionWrappers());
5286 ConnectFakeSignaling();
5287 auto caller_audio_sender =
5288 caller()->pc()->CreateSender("audio", "caller_stream");
5289 auto caller_video_sender =
5290 caller()->pc()->CreateSender("video", "caller_stream");
5291 auto callee_audio_sender =
5292 callee()->pc()->CreateSender("audio", "callee_stream");
5293 auto callee_video_sender =
5294 callee()->pc()->CreateSender("video", "callee_stream");
5295 caller()->CreateAndSetAndSignalOffer();
5296 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5297 // Wait for ICE to complete, without any tracks being set.
5298 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5299 caller()->ice_connection_state(), kMaxWaitForFramesMs);
5300 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5301 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5302 // Now set the tracks, and expect frames to immediately start flowing.
5303 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
5304 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
5305 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
5306 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08005307 MediaExpectations media_expectations;
5308 media_expectations.ExpectBidirectionalAudioAndVideo();
5309 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5310}
5311
5312// This tests that if we negotiate after calling AddTransceiver but before we
5313// have a track, then set a track later, frames from the newly-set tracks are
5314// received end-to-end.
5315TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5316 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
5317 ASSERT_TRUE(CreatePeerConnectionWrappers());
5318 ConnectFakeSignaling();
5319 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
5320 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
5321 auto caller_audio_sender = audio_result.MoveValue()->sender();
5322 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
5323 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
5324 auto caller_video_sender = video_result.MoveValue()->sender();
5325 callee()->SetRemoteOfferHandler([this] {
5326 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
5327 callee()->pc()->GetTransceivers()[0]->SetDirection(
5328 RtpTransceiverDirection::kSendRecv);
5329 callee()->pc()->GetTransceivers()[1]->SetDirection(
5330 RtpTransceiverDirection::kSendRecv);
5331 });
5332 caller()->CreateAndSetAndSignalOffer();
5333 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5334 // Wait for ICE to complete, without any tracks being set.
5335 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5336 caller()->ice_connection_state(), kMaxWaitForFramesMs);
5337 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5338 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5339 // Now set the tracks, and expect frames to immediately start flowing.
5340 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
5341 auto callee_video_sender = callee()->pc()->GetSenders()[1];
5342 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
5343 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
5344 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
5345 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
5346 MediaExpectations media_expectations;
5347 media_expectations.ExpectBidirectionalAudioAndVideo();
5348 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005349}
5350
5351// This test verifies that a remote video track can be added via AddStream,
5352// and sent end-to-end. For this particular test, it's simply echoed back
5353// from the caller to the callee, rather than being forwarded to a third
5354// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005355TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07005356 ASSERT_TRUE(CreatePeerConnectionWrappers());
5357 ConnectFakeSignaling();
5358 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08005359 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07005360 caller()->CreateAndSetAndSignalOffer();
5361 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02005362 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07005363
5364 // Echo the stream back, and do a new offer/anwer (initiated by callee this
5365 // time).
5366 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
5367 callee()->CreateAndSetAndSignalOffer();
5368 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5369
Seth Hampson2f0d7022018-02-20 11:54:42 -08005370 MediaExpectations media_expectations;
5371 media_expectations.ExpectBidirectionalVideo();
5372 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005373}
5374
5375// Test that we achieve the expected end-to-end connection time, using a
5376// fake clock and simulated latency on the media and signaling paths.
5377// We use a TURN<->TURN connection because this is usually the quickest to
5378// set up initially, especially when we're confident the connection will work
5379// and can start sending media before we get a STUN response.
5380//
5381// With various optimizations enabled, here are the network delays we expect to
5382// be on the critical path:
5383// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
5384// signaling answer (with DTLS fingerprint).
5385// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
5386// using TURN<->TURN pair, and DTLS exchange is 4 packets,
5387// the first of which should have arrived before the answer.
Yves Gerey100fe632020-01-17 19:15:53 +01005388TEST_P(PeerConnectionIntegrationTestWithFakeClock,
5389 EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07005390 static constexpr int media_hop_delay_ms = 50;
5391 static constexpr int signaling_trip_delay_ms = 500;
5392 // For explanation of these values, see comment above.
5393 static constexpr int required_media_hops = 9;
5394 static constexpr int required_signaling_trips = 2;
5395 // For internal delays (such as posting an event asychronously).
5396 static constexpr int allowed_internal_delay_ms = 20;
5397 static constexpr int total_connection_time_ms =
5398 media_hop_delay_ms * required_media_hops +
5399 signaling_trip_delay_ms * required_signaling_trips +
5400 allowed_internal_delay_ms;
5401
5402 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
5403 3478};
5404 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
5405 0};
5406 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
5407 3478};
5408 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
5409 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07005410 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
5411 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005412
Seth Hampsonaed71642018-06-11 07:41:32 -07005413 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
5414 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07005415 // Bypass permission check on received packets so media can be sent before
5416 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07005417 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
5418 turn_server_1->set_enable_permission_checks(false);
5419 });
5420 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
5421 turn_server_2->set_enable_permission_checks(false);
5422 });
deadbeef1dcb1642017-03-29 21:08:16 -07005423
5424 PeerConnectionInterface::RTCConfiguration client_1_config;
5425 webrtc::PeerConnectionInterface::IceServer ice_server_1;
5426 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
5427 ice_server_1.username = "test";
5428 ice_server_1.password = "test";
5429 client_1_config.servers.push_back(ice_server_1);
5430 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5431 client_1_config.presume_writable_when_fully_relayed = true;
5432
5433 PeerConnectionInterface::RTCConfiguration client_2_config;
5434 webrtc::PeerConnectionInterface::IceServer ice_server_2;
5435 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
5436 ice_server_2.username = "test";
5437 ice_server_2.password = "test";
5438 client_2_config.servers.push_back(ice_server_2);
5439 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5440 client_2_config.presume_writable_when_fully_relayed = true;
5441
5442 ASSERT_TRUE(
5443 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5444 // Set up the simulated delays.
5445 SetSignalingDelayMs(signaling_trip_delay_ms);
5446 ConnectFakeSignaling();
5447 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
5448 virtual_socket_server()->UpdateDelayDistribution();
5449
5450 // Set "offer to receive audio/video" without adding any tracks, so we just
5451 // set up ICE/DTLS with no media.
5452 PeerConnectionInterface::RTCOfferAnswerOptions options;
5453 options.offer_to_receive_audio = 1;
5454 options.offer_to_receive_video = 1;
5455 caller()->SetOfferAnswerOptions(options);
5456 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07005457 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
Yves Gerey100fe632020-01-17 19:15:53 +01005458 FakeClock());
Seth Hampson1d4a76d2018-06-19 14:31:41 -07005459 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
5460 // If this is not done a DCHECK can be hit in ports.cc, because a large
5461 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07005462 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07005463}
5464
Jonas Orelandbdcee282017-10-10 14:01:40 +02005465// Verify that a TurnCustomizer passed in through RTCConfiguration
5466// is actually used by the underlying TURN candidate pair.
5467// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005468TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02005469 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
5470 3478};
5471 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
5472 0};
5473 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
5474 3478};
5475 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
5476 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07005477 CreateTurnServer(turn_server_1_internal_address,
5478 turn_server_1_external_address);
5479 CreateTurnServer(turn_server_2_internal_address,
5480 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005481
5482 PeerConnectionInterface::RTCConfiguration client_1_config;
5483 webrtc::PeerConnectionInterface::IceServer ice_server_1;
5484 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
5485 ice_server_1.username = "test";
5486 ice_server_1.password = "test";
5487 client_1_config.servers.push_back(ice_server_1);
5488 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005489 auto* customizer1 = CreateTurnCustomizer();
5490 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005491
5492 PeerConnectionInterface::RTCConfiguration client_2_config;
5493 webrtc::PeerConnectionInterface::IceServer ice_server_2;
5494 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
5495 ice_server_2.username = "test";
5496 ice_server_2.password = "test";
5497 client_2_config.servers.push_back(ice_server_2);
5498 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005499 auto* customizer2 = CreateTurnCustomizer();
5500 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005501
5502 ASSERT_TRUE(
5503 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5504 ConnectFakeSignaling();
5505
5506 // Set "offer to receive audio/video" without adding any tracks, so we just
5507 // set up ICE/DTLS with no media.
5508 PeerConnectionInterface::RTCOfferAnswerOptions options;
5509 options.offer_to_receive_audio = 1;
5510 options.offer_to_receive_video = 1;
5511 caller()->SetOfferAnswerOptions(options);
5512 caller()->CreateAndSetAndSignalOffer();
5513 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5514
Seth Hampsonaed71642018-06-11 07:41:32 -07005515 ExpectTurnCustomizerCountersIncremented(customizer1);
5516 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005517}
5518
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005519// Verifies that you can use TCP instead of UDP to connect to a TURN server and
5520// send media between the caller and the callee.
5521TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
5522 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5523 3478};
5524 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5525
5526 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07005527 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5528 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005529
5530 webrtc::PeerConnectionInterface::IceServer ice_server;
5531 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
5532 ice_server.username = "test";
5533 ice_server.password = "test";
5534
5535 PeerConnectionInterface::RTCConfiguration client_1_config;
5536 client_1_config.servers.push_back(ice_server);
5537 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5538
5539 PeerConnectionInterface::RTCConfiguration client_2_config;
5540 client_2_config.servers.push_back(ice_server);
5541 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5542
5543 ASSERT_TRUE(
5544 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5545
5546 // Do normal offer/answer and wait for ICE to complete.
5547 ConnectFakeSignaling();
5548 caller()->AddAudioVideoTracks();
5549 callee()->AddAudioVideoTracks();
5550 caller()->CreateAndSetAndSignalOffer();
5551 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5552 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5553 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5554
5555 MediaExpectations media_expectations;
5556 media_expectations.ExpectBidirectionalAudioAndVideo();
5557 EXPECT_TRUE(ExpectNewFrames(media_expectations));
5558}
5559
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005560// Verify that a SSLCertificateVerifier passed in through
5561// PeerConnectionDependencies is actually used by the underlying SSL
5562// implementation to determine whether a certificate presented by the TURN
5563// server is accepted by the client. Note that openssladapter_unittest.cc
5564// contains more detailed, lower-level tests.
5565TEST_P(PeerConnectionIntegrationTest,
5566 SSLCertificateVerifierUsedForTurnConnections) {
5567 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5568 3478};
5569 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5570
5571 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5572 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005573 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5574 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005575
5576 webrtc::PeerConnectionInterface::IceServer ice_server;
5577 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5578 ice_server.username = "test";
5579 ice_server.password = "test";
5580
5581 PeerConnectionInterface::RTCConfiguration client_1_config;
5582 client_1_config.servers.push_back(ice_server);
5583 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5584
5585 PeerConnectionInterface::RTCConfiguration client_2_config;
5586 client_2_config.servers.push_back(ice_server);
5587 // Setting the type to kRelay forces the connection to go through a TURN
5588 // server.
5589 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5590
5591 // Get a copy to the pointer so we can verify calls later.
5592 rtc::TestCertificateVerifier* client_1_cert_verifier =
5593 new rtc::TestCertificateVerifier();
5594 client_1_cert_verifier->verify_certificate_ = true;
5595 rtc::TestCertificateVerifier* client_2_cert_verifier =
5596 new rtc::TestCertificateVerifier();
5597 client_2_cert_verifier->verify_certificate_ = true;
5598
5599 // Create the dependencies with the test certificate verifier.
5600 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5601 client_1_deps.tls_cert_verifier =
5602 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5603 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5604 client_2_deps.tls_cert_verifier =
5605 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5606
5607 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5608 client_1_config, std::move(client_1_deps), client_2_config,
5609 std::move(client_2_deps)));
5610 ConnectFakeSignaling();
5611
5612 // Set "offer to receive audio/video" without adding any tracks, so we just
5613 // set up ICE/DTLS with no media.
5614 PeerConnectionInterface::RTCOfferAnswerOptions options;
5615 options.offer_to_receive_audio = 1;
5616 options.offer_to_receive_video = 1;
5617 caller()->SetOfferAnswerOptions(options);
5618 caller()->CreateAndSetAndSignalOffer();
5619 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5620
5621 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5622 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005623}
5624
5625TEST_P(PeerConnectionIntegrationTest,
5626 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
5627 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5628 3478};
5629 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5630
5631 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5632 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005633 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5634 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005635
5636 webrtc::PeerConnectionInterface::IceServer ice_server;
5637 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5638 ice_server.username = "test";
5639 ice_server.password = "test";
5640
5641 PeerConnectionInterface::RTCConfiguration client_1_config;
5642 client_1_config.servers.push_back(ice_server);
5643 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5644
5645 PeerConnectionInterface::RTCConfiguration client_2_config;
5646 client_2_config.servers.push_back(ice_server);
5647 // Setting the type to kRelay forces the connection to go through a TURN
5648 // server.
5649 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5650
5651 // Get a copy to the pointer so we can verify calls later.
5652 rtc::TestCertificateVerifier* client_1_cert_verifier =
5653 new rtc::TestCertificateVerifier();
5654 client_1_cert_verifier->verify_certificate_ = false;
5655 rtc::TestCertificateVerifier* client_2_cert_verifier =
5656 new rtc::TestCertificateVerifier();
5657 client_2_cert_verifier->verify_certificate_ = false;
5658
5659 // Create the dependencies with the test certificate verifier.
5660 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5661 client_1_deps.tls_cert_verifier =
5662 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5663 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5664 client_2_deps.tls_cert_verifier =
5665 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5666
5667 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5668 client_1_config, std::move(client_1_deps), client_2_config,
5669 std::move(client_2_deps)));
5670 ConnectFakeSignaling();
5671
5672 // Set "offer to receive audio/video" without adding any tracks, so we just
5673 // set up ICE/DTLS with no media.
5674 PeerConnectionInterface::RTCOfferAnswerOptions options;
5675 options.offer_to_receive_audio = 1;
5676 options.offer_to_receive_video = 1;
5677 caller()->SetOfferAnswerOptions(options);
5678 caller()->CreateAndSetAndSignalOffer();
5679 bool wait_res = true;
5680 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
5681 // properly, should be able to just wait for a state of "failed" instead of
5682 // waiting a fixed 10 seconds.
5683 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
5684 ASSERT_FALSE(wait_res);
5685
5686 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5687 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005688}
5689
Qingsi Wang25ec8882019-11-15 12:33:05 -08005690// Test that the injected ICE transport factory is used to create ICE transports
5691// for WebRTC connections.
5692TEST_P(PeerConnectionIntegrationTest, IceTransportFactoryUsedForConnections) {
5693 PeerConnectionInterface::RTCConfiguration default_config;
5694 PeerConnectionDependencies dependencies(nullptr);
5695 auto ice_transport_factory = std::make_unique<MockIceTransportFactory>();
5696 EXPECT_CALL(*ice_transport_factory, RecordIceTransportCreated()).Times(1);
5697 dependencies.ice_transport_factory = std::move(ice_transport_factory);
Johannes Kron3e983682020-03-29 22:17:00 +02005698 auto wrapper = CreatePeerConnectionWrapper(
5699 "Caller", nullptr, &default_config, std::move(dependencies), nullptr,
5700 nullptr, /*reset_encoder_factory=*/false,
5701 /*reset_decoder_factory=*/false);
Qingsi Wang25ec8882019-11-15 12:33:05 -08005702 ASSERT_TRUE(wrapper);
5703 wrapper->CreateDataChannel();
5704 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5705 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5706 wrapper->pc()->SetLocalDescription(observer,
5707 wrapper->CreateOfferAndWait().release());
5708}
5709
deadbeefc964d0b2017-04-03 10:03:35 -07005710// Test that audio and video flow end-to-end when codec names don't use the
5711// expected casing, given that they're supposed to be case insensitive. To test
5712// this, all but one codec is removed from each media description, and its
5713// casing is changed.
5714//
5715// In the past, this has regressed and caused crashes/black video, due to the
5716// fact that code at some layers was doing case-insensitive comparisons and
5717// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005718TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07005719 ASSERT_TRUE(CreatePeerConnectionWrappers());
5720 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005721 caller()->AddAudioVideoTracks();
5722 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07005723
5724 // Remove all but one audio/video codec (opus and VP8), and change the
5725 // casing of the caller's generated offer.
5726 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
5727 cricket::AudioContentDescription* audio =
5728 GetFirstAudioContentDescription(description);
5729 ASSERT_NE(nullptr, audio);
5730 auto audio_codecs = audio->codecs();
5731 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
5732 [](const cricket::AudioCodec& codec) {
5733 return codec.name != "opus";
5734 }),
5735 audio_codecs.end());
5736 ASSERT_EQ(1u, audio_codecs.size());
5737 audio_codecs[0].name = "OpUs";
5738 audio->set_codecs(audio_codecs);
5739
5740 cricket::VideoContentDescription* video =
5741 GetFirstVideoContentDescription(description);
5742 ASSERT_NE(nullptr, video);
5743 auto video_codecs = video->codecs();
5744 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
5745 [](const cricket::VideoCodec& codec) {
5746 return codec.name != "VP8";
5747 }),
5748 video_codecs.end());
5749 ASSERT_EQ(1u, video_codecs.size());
5750 video_codecs[0].name = "vP8";
5751 video->set_codecs(video_codecs);
5752 });
5753
5754 caller()->CreateAndSetAndSignalOffer();
5755 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5756
5757 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005758 MediaExpectations media_expectations;
5759 media_expectations.ExpectBidirectionalAudioAndVideo();
5760 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07005761}
5762
Jonas Oreland49ac5952018-09-26 16:04:32 +02005763TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07005764 ASSERT_TRUE(CreatePeerConnectionWrappers());
5765 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005766 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07005767 caller()->CreateAndSetAndSignalOffer();
5768 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07005769 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005770 MediaExpectations media_expectations;
5771 media_expectations.CalleeExpectsSomeAudio(1);
5772 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02005773 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07005774 auto receiver = callee()->pc()->GetReceivers()[0];
5775 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005776 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07005777 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
5778 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02005779 sources[0].source_id());
5780 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
5781}
5782
5783TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
5784 ASSERT_TRUE(CreatePeerConnectionWrappers());
5785 ConnectFakeSignaling();
5786 caller()->AddVideoTrack();
5787 caller()->CreateAndSetAndSignalOffer();
5788 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5789 // Wait for one video frame to be received by the callee.
5790 MediaExpectations media_expectations;
5791 media_expectations.CalleeExpectsSomeVideo(1);
5792 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5793 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
5794 auto receiver = callee()->pc()->GetReceivers()[0];
5795 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
5796 auto sources = receiver->GetSources();
5797 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02005798 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005799 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
5800 sources[0].source_id());
5801 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07005802}
5803
deadbeef2f425aa2017-04-14 10:41:32 -07005804// Test that if a track is removed and added again with a different stream ID,
5805// the new stream ID is successfully communicated in SDP and media continues to
5806// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005807// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
5808// it will not reuse a transceiver that has already been sending. After creating
5809// a new transceiver it tries to create an offer with two senders of the same
5810// track ids and it fails.
5811TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07005812 ASSERT_TRUE(CreatePeerConnectionWrappers());
5813 ConnectFakeSignaling();
5814
deadbeef2f425aa2017-04-14 10:41:32 -07005815 // Add track using stream 1, do offer/answer.
5816 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
5817 caller()->CreateLocalAudioTrack();
5818 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07005819 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07005820 caller()->CreateAndSetAndSignalOffer();
5821 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005822 {
5823 MediaExpectations media_expectations;
5824 media_expectations.CalleeExpectsSomeAudio(1);
5825 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5826 }
deadbeef2f425aa2017-04-14 10:41:32 -07005827 // Remove the sender, and create a new one with the new stream.
5828 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07005829 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07005830 caller()->CreateAndSetAndSignalOffer();
5831 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5832 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005833 {
5834 MediaExpectations media_expectations;
5835 media_expectations.CalleeExpectsSomeAudio();
5836 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5837 }
deadbeef2f425aa2017-04-14 10:41:32 -07005838}
5839
Seth Hampson2f0d7022018-02-20 11:54:42 -08005840TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02005841 ASSERT_TRUE(CreatePeerConnectionWrappers());
5842 ConnectFakeSignaling();
5843
Mirko Bonadei317a1f02019-09-17 17:06:18 +02005844 auto output = std::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005845 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
5846 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02005847 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01005848 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
5849 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02005850
Steve Anton15324772018-01-16 10:26:49 -08005851 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02005852 caller()->CreateAndSetAndSignalOffer();
5853 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5854}
5855
Steve Antonede9ca52017-10-16 13:04:27 -07005856// Test that if candidates are only signaled by applying full session
5857// descriptions (instead of using AddIceCandidate), the peers can connect to
5858// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005859TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07005860 ASSERT_TRUE(CreatePeerConnectionWrappers());
5861 // Each side will signal the session descriptions but not candidates.
5862 ConnectFakeSignalingForSdpOnly();
5863
5864 // Add audio video track and exchange the initial offer/answer with media
5865 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08005866 caller()->AddAudioVideoTracks();
5867 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07005868 caller()->CreateAndSetAndSignalOffer();
5869
5870 // Wait for all candidates to be gathered on both the caller and callee.
5871 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5872 caller()->ice_gathering_state(), kDefaultTimeout);
5873 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5874 callee()->ice_gathering_state(), kDefaultTimeout);
5875
5876 // The candidates will now be included in the session description, so
5877 // signaling them will start the ICE connection.
5878 caller()->CreateAndSetAndSignalOffer();
5879 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5880
5881 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005882 MediaExpectations media_expectations;
5883 media_expectations.ExpectBidirectionalAudioAndVideo();
5884 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07005885}
5886
henrika5f6bf242017-11-01 11:06:56 +01005887// Test that SetAudioPlayout can be used to disable audio playout from the
5888// start, then later enable it. This may be useful, for example, if the caller
5889// needs to play a local ringtone until some event occurs, after which it
5890// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005891TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01005892 ASSERT_TRUE(CreatePeerConnectionWrappers());
5893 ConnectFakeSignaling();
5894
5895 // Set up audio-only call where audio playout is disabled on caller's side.
5896 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08005897 caller()->AddAudioTrack();
5898 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005899 caller()->CreateAndSetAndSignalOffer();
5900 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5901
5902 // Pump messages for a second.
5903 WAIT(false, 1000);
5904 // Since audio playout is disabled, the caller shouldn't have received
5905 // anything (at the playout level, at least).
5906 EXPECT_EQ(0, caller()->audio_frames_received());
5907 // As a sanity check, make sure the callee (for which playout isn't disabled)
5908 // did still see frames on its audio level.
5909 ASSERT_GT(callee()->audio_frames_received(), 0);
5910
5911 // Enable playout again, and ensure audio starts flowing.
5912 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005913 MediaExpectations media_expectations;
5914 media_expectations.ExpectBidirectionalAudio();
5915 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01005916}
5917
5918double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5919 auto report = pc->NewGetStats();
5920 auto track_stats_list =
5921 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5922 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5923 for (const auto* track_stats : track_stats_list) {
5924 if (track_stats->remote_source.is_defined() &&
5925 *track_stats->remote_source) {
5926 remote_track_stats = track_stats;
5927 break;
5928 }
5929 }
5930
5931 if (!remote_track_stats->total_audio_energy.is_defined()) {
5932 return 0.0;
5933 }
5934 return *remote_track_stats->total_audio_energy;
5935}
5936
5937// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5938// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005939TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005940 DisableAudioPlayoutStillGeneratesAudioStats) {
5941 ASSERT_TRUE(CreatePeerConnectionWrappers());
5942 ConnectFakeSignaling();
5943
5944 // Set up audio-only call where playout is disabled but audio-processing is
5945 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005946 caller()->AddAudioTrack();
5947 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005948 caller()->pc()->SetAudioPlayout(false);
5949
5950 caller()->CreateAndSetAndSignalOffer();
5951 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5952
5953 // Wait for the callee to receive audio stats.
5954 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5955}
5956
henrika4f167df2017-11-01 14:45:55 +01005957// Test that SetAudioRecording can be used to disable audio recording from the
5958// start, then later enable it. This may be useful, for example, if the caller
5959// wants to ensure that no audio resources are active before a certain state
5960// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005961TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005962 ASSERT_TRUE(CreatePeerConnectionWrappers());
5963 ConnectFakeSignaling();
5964
5965 // Set up audio-only call where audio recording is disabled on caller's side.
5966 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005967 caller()->AddAudioTrack();
5968 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005969 caller()->CreateAndSetAndSignalOffer();
5970 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5971
5972 // Pump messages for a second.
5973 WAIT(false, 1000);
5974 // Since caller has disabled audio recording, the callee shouldn't have
5975 // received anything.
5976 EXPECT_EQ(0, callee()->audio_frames_received());
5977 // As a sanity check, make sure the caller did still see frames on its
5978 // audio level since audio recording is enabled on the calle side.
5979 ASSERT_GT(caller()->audio_frames_received(), 0);
5980
5981 // Enable audio recording again, and ensure audio starts flowing.
5982 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005983 MediaExpectations media_expectations;
5984 media_expectations.ExpectBidirectionalAudio();
5985 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005986}
5987
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005988// Test that after closing PeerConnections, they stop sending any packets (ICE,
5989// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005990TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005991 // Set up audio/video/data, wait for some frames to be received.
5992 ASSERT_TRUE(CreatePeerConnectionWrappers());
5993 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005994 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005995#ifdef HAVE_SCTP
5996 caller()->CreateDataChannel();
5997#endif
5998 caller()->CreateAndSetAndSignalOffer();
5999 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08006000 MediaExpectations media_expectations;
6001 media_expectations.CalleeExpectsSomeAudioAndVideo();
6002 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08006003 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07006004 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08006005 // Pump messages for a second, and ensure no new packets end up sent.
6006 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
6007 WAIT(false, 1000);
6008 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
6009 EXPECT_EQ(sent_packets_a, sent_packets_b);
6010}
6011
Steve Anton7eca0932018-03-30 15:18:41 -07006012// Test that transport stats are generated by the RTCStatsCollector for a
6013// connection that only involves data channels. This is a regression test for
6014// crbug.com/826972.
6015#ifdef HAVE_SCTP
6016TEST_P(PeerConnectionIntegrationTest,
6017 TransportStatsReportedForDataChannelOnlyConnection) {
6018 ASSERT_TRUE(CreatePeerConnectionWrappers());
6019 ConnectFakeSignaling();
6020 caller()->CreateDataChannel();
6021
6022 caller()->CreateAndSetAndSignalOffer();
6023 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6024 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
6025
6026 auto caller_report = caller()->NewGetStats();
6027 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
6028 auto callee_report = callee()->NewGetStats();
6029 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
6030}
6031#endif // HAVE_SCTP
6032
Qingsi Wang7685e862018-06-11 20:15:46 -07006033TEST_P(PeerConnectionIntegrationTest,
6034 IceEventsGeneratedAndLoggedInRtcEventLog) {
6035 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
6036 ConnectFakeSignaling();
6037 PeerConnectionInterface::RTCOfferAnswerOptions options;
6038 options.offer_to_receive_audio = 1;
6039 caller()->SetOfferAnswerOptions(options);
6040 caller()->CreateAndSetAndSignalOffer();
6041 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
6042 ASSERT_NE(nullptr, caller()->event_log_factory());
6043 ASSERT_NE(nullptr, callee()->event_log_factory());
6044 webrtc::FakeRtcEventLog* caller_event_log =
6045 static_cast<webrtc::FakeRtcEventLog*>(
6046 caller()->event_log_factory()->last_log_created());
6047 webrtc::FakeRtcEventLog* callee_event_log =
6048 static_cast<webrtc::FakeRtcEventLog*>(
6049 callee()->event_log_factory()->last_log_created());
6050 ASSERT_NE(nullptr, caller_event_log);
6051 ASSERT_NE(nullptr, callee_event_log);
6052 int caller_ice_config_count = caller_event_log->GetEventCount(
6053 webrtc::RtcEvent::Type::IceCandidatePairConfig);
6054 int caller_ice_event_count = caller_event_log->GetEventCount(
6055 webrtc::RtcEvent::Type::IceCandidatePairEvent);
6056 int callee_ice_config_count = callee_event_log->GetEventCount(
6057 webrtc::RtcEvent::Type::IceCandidatePairConfig);
6058 int callee_ice_event_count = callee_event_log->GetEventCount(
6059 webrtc::RtcEvent::Type::IceCandidatePairEvent);
6060 EXPECT_LT(0, caller_ice_config_count);
6061 EXPECT_LT(0, caller_ice_event_count);
6062 EXPECT_LT(0, callee_ice_config_count);
6063 EXPECT_LT(0, callee_ice_event_count);
6064}
6065
Qingsi Wangc129c352019-04-18 10:41:58 -07006066TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07006067 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
6068 3478};
6069 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
6070
6071 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
6072
6073 webrtc::PeerConnectionInterface::IceServer ice_server;
6074 ice_server.urls.push_back("turn:88.88.88.0:3478");
6075 ice_server.username = "test";
6076 ice_server.password = "test";
6077
6078 PeerConnectionInterface::RTCConfiguration caller_config;
6079 caller_config.servers.push_back(ice_server);
6080 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
6081 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006082 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07006083
6084 PeerConnectionInterface::RTCConfiguration callee_config;
6085 callee_config.servers.push_back(ice_server);
6086 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
6087 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07006088 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07006089
6090 ASSERT_TRUE(
6091 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
6092
6093 // Do normal offer/answer and wait for ICE to complete.
6094 ConnectFakeSignaling();
6095 caller()->AddAudioVideoTracks();
6096 callee()->AddAudioVideoTracks();
6097 caller()->CreateAndSetAndSignalOffer();
6098 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6099 // Since we are doing continual gathering, the ICE transport does not reach
6100 // kIceGatheringComplete (see
6101 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
6102 // kIceConnectionComplete.
6103 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
6104 caller()->ice_connection_state(), kDefaultTimeout);
6105 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
6106 callee()->ice_connection_state(), kDefaultTimeout);
6107 // Note that we cannot use the metric
6108 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
6109 // metric is only populated when we reach kIceConnectionComplete in the
6110 // current implementation.
6111 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
6112 caller()->last_candidate_gathered().type());
6113 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
6114 callee()->last_candidate_gathered().type());
6115
6116 // Loosen the caller's candidate filter.
6117 caller_config = caller()->pc()->GetConfiguration();
6118 caller_config.type = webrtc::PeerConnectionInterface::kAll;
6119 caller()->pc()->SetConfiguration(caller_config);
6120 // We should have gathered a new host candidate.
6121 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
6122 caller()->last_candidate_gathered().type(), kDefaultTimeout);
6123
6124 // Loosen the callee's candidate filter.
6125 callee_config = callee()->pc()->GetConfiguration();
6126 callee_config.type = webrtc::PeerConnectionInterface::kAll;
6127 callee()->pc()->SetConfiguration(callee_config);
6128 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
6129 callee()->last_candidate_gathered().type(), kDefaultTimeout);
6130}
6131
Eldar Relloda13ea22019-06-01 12:23:43 +03006132TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03006133 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
6134 3478};
6135 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
6136
6137 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
6138
6139 webrtc::PeerConnectionInterface::IceServer ice_server;
6140 ice_server.urls.push_back("turn:88.88.88.0:3478");
6141 ice_server.username = "test";
6142 ice_server.password = "123";
6143
6144 PeerConnectionInterface::RTCConfiguration caller_config;
6145 caller_config.servers.push_back(ice_server);
6146 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
6147 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
6148
6149 PeerConnectionInterface::RTCConfiguration callee_config;
6150 callee_config.servers.push_back(ice_server);
6151 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
6152 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
6153
6154 ASSERT_TRUE(
6155 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
6156
6157 // Do normal offer/answer and wait for ICE to complete.
6158 ConnectFakeSignaling();
6159 caller()->AddAudioVideoTracks();
6160 callee()->AddAudioVideoTracks();
6161 caller()->CreateAndSetAndSignalOffer();
6162 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6163 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
6164 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
6165 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
Eldar Rello0095d372019-12-02 22:22:07 +02006166 EXPECT_NE(caller()->error_event().address, "");
Eldar Relloda13ea22019-06-01 12:23:43 +03006167}
6168
Eldar Rello5ab79e62019-10-09 18:29:44 +03006169TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6170 AudioKeepsFlowingAfterImplicitRollback) {
6171 PeerConnectionInterface::RTCConfiguration config;
6172 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
6173 config.enable_implicit_rollback = true;
6174 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
6175 ConnectFakeSignaling();
6176 caller()->AddAudioTrack();
6177 callee()->AddAudioTrack();
6178 caller()->CreateAndSetAndSignalOffer();
6179 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6180 MediaExpectations media_expectations;
6181 media_expectations.ExpectBidirectionalAudio();
6182 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6183 SetSignalIceCandidates(false); // Workaround candidate outrace sdp.
6184 caller()->AddVideoTrack();
6185 callee()->AddVideoTrack();
6186 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
6187 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
6188 callee()->pc()->SetLocalDescription(observer,
6189 callee()->CreateOfferAndWait().release());
6190 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
6191 caller()->CreateAndSetAndSignalOffer(); // Implicit rollback.
6192 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6193 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6194}
6195
6196TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6197 ImplicitRollbackVisitsStableState) {
6198 RTCConfiguration config;
6199 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
6200 config.enable_implicit_rollback = true;
6201
6202 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
6203
6204 rtc::scoped_refptr<MockSetSessionDescriptionObserver> sld_observer(
6205 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
6206 callee()->pc()->SetLocalDescription(sld_observer,
6207 callee()->CreateOfferAndWait().release());
6208 EXPECT_TRUE_WAIT(sld_observer->called(), kDefaultTimeout);
6209 EXPECT_EQ(sld_observer->error(), "");
6210
6211 rtc::scoped_refptr<MockSetSessionDescriptionObserver> srd_observer(
6212 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
6213 callee()->pc()->SetRemoteDescription(
6214 srd_observer, caller()->CreateOfferAndWait().release());
6215 EXPECT_TRUE_WAIT(srd_observer->called(), kDefaultTimeout);
6216 EXPECT_EQ(srd_observer->error(), "");
6217
6218 EXPECT_THAT(callee()->peer_connection_signaling_state_history(),
6219 ElementsAre(PeerConnectionInterface::kHaveLocalOffer,
6220 PeerConnectionInterface::kStable,
6221 PeerConnectionInterface::kHaveRemoteOffer));
6222}
6223
Mirko Bonadeic84f6612019-01-31 12:20:57 +01006224INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
6225 PeerConnectionIntegrationTest,
6226 Values(SdpSemantics::kPlanB,
6227 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08006228
Yves Gerey100fe632020-01-17 19:15:53 +01006229INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
6230 PeerConnectionIntegrationTestWithFakeClock,
6231 Values(SdpSemantics::kPlanB,
6232 SdpSemantics::kUnifiedPlan));
6233
Steve Anton74255ff2018-01-24 18:32:57 -08006234// Tests that verify interoperability between Plan B and Unified Plan
6235// PeerConnections.
6236class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08006237 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08006238 public ::testing::WithParamInterface<
6239 std::tuple<SdpSemantics, SdpSemantics>> {
6240 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08006241 // Setting the SdpSemantics for the base test to kDefault does not matter
6242 // because we specify not to use the test semantics when creating
6243 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08006244 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07006245 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08006246 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08006247 callee_semantics_(std::get<1>(GetParam())) {}
6248
6249 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07006250 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
6251 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08006252 }
6253
6254 const SdpSemantics caller_semantics_;
6255 const SdpSemantics callee_semantics_;
6256};
6257
6258TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
6259 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6260 ConnectFakeSignaling();
6261
6262 caller()->CreateAndSetAndSignalOffer();
6263 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6264}
6265
6266TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
6267 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6268 ConnectFakeSignaling();
6269 auto audio_sender = caller()->AddAudioTrack();
6270
6271 caller()->CreateAndSetAndSignalOffer();
6272 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6273
6274 // Verify that one audio receiver has been created on the remote and that it
6275 // has the same track ID as the sending track.
6276 auto receivers = callee()->pc()->GetReceivers();
6277 ASSERT_EQ(1u, receivers.size());
6278 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
6279 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
6280
Seth Hampson2f0d7022018-02-20 11:54:42 -08006281 MediaExpectations media_expectations;
6282 media_expectations.CalleeExpectsSomeAudio();
6283 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006284}
6285
6286TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
6287 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6288 ConnectFakeSignaling();
6289 auto video_sender = caller()->AddVideoTrack();
6290 auto audio_sender = caller()->AddAudioTrack();
6291
6292 caller()->CreateAndSetAndSignalOffer();
6293 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6294
6295 // Verify that one audio and one video receiver have been created on the
6296 // remote and that they have the same track IDs as the sending tracks.
6297 auto audio_receivers =
6298 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
6299 ASSERT_EQ(1u, audio_receivers.size());
6300 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
6301 auto video_receivers =
6302 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
6303 ASSERT_EQ(1u, video_receivers.size());
6304 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
6305
Seth Hampson2f0d7022018-02-20 11:54:42 -08006306 MediaExpectations media_expectations;
6307 media_expectations.CalleeExpectsSomeAudioAndVideo();
6308 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006309}
6310
6311TEST_P(PeerConnectionIntegrationInteropTest,
6312 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
6313 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6314 ConnectFakeSignaling();
6315 caller()->AddAudioVideoTracks();
6316 callee()->AddAudioVideoTracks();
6317
6318 caller()->CreateAndSetAndSignalOffer();
6319 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6320
Seth Hampson2f0d7022018-02-20 11:54:42 -08006321 MediaExpectations media_expectations;
6322 media_expectations.ExpectBidirectionalAudioAndVideo();
6323 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006324}
6325
6326TEST_P(PeerConnectionIntegrationInteropTest,
6327 ReverseRolesOneAudioLocalToOneVideoRemote) {
6328 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6329 ConnectFakeSignaling();
6330 caller()->AddAudioTrack();
6331 callee()->AddVideoTrack();
6332
6333 caller()->CreateAndSetAndSignalOffer();
6334 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6335
6336 // Verify that only the audio track has been negotiated.
6337 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
6338 // Might also check that the callee's NegotiationNeeded flag is set.
6339
6340 // Reverse roles.
6341 callee()->CreateAndSetAndSignalOffer();
6342 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6343
Seth Hampson2f0d7022018-02-20 11:54:42 -08006344 MediaExpectations media_expectations;
6345 media_expectations.CallerExpectsSomeVideo();
6346 media_expectations.CalleeExpectsSomeAudio();
6347 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006348}
6349
Mirko Bonadeic84f6612019-01-31 12:20:57 +01006350INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07006351 PeerConnectionIntegrationTest,
6352 PeerConnectionIntegrationInteropTest,
6353 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
6354 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
6355
6356// Test that if the Unified Plan side offers two video tracks then the Plan B
6357// side will only see the first one and ignore the second.
6358TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07006359 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
6360 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08006361 ConnectFakeSignaling();
6362 auto first_sender = caller()->AddVideoTrack();
6363 caller()->AddVideoTrack();
6364
6365 caller()->CreateAndSetAndSignalOffer();
6366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6367
6368 // Verify that there is only one receiver and it corresponds to the first
6369 // added track.
6370 auto receivers = callee()->pc()->GetReceivers();
6371 ASSERT_EQ(1u, receivers.size());
6372 EXPECT_TRUE(receivers[0]->track()->enabled());
6373 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
6374
Seth Hampson2f0d7022018-02-20 11:54:42 -08006375 MediaExpectations media_expectations;
6376 media_expectations.CalleeExpectsSomeVideo();
6377 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006378}
6379
Steve Anton2bed3972019-01-04 17:04:30 -08006380// Test that if the initial offer tagged BUNDLE section is rejected due to its
6381// associated RtpTransceiver being stopped and another transceiver is added,
6382// then renegotiation causes the callee to receive the new video track without
6383// error.
6384// This is a regression test for bugs.webrtc.org/9954
6385TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6386 ReOfferWithStoppedBundleTaggedTransceiver) {
6387 RTCConfiguration config;
6388 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
6389 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
6390 ConnectFakeSignaling();
6391 auto audio_transceiver_or_error =
6392 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
6393 ASSERT_TRUE(audio_transceiver_or_error.ok());
6394 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
6395
6396 caller()->CreateAndSetAndSignalOffer();
6397 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6398 {
6399 MediaExpectations media_expectations;
6400 media_expectations.CalleeExpectsSomeAudio();
6401 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6402 }
6403
6404 audio_transceiver->Stop();
6405 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
6406
6407 caller()->CreateAndSetAndSignalOffer();
6408 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6409 {
6410 MediaExpectations media_expectations;
6411 media_expectations.CalleeExpectsSomeVideo();
6412 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6413 }
6414}
6415
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006416#ifdef HAVE_SCTP
6417
6418TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6419 EndToEndCallWithBundledSctpDataChannel) {
6420 ASSERT_TRUE(CreatePeerConnectionWrappers());
6421 ConnectFakeSignaling();
6422 caller()->CreateDataChannel();
6423 caller()->AddAudioVideoTracks();
6424 callee()->AddAudioVideoTracks();
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006425 caller()->CreateAndSetAndSignalOffer();
6426 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01006427 ASSERT_EQ_WAIT(SctpTransportState::kConnected,
6428 caller()->pc()->GetSctpTransport()->Information().state(),
6429 kDefaultTimeout);
6430 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
6431 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6432}
6433
6434TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6435 EndToEndCallWithDataChannelOnlyConnects) {
6436 ASSERT_TRUE(CreatePeerConnectionWrappers());
6437 ConnectFakeSignaling();
6438 caller()->CreateDataChannel();
6439 caller()->CreateAndSetAndSignalOffer();
6440 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6441 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
6442 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6443 ASSERT_TRUE(caller()->data_observer()->IsOpen());
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006444}
6445
Harald Alvestrand2697ac12019-12-16 10:37:04 +01006446TEST_F(PeerConnectionIntegrationTestUnifiedPlan, DataChannelClosesWhenClosed) {
6447 ASSERT_TRUE(CreatePeerConnectionWrappers());
6448 ConnectFakeSignaling();
6449 caller()->CreateDataChannel();
6450 caller()->CreateAndSetAndSignalOffer();
6451 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6452 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6453 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6454 caller()->data_channel()->Close();
6455 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
6456}
6457
6458TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6459 DataChannelClosesWhenClosedReverse) {
6460 ASSERT_TRUE(CreatePeerConnectionWrappers());
6461 ConnectFakeSignaling();
6462 caller()->CreateDataChannel();
6463 caller()->CreateAndSetAndSignalOffer();
6464 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6465 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6466 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6467 callee()->data_channel()->Close();
6468 ASSERT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
6469}
6470
6471TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6472 DataChannelClosesWhenPeerConnectionClosed) {
6473 ASSERT_TRUE(CreatePeerConnectionWrappers());
6474 ConnectFakeSignaling();
6475 caller()->CreateDataChannel();
6476 caller()->CreateAndSetAndSignalOffer();
6477 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6478 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6479 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6480 caller()->pc()->Close();
6481 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
6482}
6483
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006484#endif // HAVE_SCTP
6485
deadbeef1dcb1642017-03-29 21:08:16 -07006486} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01006487} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07006488
6489#endif // if !defined(THREAD_SANITIZER)