blob: 4b098e1d5fed34e6c952e7d3abf0736e9d1228c7 [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"
Erik Språngceb44952020-09-22 11:36:35 +020031#include "api/transport/field_trial_based_config.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"
Per Åhgrencc73ed32020-04-26 23:56:17 +020039#include "modules/audio_processing/test/audio_processing_builder_for_testing.h"
Qingsi Wang25ec8882019-11-15 12:33:05 -080040#include "p2p/base/fake_ice_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "p2p/base/mock_async_resolver.h"
42#include "p2p/base/p2p_constants.h"
43#include "p2p/base/port_interface.h"
44#include "p2p/base/test_stun_server.h"
45#include "p2p/base/test_turn_customizer.h"
46#include "p2p/base/test_turn_server.h"
47#include "p2p/client/basic_port_allocator.h"
48#include "pc/dtmf_sender.h"
49#include "pc/local_audio_source.h"
50#include "pc/media_session.h"
51#include "pc/peer_connection.h"
52#include "pc/peer_connection_factory.h"
53#include "pc/rtp_media_utils.h"
54#include "pc/session_description.h"
55#include "pc/test/fake_audio_capture_module.h"
56#include "pc/test/fake_periodic_video_track_source.h"
57#include "pc/test/fake_rtc_certificate_generator.h"
58#include "pc/test/fake_video_track_renderer.h"
59#include "pc/test/mock_peer_connection_observers.h"
Jonas Olssonb75d9e92019-02-22 10:33:29 +010060#include "rtc_base/fake_clock.h"
Qingsi Wangecd30542019-05-22 14:34:56 -070061#include "rtc_base/fake_mdns_responder.h"
Steve Anton10542f22019-01-11 09:11:00 -080062#include "rtc_base/fake_network.h"
63#include "rtc_base/firewall_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020064#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020065#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080066#include "rtc_base/test_certificate_verifier.h"
67#include "rtc_base/time_utils.h"
68#include "rtc_base/virtual_socket_server.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020069#include "system_wrappers/include/metrics.h"
Qingsi Wangc129c352019-04-18 10:41:58 -070070#include "test/field_trial.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020071#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070072
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010073namespace webrtc {
74namespace {
75
76using ::cricket::ContentInfo;
77using ::cricket::StreamParams;
78using ::rtc::SocketAddress;
79using ::testing::_;
Seth Hampson2f0d7022018-02-20 11:54:42 -080080using ::testing::Combine;
Steve Anton64b626b2019-01-28 17:25:26 -080081using ::testing::Contains;
Mirko Bonadeie46f5db2019-03-26 20:14:46 +010082using ::testing::DoAll;
Steve Antonede9ca52017-10-16 13:04:27 -070083using ::testing::ElementsAre;
Qingsi Wang1dac6d82018-12-12 15:28:47 -080084using ::testing::NiceMock;
Steve Anton64b626b2019-01-28 17:25:26 -080085using ::testing::Return;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070086using ::testing::SetArgPointee;
Steve Antonffa6ce42018-11-30 09:26:08 -080087using ::testing::UnorderedElementsAreArray;
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010088using ::testing::Values;
Steve Anton74255ff2018-01-24 18:32:57 -080089using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -070090
91static const int kDefaultTimeout = 10000;
92static const int kMaxWaitForStatsMs = 3000;
93static const int kMaxWaitForActivationMs = 5000;
94static const int kMaxWaitForFramesMs = 10000;
95// Default number of audio/video frames to wait for before considering a test
96// successful.
97static const int kDefaultExpectedAudioFrameCount = 3;
98static const int kDefaultExpectedVideoFrameCount = 3;
99
deadbeef1dcb1642017-03-29 21:08:16 -0700100static const char kDataChannelLabel[] = "data_channel";
101
102// SRTP cipher name negotiated by the tests. This must be updated if the
103// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700104static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700105static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
106
Steve Antonede9ca52017-10-16 13:04:27 -0700107static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
108
deadbeef1dcb1642017-03-29 21:08:16 -0700109// Helper function for constructing offer/answer options to initiate an ICE
110// restart.
111PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
112 PeerConnectionInterface::RTCOfferAnswerOptions options;
113 options.ice_restart = true;
114 return options;
115}
116
deadbeefd8ad7882017-04-18 16:01:17 -0700117// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
118// attribute from received SDP, simulating a legacy endpoint.
119void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
120 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800121 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700122 }
123 desc->set_msid_supported(false);
Henrik Boström5b147782018-12-04 11:25:05 +0100124 desc->set_msid_signaling(0);
deadbeefd8ad7882017-04-18 16:01:17 -0700125}
126
Seth Hampson5897a6e2018-04-03 11:16:33 -0700127// Removes all stream information besides the stream ids, simulating an
128// endpoint that only signals a=msid lines to convey stream_ids.
129void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
130 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700131 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700132 std::vector<std::string> stream_ids;
133 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700134 const StreamParams& first_stream =
135 content.media_description()->streams()[0];
136 track_id = first_stream.id;
137 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700138 }
139 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700140 StreamParams new_stream;
141 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700142 new_stream.set_stream_ids(stream_ids);
143 content.media_description()->AddStream(new_stream);
144 }
145}
146
zhihuangf8164932017-05-19 13:09:47 -0700147int FindFirstMediaStatsIndexByKind(
148 const std::string& kind,
149 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
150 media_stats_vec) {
151 for (size_t i = 0; i < media_stats_vec.size(); i++) {
152 if (media_stats_vec[i]->kind.ValueToString() == kind) {
153 return i;
154 }
155 }
156 return -1;
157}
158
deadbeef1dcb1642017-03-29 21:08:16 -0700159class SignalingMessageReceiver {
160 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800161 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700162 virtual void ReceiveIceMessage(const std::string& sdp_mid,
163 int sdp_mline_index,
164 const std::string& msg) = 0;
165
166 protected:
167 SignalingMessageReceiver() {}
168 virtual ~SignalingMessageReceiver() {}
169};
170
171class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
172 public:
173 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
174 : expected_media_type_(media_type) {}
175
176 void OnFirstPacketReceived(cricket::MediaType media_type) override {
177 ASSERT_EQ(expected_media_type_, media_type);
178 first_packet_received_ = true;
179 }
180
181 bool first_packet_received() const { return first_packet_received_; }
182
183 virtual ~MockRtpReceiverObserver() {}
184
185 private:
186 bool first_packet_received_ = false;
187 cricket::MediaType expected_media_type_;
188};
189
190// Helper class that wraps a peer connection, observes it, and can accept
191// signaling messages from another wrapper.
192//
193// Uses a fake network, fake A/V capture, and optionally fake
194// encoders/decoders, though they aren't used by default since they don't
195// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700196// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800197// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700198class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800199 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700200 public:
201 // Different factory methods for convenience.
202 // TODO(deadbeef): Could use the pattern of:
203 //
204 // PeerConnectionWrapper =
205 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
206 //
207 // To reduce some code duplication.
208 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
209 const std::string& debug_name,
210 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
211 rtc::Thread* network_thread,
212 rtc::Thread* worker_thread) {
213 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700214 webrtc::PeerConnectionDependencies dependencies(nullptr);
215 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200216 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800217 worker_thread, nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +0200218 /*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 bool reset_encoder_factory,
614 bool reset_decoder_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700615 // There's an error in this test code if Init ends up being called twice.
616 RTC_DCHECK(!peer_connection_);
617 RTC_DCHECK(!peer_connection_factory_);
618
619 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700620 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700621
622 std::unique_ptr<cricket::PortAllocator> port_allocator(
623 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700624 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700625 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
626 if (!fake_audio_capture_module_) {
627 return false;
628 }
deadbeef1dcb1642017-03-29 21:08:16 -0700629 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700630
631 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
632 pc_factory_dependencies.network_thread = network_thread;
633 pc_factory_dependencies.worker_thread = worker_thread;
634 pc_factory_dependencies.signaling_thread = signaling_thread;
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200635 pc_factory_dependencies.task_queue_factory =
636 webrtc::CreateDefaultTaskQueueFactory();
Erik Språngceb44952020-09-22 11:36:35 +0200637 pc_factory_dependencies.trials = std::make_unique<FieldTrialBasedConfig>();
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200638 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
Per Åhgrencc73ed32020-04-26 23:56:17 +0200651 if (!media_deps.audio_processing) {
652 // If the standard Creation method for APM returns a null pointer, instead
653 // use the builder for testing to create an APM object.
654 media_deps.audio_processing = AudioProcessingBuilderForTesting().Create();
655 }
656
Erik Språngceb44952020-09-22 11:36:35 +0200657 media_deps.trials = pc_factory_dependencies.trials.get();
658
Qingsi Wang7685e862018-06-11 20:15:46 -0700659 pc_factory_dependencies.media_engine =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200660 cricket::CreateMediaEngine(std::move(media_deps));
Qingsi Wang7685e862018-06-11 20:15:46 -0700661 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
662 if (event_log_factory) {
663 event_log_factory_ = event_log_factory.get();
664 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
665 } else {
666 pc_factory_dependencies.event_log_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200667 std::make_unique<webrtc::RtcEventLogFactory>(
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200668 pc_factory_dependencies.task_queue_factory.get());
Qingsi Wang7685e862018-06-11 20:15:46 -0700669 }
670 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
671 std::move(pc_factory_dependencies));
672
deadbeef1dcb1642017-03-29 21:08:16 -0700673 if (!peer_connection_factory_) {
674 return false;
675 }
676 if (options) {
677 peer_connection_factory_->SetOptions(*options);
678 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800679 if (config) {
680 sdp_semantics_ = config->sdp_semantics;
681 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700682
683 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200684 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700685 return peer_connection_.get() != nullptr;
686 }
687
688 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700689 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700690 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700691 PeerConnectionInterface::RTCConfiguration modified_config;
692 // If |config| is null, this will result in a default configuration being
693 // used.
694 if (config) {
695 modified_config = *config;
696 }
697 // Disable resolution adaptation; we don't want it interfering with the
698 // test results.
699 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
700 // ratios and not specific resolutions, is this even necessary?
701 modified_config.set_cpu_adaptation(false);
702
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700703 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700704 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700705 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700706 }
707
708 void set_signaling_message_receiver(
709 SignalingMessageReceiver* signaling_message_receiver) {
710 signaling_message_receiver_ = signaling_message_receiver;
711 }
712
713 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
714
Steve Antonede9ca52017-10-16 13:04:27 -0700715 void set_signal_ice_candidates(bool signal) {
716 signal_ice_candidates_ = signal;
717 }
718
deadbeef1dcb1642017-03-29 21:08:16 -0700719 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200720 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700721 // Set max frame rate to 10fps to reduce the risk of test flakiness.
722 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200723 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700724
Niels Möller5c7efe72018-05-11 10:34:46 +0200725 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200726 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
727 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700728 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200729 peer_connection_factory_->CreateVideoTrack(
730 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700731 if (!local_video_renderer_) {
732 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
733 }
734 return track;
735 }
736
737 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800739 std::unique_ptr<SessionDescriptionInterface> desc =
740 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700741 if (received_sdp_munger_) {
742 received_sdp_munger_(desc->description());
743 }
744
745 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
746 // Setting a remote description may have changed the number of receivers,
747 // so reset the receiver observers.
748 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800749 if (remote_offer_handler_) {
750 remote_offer_handler_();
751 }
deadbeef1dcb1642017-03-29 21:08:16 -0700752 auto answer = CreateAnswer();
753 ASSERT_NE(nullptr, answer);
754 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
755 }
756
757 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100758 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800759 std::unique_ptr<SessionDescriptionInterface> desc =
760 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700761 if (received_sdp_munger_) {
762 received_sdp_munger_(desc->description());
763 }
764
765 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
766 // Set the RtpReceiverObserver after receivers are created.
767 ResetRtpReceiverObservers();
768 }
769
770 // Returns null on failure.
deadbeef1dcb1642017-03-29 21:08:16 -0700771 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
772 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
773 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
774 pc()->CreateAnswer(observer, offer_answer_options_);
775 return WaitForDescriptionFromObserver(observer);
776 }
777
778 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100779 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700780 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
781 if (!observer->result()) {
782 return nullptr;
783 }
784 auto description = observer->MoveDescription();
785 if (generated_sdp_munger_) {
786 generated_sdp_munger_(description->description());
787 }
788 return description;
789 }
790
791 // Setting the local description and sending the SDP message over the fake
792 // signaling channel are combined into the same method because the SDP
793 // message needs to be sent as soon as SetLocalDescription finishes, without
794 // waiting for the observer to be called. This ensures that ICE candidates
795 // don't outrace the description.
796 bool SetLocalDescriptionAndSendSdpMessage(
797 std::unique_ptr<SessionDescriptionInterface> desc) {
798 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
799 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100800 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800801 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700802 std::string sdp;
803 EXPECT_TRUE(desc->ToString(&sdp));
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700804 RTC_LOG(LS_INFO) << debug_name_ << ": local SDP contents=\n" << sdp;
deadbeef1dcb1642017-03-29 21:08:16 -0700805 pc()->SetLocalDescription(observer, desc.release());
Harald Alvestrand6060df52020-08-11 09:54:02 +0200806 RemoveUnusedVideoRenderers();
deadbeef1dcb1642017-03-29 21:08:16 -0700807 // As mentioned above, we need to send the message immediately after
808 // SetLocalDescription.
809 SendSdpMessage(type, sdp);
810 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
811 return true;
812 }
813
814 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
815 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
816 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100817 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700818 pc()->SetRemoteDescription(observer, desc.release());
Harald Alvestrand6060df52020-08-11 09:54:02 +0200819 RemoveUnusedVideoRenderers();
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() {
Harald Alvestrand6060df52020-08-11 09:54:02 +0200827 if (sdp_semantics_ != SdpSemantics::kUnifiedPlan) {
828 return;
829 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800830 auto transceivers = pc()->GetTransceivers();
Harald Alvestrand6060df52020-08-11 09:54:02 +0200831 std::set<std::string> active_renderers;
Seth Hampson2f0d7022018-02-20 11:54:42 -0800832 for (auto& transceiver : transceivers) {
Harald Alvestrand6060df52020-08-11 09:54:02 +0200833 // Note - we don't check for direction here. This function is called
834 // before direction is set, and in that case, we should not remove
835 // the renderer.
836 if (transceiver->receiver()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
837 active_renderers.insert(transceiver->receiver()->track()->id());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800838 }
Harald Alvestrand6060df52020-08-11 09:54:02 +0200839 }
840 for (auto it = fake_video_renderers_.begin();
841 it != fake_video_renderers_.end();) {
842 // Remove fake video renderers belonging to any non-active transceivers.
843 if (!active_renderers.count(it->first)) {
844 it = fake_video_renderers_.erase(it);
845 } else {
846 it++;
Seth Hampson2f0d7022018-02-20 11:54:42 -0800847 }
848 }
849 }
850
deadbeef1dcb1642017-03-29 21:08:16 -0700851 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
852 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800853 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700854 if (signaling_delay_ms_ == 0) {
855 RelaySdpMessageIfReceiverExists(type, msg);
856 } else {
857 invoker_.AsyncInvokeDelayed<void>(
858 RTC_FROM_HERE, rtc::Thread::Current(),
859 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
860 this, type, msg),
861 signaling_delay_ms_);
862 }
863 }
864
Steve Antona3a92c22017-12-07 10:27:41 -0800865 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700866 if (signaling_message_receiver_) {
867 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
868 }
869 }
870
871 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
872 // default).
873 void SendIceMessage(const std::string& sdp_mid,
874 int sdp_mline_index,
875 const std::string& msg) {
876 if (signaling_delay_ms_ == 0) {
877 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
878 } else {
879 invoker_.AsyncInvokeDelayed<void>(
880 RTC_FROM_HERE, rtc::Thread::Current(),
881 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
882 this, sdp_mid, sdp_mline_index, msg),
883 signaling_delay_ms_);
884 }
885 }
886
887 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
888 int sdp_mline_index,
889 const std::string& msg) {
890 if (signaling_message_receiver_) {
891 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
892 msg);
893 }
894 }
895
896 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800897 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
898 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700899 HandleIncomingOffer(msg);
900 } else {
901 HandleIncomingAnswer(msg);
902 }
903 }
904
905 void ReceiveIceMessage(const std::string& sdp_mid,
906 int sdp_mline_index,
907 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100908 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700909 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
910 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
911 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
912 }
913
914 // PeerConnectionObserver callbacks.
915 void OnSignalingChange(
916 webrtc::PeerConnectionInterface::SignalingState new_state) override {
917 EXPECT_EQ(pc()->signaling_state(), new_state);
Eldar Rello5ab79e62019-10-09 18:29:44 +0300918 peer_connection_signaling_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700919 }
Steve Anton15324772018-01-16 10:26:49 -0800920 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
921 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
922 streams) override {
923 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
924 rtc::scoped_refptr<VideoTrackInterface> video_track(
925 static_cast<VideoTrackInterface*>(receiver->track().get()));
926 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700927 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800928 fake_video_renderers_[video_track->id()] =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200929 std::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700930 }
931 }
Steve Anton15324772018-01-16 10:26:49 -0800932 void OnRemoveTrack(
933 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
934 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
935 auto it = fake_video_renderers_.find(receiver->track()->id());
Harald Alvestrand6060df52020-08-11 09:54:02 +0200936 if (it != fake_video_renderers_.end()) {
937 fake_video_renderers_.erase(it);
938 } else {
939 RTC_LOG(LS_ERROR) << "OnRemoveTrack called for non-active renderer";
940 }
Steve Anton15324772018-01-16 10:26:49 -0800941 }
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;
Danil Chapovalov3a353122020-05-15 11:16:53 +02001078 MOCK_METHOD(bool, IsActive, (), (const, override));
1079 MOCK_METHOD(bool, Write, (const std::string&), (override));
Elad Alon99c3fe52017-10-13 16:29:40 +02001080};
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 }
Danil Chapovalov3a353122020-05-15 11:16:53 +02001212 MOCK_METHOD(void, RecordIceTransportCreated, ());
Qingsi Wang25ec8882019-11-15 12:33:05 -08001213};
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())),
Niels Möller2a707032020-06-16 16:39:13 +02001226 worker_thread_(rtc::Thread::Create()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001227 network_thread_->SetName("PCNetworkThread", this);
1228 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001229 RTC_CHECK(network_thread_->Start());
1230 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001231 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001232 }
1233
Seth Hampson2f0d7022018-02-20 11:54:42 -08001234 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001235 // The PeerConnections should deleted before the TurnCustomizers.
1236 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1237 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1238 // that the TurnCustomizer outlives the life of the PeerConnection or else
1239 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001240 if (caller_) {
1241 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001242 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001243 }
1244 if (callee_) {
1245 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001246 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001247 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001248
1249 // If turn servers were created for the test they need to be destroyed on
1250 // the network thread.
1251 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1252 turn_servers_.clear();
1253 turn_customizers_.clear();
1254 });
deadbeef1dcb1642017-03-29 21:08:16 -07001255 }
1256
1257 bool SignalingStateStable() {
1258 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1259 }
1260
deadbeef71452802017-05-07 17:21:01 -07001261 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001262 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1263 // are connected. This is an important distinction. Once we have separate
1264 // ICE and DTLS state, this check needs to use the DTLS state.
1265 return (callee()->ice_connection_state() ==
1266 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1267 callee()->ice_connection_state() ==
1268 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1269 (caller()->ice_connection_state() ==
1270 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1271 caller()->ice_connection_state() ==
1272 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001273 }
1274
Qingsi Wang7685e862018-06-11 20:15:46 -07001275 // When |event_log_factory| is null, the default implementation of the event
1276 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001277 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1278 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001279 const PeerConnectionFactory::Options* options,
1280 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001281 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001282 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron3e983682020-03-29 22:17:00 +02001283 bool reset_encoder_factory,
1284 bool reset_decoder_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001285 RTCConfiguration modified_config;
1286 if (config) {
1287 modified_config = *config;
1288 }
Steve Anton3acffc32018-04-12 17:21:03 -07001289 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001290 if (!dependencies.cert_generator) {
1291 dependencies.cert_generator =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001292 std::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001293 }
1294 std::unique_ptr<PeerConnectionWrapper> client(
1295 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001296
Niels Möllerf06f9232018-08-07 12:32:18 +02001297 if (!client->Init(options, &modified_config, std::move(dependencies),
1298 network_thread_.get(), worker_thread_.get(),
Niels Möller2a707032020-06-16 16:39:13 +02001299 std::move(event_log_factory), reset_encoder_factory,
Johannes Kron3e983682020-03-29 22:17:00 +02001300 reset_decoder_factory)) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001301 return nullptr;
1302 }
1303 return client;
1304 }
1305
Qingsi Wang7685e862018-06-11 20:15:46 -07001306 std::unique_ptr<PeerConnectionWrapper>
1307 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1308 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001309 const PeerConnectionFactory::Options* options,
1310 const RTCConfiguration* config,
1311 webrtc::PeerConnectionDependencies dependencies) {
1312 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1313 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möller2a707032020-06-16 16:39:13 +02001314 return CreatePeerConnectionWrapper(debug_name, options, config,
1315 std::move(dependencies),
1316 std::move(event_log_factory),
1317 /*reset_encoder_factory=*/false,
1318 /*reset_decoder_factory=*/false);
Qingsi Wang7685e862018-06-11 20:15:46 -07001319 }
1320
deadbeef1dcb1642017-03-29 21:08:16 -07001321 bool CreatePeerConnectionWrappers() {
1322 return CreatePeerConnectionWrappersWithConfig(
1323 PeerConnectionInterface::RTCConfiguration(),
1324 PeerConnectionInterface::RTCConfiguration());
1325 }
1326
Steve Anton3acffc32018-04-12 17:21:03 -07001327 bool CreatePeerConnectionWrappersWithSdpSemantics(
1328 SdpSemantics caller_semantics,
1329 SdpSemantics callee_semantics) {
1330 // Can't specify the sdp_semantics in the passed-in configuration since it
1331 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1332 // stored in sdp_semantics_. So get around this by modifying the instance
1333 // variable before calling CreatePeerConnectionWrapper for the caller and
1334 // callee PeerConnections.
1335 SdpSemantics original_semantics = sdp_semantics_;
1336 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001337 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001338 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Niels Möller2a707032020-06-16 16:39:13 +02001339 nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001340 /*reset_encoder_factory=*/false,
1341 /*reset_decoder_factory=*/false);
Steve Anton3acffc32018-04-12 17:21:03 -07001342 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001343 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001344 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Niels Möller2a707032020-06-16 16:39:13 +02001345 nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001346 /*reset_encoder_factory=*/false,
1347 /*reset_decoder_factory=*/false);
Steve Anton3acffc32018-04-12 17:21:03 -07001348 sdp_semantics_ = original_semantics;
1349 return caller_ && callee_;
1350 }
1351
deadbeef1dcb1642017-03-29 21:08:16 -07001352 bool CreatePeerConnectionWrappersWithConfig(
1353 const PeerConnectionInterface::RTCConfiguration& caller_config,
1354 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001355 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001356 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001357 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Niels Möller2a707032020-06-16 16:39:13 +02001358 /*reset_encoder_factory=*/false,
Johannes Kron3e983682020-03-29 22:17:00 +02001359 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001360 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001361 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001362 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Niels Möller2a707032020-06-16 16:39:13 +02001363 /*reset_encoder_factory=*/false,
Johannes Kron3e983682020-03-29 22:17:00 +02001364 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001365 return caller_ && callee_;
1366 }
1367
1368 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1369 const PeerConnectionInterface::RTCConfiguration& caller_config,
1370 webrtc::PeerConnectionDependencies caller_dependencies,
1371 const PeerConnectionInterface::RTCConfiguration& callee_config,
1372 webrtc::PeerConnectionDependencies callee_dependencies) {
Niels Möller2a707032020-06-16 16:39:13 +02001373 caller_ =
1374 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1375 std::move(caller_dependencies), nullptr,
1376 /*reset_encoder_factory=*/false,
1377 /*reset_decoder_factory=*/false);
1378 callee_ =
1379 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1380 std::move(callee_dependencies), nullptr,
1381 /*reset_encoder_factory=*/false,
1382 /*reset_decoder_factory=*/false);
deadbeef1dcb1642017-03-29 21:08:16 -07001383 return caller_ && callee_;
1384 }
1385
1386 bool CreatePeerConnectionWrappersWithOptions(
1387 const PeerConnectionFactory::Options& caller_options,
1388 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001389 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001390 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001391 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Niels Möller2a707032020-06-16 16:39:13 +02001392 /*reset_encoder_factory=*/false,
Johannes Kron3e983682020-03-29 22:17:00 +02001393 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001394 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001395 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001396 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Niels Möller2a707032020-06-16 16:39:13 +02001397 /*reset_encoder_factory=*/false,
Johannes Kron3e983682020-03-29 22:17:00 +02001398 /*reset_decoder_factory=*/false);
Qingsi Wang7685e862018-06-11 20:15:46 -07001399 return caller_ && callee_;
1400 }
1401
1402 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1403 PeerConnectionInterface::RTCConfiguration default_config;
1404 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001405 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001406 webrtc::PeerConnectionDependencies(nullptr));
1407 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001408 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001409 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001410 return caller_ && callee_;
1411 }
1412
Seth Hampson2f0d7022018-02-20 11:54:42 -08001413 std::unique_ptr<PeerConnectionWrapper>
1414 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001415 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1416 new FakeRTCCertificateGenerator());
1417 cert_generator->use_alternate_key();
1418
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001419 webrtc::PeerConnectionDependencies dependencies(nullptr);
1420 dependencies.cert_generator = std::move(cert_generator);
Niels Möller2a707032020-06-16 16:39:13 +02001421 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
1422 std::move(dependencies), nullptr,
1423 /*reset_encoder_factory=*/false,
1424 /*reset_decoder_factory=*/false);
Johannes Kron3e983682020-03-29 22:17:00 +02001425 }
1426
1427 bool CreateOneDirectionalPeerConnectionWrappers(bool caller_to_callee) {
1428 caller_ = CreatePeerConnectionWrapper(
1429 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Niels Möller2a707032020-06-16 16:39:13 +02001430 nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001431 /*reset_encoder_factory=*/!caller_to_callee,
1432 /*reset_decoder_factory=*/caller_to_callee);
1433 callee_ = CreatePeerConnectionWrapper(
1434 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Niels Möller2a707032020-06-16 16:39:13 +02001435 nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001436 /*reset_encoder_factory=*/caller_to_callee,
1437 /*reset_decoder_factory=*/!caller_to_callee);
1438 return caller_ && callee_;
deadbeef1dcb1642017-03-29 21:08:16 -07001439 }
1440
Seth Hampsonaed71642018-06-11 07:41:32 -07001441 cricket::TestTurnServer* CreateTurnServer(
1442 rtc::SocketAddress internal_address,
1443 rtc::SocketAddress external_address,
1444 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1445 const std::string& common_name = "test turn server") {
1446 rtc::Thread* thread = network_thread();
1447 std::unique_ptr<cricket::TestTurnServer> turn_server =
1448 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1449 RTC_FROM_HERE,
1450 [thread, internal_address, external_address, type, common_name] {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001451 return std::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001452 thread, internal_address, external_address, type,
1453 /*ignore_bad_certs=*/true, common_name);
1454 });
1455 turn_servers_.push_back(std::move(turn_server));
1456 // Interactions with the turn server should be done on the network thread.
1457 return turn_servers_.back().get();
1458 }
1459
1460 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1461 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1462 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1463 RTC_FROM_HERE,
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001464 [] { return std::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001465 turn_customizers_.push_back(std::move(turn_customizer));
1466 // Interactions with the turn customizer should be done on the network
1467 // thread.
1468 return turn_customizers_.back().get();
1469 }
1470
1471 // Checks that the function counters for a TestTurnCustomizer are greater than
1472 // 0.
1473 void ExpectTurnCustomizerCountersIncremented(
1474 cricket::TestTurnCustomizer* turn_customizer) {
1475 unsigned int allow_channel_data_counter =
1476 network_thread()->Invoke<unsigned int>(
1477 RTC_FROM_HERE, [turn_customizer] {
1478 return turn_customizer->allow_channel_data_cnt_;
1479 });
1480 EXPECT_GT(allow_channel_data_counter, 0u);
1481 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1482 RTC_FROM_HERE,
1483 [turn_customizer] { return turn_customizer->modify_cnt_; });
1484 EXPECT_GT(modify_counter, 0u);
1485 }
1486
deadbeef1dcb1642017-03-29 21:08:16 -07001487 // Once called, SDP blobs and ICE candidates will be automatically signaled
1488 // between PeerConnections.
1489 void ConnectFakeSignaling() {
1490 caller_->set_signaling_message_receiver(callee_.get());
1491 callee_->set_signaling_message_receiver(caller_.get());
1492 }
1493
Steve Antonede9ca52017-10-16 13:04:27 -07001494 // Once called, SDP blobs will be automatically signaled between
1495 // PeerConnections. Note that ICE candidates will not be signaled unless they
1496 // are in the exchanged SDP blobs.
1497 void ConnectFakeSignalingForSdpOnly() {
1498 ConnectFakeSignaling();
1499 SetSignalIceCandidates(false);
1500 }
1501
deadbeef1dcb1642017-03-29 21:08:16 -07001502 void SetSignalingDelayMs(int delay_ms) {
1503 caller_->set_signaling_delay_ms(delay_ms);
1504 callee_->set_signaling_delay_ms(delay_ms);
1505 }
1506
Steve Antonede9ca52017-10-16 13:04:27 -07001507 void SetSignalIceCandidates(bool signal) {
1508 caller_->set_signal_ice_candidates(signal);
1509 callee_->set_signal_ice_candidates(signal);
1510 }
1511
deadbeef1dcb1642017-03-29 21:08:16 -07001512 // Messages may get lost on the unreliable DataChannel, so we send multiple
1513 // times to avoid test flakiness.
1514 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1515 const std::string& data,
1516 int retries) {
1517 for (int i = 0; i < retries; ++i) {
1518 dc->Send(DataBuffer(data));
1519 }
1520 }
1521
1522 rtc::Thread* network_thread() { return network_thread_.get(); }
1523
1524 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1525
1526 PeerConnectionWrapper* caller() { return caller_.get(); }
1527
1528 // Set the |caller_| to the |wrapper| passed in and return the
1529 // original |caller_|.
1530 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1531 PeerConnectionWrapper* wrapper) {
1532 PeerConnectionWrapper* old = caller_.release();
1533 caller_.reset(wrapper);
1534 return old;
1535 }
1536
1537 PeerConnectionWrapper* callee() { return callee_.get(); }
1538
1539 // Set the |callee_| to the |wrapper| passed in and return the
1540 // original |callee_|.
1541 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1542 PeerConnectionWrapper* wrapper) {
1543 PeerConnectionWrapper* old = callee_.release();
1544 callee_.reset(wrapper);
1545 return old;
1546 }
1547
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001548 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1549 network_thread()->Invoke<void>(
1550 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1551 caller()->port_allocator(), caller_flags));
1552 network_thread()->Invoke<void>(
1553 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1554 callee()->port_allocator(), callee_flags));
1555 }
1556
Steve Antonede9ca52017-10-16 13:04:27 -07001557 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1558
Seth Hampson2f0d7022018-02-20 11:54:42 -08001559 // Expects the provided number of new frames to be received within
1560 // kMaxWaitForFramesMs. The new expected frames are specified in
1561 // |media_expectations|. Returns false if any of the expectations were
1562 // not met.
1563 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
Harald Alvestrand6060df52020-08-11 09:54:02 +02001564 // Make sure there are no bogus tracks confusing the issue.
1565 caller()->RemoveUnusedVideoRenderers();
1566 callee()->RemoveUnusedVideoRenderers();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001567 // First initialize the expected frame counts based upon the current
1568 // frame count.
1569 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1570 if (media_expectations.caller_audio_expectation_ ==
1571 MediaExpectations::kExpectSomeFrames) {
1572 total_caller_audio_frames_expected +=
1573 media_expectations.caller_audio_frames_expected_;
1574 }
1575 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001576 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001577 if (media_expectations.caller_video_expectation_ ==
1578 MediaExpectations::kExpectSomeFrames) {
1579 total_caller_video_frames_expected +=
1580 media_expectations.caller_video_frames_expected_;
1581 }
1582 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1583 if (media_expectations.callee_audio_expectation_ ==
1584 MediaExpectations::kExpectSomeFrames) {
1585 total_callee_audio_frames_expected +=
1586 media_expectations.callee_audio_frames_expected_;
1587 }
1588 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001589 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001590 if (media_expectations.callee_video_expectation_ ==
1591 MediaExpectations::kExpectSomeFrames) {
1592 total_callee_video_frames_expected +=
1593 media_expectations.callee_video_frames_expected_;
1594 }
deadbeef1dcb1642017-03-29 21:08:16 -07001595
Seth Hampson2f0d7022018-02-20 11:54:42 -08001596 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001597 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001598 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001599 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001600 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001601 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001602 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001603 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001604 total_callee_video_frames_expected,
1605 kMaxWaitForFramesMs);
1606 bool expectations_correct =
1607 caller()->audio_frames_received() >=
1608 total_caller_audio_frames_expected &&
1609 caller()->min_video_frames_received_per_track() >=
1610 total_caller_video_frames_expected &&
1611 callee()->audio_frames_received() >=
1612 total_callee_audio_frames_expected &&
1613 callee()->min_video_frames_received_per_track() >=
1614 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001615
Seth Hampson2f0d7022018-02-20 11:54:42 -08001616 // After the combined wait, print out a more detailed message upon
1617 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001618 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001619 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001620 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001621 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001622 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001623 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001624 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001625 total_callee_video_frames_expected);
1626
1627 // We want to make sure nothing unexpected was received.
1628 if (media_expectations.caller_audio_expectation_ ==
1629 MediaExpectations::kExpectNoFrames) {
1630 EXPECT_EQ(caller()->audio_frames_received(),
1631 total_caller_audio_frames_expected);
1632 if (caller()->audio_frames_received() !=
1633 total_caller_audio_frames_expected) {
1634 expectations_correct = false;
1635 }
1636 }
1637 if (media_expectations.caller_video_expectation_ ==
1638 MediaExpectations::kExpectNoFrames) {
1639 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1640 total_caller_video_frames_expected);
1641 if (caller()->min_video_frames_received_per_track() !=
1642 total_caller_video_frames_expected) {
1643 expectations_correct = false;
1644 }
1645 }
1646 if (media_expectations.callee_audio_expectation_ ==
1647 MediaExpectations::kExpectNoFrames) {
1648 EXPECT_EQ(callee()->audio_frames_received(),
1649 total_callee_audio_frames_expected);
1650 if (callee()->audio_frames_received() !=
1651 total_callee_audio_frames_expected) {
1652 expectations_correct = false;
1653 }
1654 }
1655 if (media_expectations.callee_video_expectation_ ==
1656 MediaExpectations::kExpectNoFrames) {
1657 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1658 total_callee_video_frames_expected);
1659 if (callee()->min_video_frames_received_per_track() !=
1660 total_callee_video_frames_expected) {
1661 expectations_correct = false;
1662 }
1663 }
1664 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001665 }
1666
Steve Antond91969e2019-05-30 12:27:03 -07001667 void ClosePeerConnections() {
1668 caller()->pc()->Close();
1669 callee()->pc()->Close();
1670 }
1671
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001672 void TestNegotiatedCipherSuite(
1673 const PeerConnectionFactory::Options& caller_options,
1674 const PeerConnectionFactory::Options& callee_options,
1675 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001676 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1677 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001678 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001679 caller()->AddAudioVideoTracks();
1680 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001681 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001682 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001683 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001684 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001685 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01001686 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
1687 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1688 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001689 }
1690
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001691 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1692 bool remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001693 bool aes_ctr_enabled,
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001694 int expected_cipher_suite) {
1695 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001696 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1697 local_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001698 caller_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1699 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001700 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001701 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1702 remote_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001703 callee_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1704 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001705 TestNegotiatedCipherSuite(caller_options, callee_options,
1706 expected_cipher_suite);
1707 }
1708
Seth Hampson2f0d7022018-02-20 11:54:42 -08001709 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001710 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001711
deadbeef1dcb1642017-03-29 21:08:16 -07001712 private:
1713 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001714 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001715 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001716 // |network_thread_| and |worker_thread_| are used by both
1717 // |caller_| and |callee_| so they must be destroyed
1718 // later.
1719 std::unique_ptr<rtc::Thread> network_thread_;
1720 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001721 // The turn servers and turn customizers should be accessed & deleted on the
1722 // network thread to avoid a race with the socket read/write that occurs
1723 // on the network thread.
1724 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1725 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001726 std::unique_ptr<PeerConnectionWrapper> caller_;
1727 std::unique_ptr<PeerConnectionWrapper> callee_;
1728};
1729
Seth Hampson2f0d7022018-02-20 11:54:42 -08001730class PeerConnectionIntegrationTest
1731 : public PeerConnectionIntegrationBaseTest,
1732 public ::testing::WithParamInterface<SdpSemantics> {
1733 protected:
1734 PeerConnectionIntegrationTest()
1735 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1736};
1737
Yves Gerey100fe632020-01-17 19:15:53 +01001738// Fake clock must be set before threads are started to prevent race on
1739// Set/GetClockForTesting().
1740// To achieve that, multiple inheritance is used as a mixin pattern
1741// where order of construction is finely controlled.
1742// This also ensures peerconnection is closed before switching back to non-fake
1743// clock, avoiding other races and DCHECK failures such as in rtp_sender.cc.
1744class FakeClockForTest : public rtc::ScopedFakeClock {
1745 protected:
1746 FakeClockForTest() {
1747 // Some things use a time of "0" as a special value, so we need to start out
1748 // the fake clock at a nonzero time.
1749 // TODO(deadbeef): Fix this.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001750 AdvanceTime(webrtc::TimeDelta::Seconds(1));
Yves Gerey100fe632020-01-17 19:15:53 +01001751 }
1752
1753 // Explicit handle.
1754 ScopedFakeClock& FakeClock() { return *this; }
1755};
1756
1757// Ensure FakeClockForTest is constructed first (see class for rationale).
1758class PeerConnectionIntegrationTestWithFakeClock
1759 : public FakeClockForTest,
1760 public PeerConnectionIntegrationTest {};
1761
Seth Hampson2f0d7022018-02-20 11:54:42 -08001762class PeerConnectionIntegrationTestPlanB
1763 : public PeerConnectionIntegrationBaseTest {
1764 protected:
1765 PeerConnectionIntegrationTestPlanB()
1766 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1767};
1768
1769class PeerConnectionIntegrationTestUnifiedPlan
1770 : public PeerConnectionIntegrationBaseTest {
1771 protected:
1772 PeerConnectionIntegrationTestUnifiedPlan()
1773 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1774};
1775
deadbeef1dcb1642017-03-29 21:08:16 -07001776// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1777// includes testing that the callback is invoked if an observer is connected
1778// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001779TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001780 RtpReceiverObserverOnFirstPacketReceived) {
1781 ASSERT_TRUE(CreatePeerConnectionWrappers());
1782 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001783 caller()->AddAudioVideoTracks();
1784 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001785 // Start offer/answer exchange and wait for it to complete.
1786 caller()->CreateAndSetAndSignalOffer();
1787 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1788 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001789 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1790 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001791 // Wait for all "first packet received" callbacks to be fired.
1792 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001793 absl::c_all_of(caller()->rtp_receiver_observers(),
1794 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1795 return o->first_packet_received();
1796 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001797 kMaxWaitForFramesMs);
1798 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001799 absl::c_all_of(callee()->rtp_receiver_observers(),
1800 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1801 return o->first_packet_received();
1802 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001803 kMaxWaitForFramesMs);
1804 // If new observers are set after the first packet was already received, the
1805 // callback should still be invoked.
1806 caller()->ResetRtpReceiverObservers();
1807 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001808 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1809 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001810 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001811 absl::c_all_of(caller()->rtp_receiver_observers(),
1812 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1813 return o->first_packet_received();
1814 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001815 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001816 absl::c_all_of(callee()->rtp_receiver_observers(),
1817 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1818 return o->first_packet_received();
1819 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001820}
1821
1822class DummyDtmfObserver : public DtmfSenderObserverInterface {
1823 public:
1824 DummyDtmfObserver() : completed_(false) {}
1825
1826 // Implements DtmfSenderObserverInterface.
1827 void OnToneChange(const std::string& tone) override {
1828 tones_.push_back(tone);
1829 if (tone.empty()) {
1830 completed_ = true;
1831 }
1832 }
1833
1834 const std::vector<std::string>& tones() const { return tones_; }
1835 bool completed() const { return completed_; }
1836
1837 private:
1838 bool completed_;
1839 std::vector<std::string> tones_;
1840};
1841
1842// Assumes |sender| already has an audio track added and the offer/answer
1843// exchange is done.
1844void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1845 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001846 // We should be able to get a DTMF sender from the local sender.
1847 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1848 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1849 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001850 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001851 dtmf_sender->RegisterObserver(&observer);
1852
1853 // Test the DtmfSender object just created.
1854 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1855 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1856
1857 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1858 std::vector<std::string> tones = {"1", "a", ""};
1859 EXPECT_EQ(tones, observer.tones());
1860 dtmf_sender->UnregisterObserver();
1861 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1862}
1863
1864// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1865// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001866TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001867 ASSERT_TRUE(CreatePeerConnectionWrappers());
1868 ConnectFakeSignaling();
1869 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001870 caller()->AddAudioTrack();
1871 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001872 caller()->CreateAndSetAndSignalOffer();
1873 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001874 // DTLS must finish before the DTMF sender can be used reliably.
1875 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001876 TestDtmfFromSenderToReceiver(caller(), callee());
1877 TestDtmfFromSenderToReceiver(callee(), caller());
1878}
1879
1880// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1881// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001882TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001883 ASSERT_TRUE(CreatePeerConnectionWrappers());
1884 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001885
deadbeef1dcb1642017-03-29 21:08:16 -07001886 // Do normal offer/answer and wait for some frames to be received in each
1887 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001888 caller()->AddAudioVideoTracks();
1889 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001890 caller()->CreateAndSetAndSignalOffer();
1891 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001892 MediaExpectations media_expectations;
1893 media_expectations.ExpectBidirectionalAudioAndVideo();
1894 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001895 EXPECT_METRIC_LE(
1896 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1897 webrtc::kEnumCounterKeyProtocolDtls));
1898 EXPECT_METRIC_EQ(
1899 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1900 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001901}
1902
1903// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001904TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001905 PeerConnectionInterface::RTCConfiguration sdes_config;
1906 sdes_config.enable_dtls_srtp.emplace(false);
1907 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1908 ConnectFakeSignaling();
1909
1910 // Do normal offer/answer and wait for some frames to be received in each
1911 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001912 caller()->AddAudioVideoTracks();
1913 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001914 caller()->CreateAndSetAndSignalOffer();
1915 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001916 MediaExpectations media_expectations;
1917 media_expectations.ExpectBidirectionalAudioAndVideo();
1918 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001919 EXPECT_METRIC_LE(
1920 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1921 webrtc::kEnumCounterKeyProtocolSdes));
1922 EXPECT_METRIC_EQ(
1923 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1924 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001925}
1926
Steve Anton9a44b2d2019-07-12 12:58:30 -07001927// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1928// option to offer encrypted versions of all header extensions alongside the
1929// unencrypted versions.
1930TEST_P(PeerConnectionIntegrationTest,
1931 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1932 CryptoOptions crypto_options;
1933 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1934 PeerConnectionInterface::RTCConfiguration config;
1935 config.crypto_options = crypto_options;
1936 // Note: This allows offering >14 RTP header extensions.
1937 config.offer_extmap_allow_mixed = true;
1938 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1939 ConnectFakeSignaling();
1940
1941 // Do normal offer/answer and wait for some frames to be received in each
1942 // direction.
1943 caller()->AddAudioVideoTracks();
1944 callee()->AddAudioVideoTracks();
1945 caller()->CreateAndSetAndSignalOffer();
1946 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1947 MediaExpectations media_expectations;
1948 media_expectations.ExpectBidirectionalAudioAndVideo();
1949 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1950}
1951
Steve Anton8c0f7a72017-10-03 10:03:10 -07001952// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1953// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001954TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001955 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1956 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1957 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1958 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1959 return pc->GetRemoteAudioSSLCertificate();
1960 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001961 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1962 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1963 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1964 return pc->GetRemoteAudioSSLCertChain();
1965 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001966
1967 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1968 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1969
1970 // Configure each side with a known certificate so they can be compared later.
1971 PeerConnectionInterface::RTCConfiguration caller_config;
1972 caller_config.enable_dtls_srtp.emplace(true);
1973 caller_config.certificates.push_back(caller_cert);
1974 PeerConnectionInterface::RTCConfiguration callee_config;
1975 callee_config.enable_dtls_srtp.emplace(true);
1976 callee_config.certificates.push_back(callee_cert);
1977 ASSERT_TRUE(
1978 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1979 ConnectFakeSignaling();
1980
1981 // When first initialized, there should not be a remote SSL certificate (and
1982 // calling this method should not crash).
1983 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1984 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001985 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1986 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001987
Steve Anton15324772018-01-16 10:26:49 -08001988 caller()->AddAudioTrack();
1989 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001990 caller()->CreateAndSetAndSignalOffer();
1991 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1992 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1993
1994 // Once DTLS has been connected, each side should return the other's SSL
1995 // certificate when calling GetRemoteAudioSSLCertificate.
1996
1997 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1998 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001999 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07002000 caller_remote_cert->ToPEMString());
2001
2002 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
2003 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002004 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07002005 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08002006
2007 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
2008 ASSERT_TRUE(caller_remote_cert_chain);
2009 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
2010 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002011 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08002012 remote_cert->ToPEMString());
2013
2014 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
2015 ASSERT_TRUE(callee_remote_cert_chain);
2016 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
2017 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07002018 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08002019 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002020}
2021
deadbeef1dcb1642017-03-29 21:08:16 -07002022// This test sets up a call between two parties with a source resolution of
2023// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002024TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002025 Send1280By720ResolutionAndReceive16To9AspectRatio) {
2026 ASSERT_TRUE(CreatePeerConnectionWrappers());
2027 ConnectFakeSignaling();
2028
Niels Möller5c7efe72018-05-11 10:34:46 +02002029 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
2030 webrtc::FakePeriodicVideoSource::Config config;
2031 config.width = 1280;
2032 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02002033 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02002034 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
2035 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07002036
2037 // Do normal offer/answer and wait for at least one frame to be received in
2038 // each direction.
2039 caller()->CreateAndSetAndSignalOffer();
2040 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2041 callee()->min_video_frames_received_per_track() > 0,
2042 kMaxWaitForFramesMs);
2043
2044 // Check rendered aspect ratio.
2045 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
2046 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
2047 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
2048 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
2049}
2050
2051// This test sets up an one-way call, with media only from caller to
2052// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002053TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07002054 ASSERT_TRUE(CreatePeerConnectionWrappers());
2055 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002056 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002057 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002058 MediaExpectations media_expectations;
2059 media_expectations.CalleeExpectsSomeAudioAndVideo();
2060 media_expectations.CallerExpectsNoAudio();
2061 media_expectations.CallerExpectsNoVideo();
2062 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002063}
2064
Johannes Kron3e983682020-03-29 22:17:00 +02002065// Tests that send only works without the caller having a decoder factory and
2066// the callee having an encoder factory.
2067TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSendOnlyVideo) {
2068 ASSERT_TRUE(
2069 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/true));
2070 ConnectFakeSignaling();
2071 // Add one-directional video, from caller to callee.
2072 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2073 caller()->CreateLocalVideoTrack();
2074 caller()->AddTrack(caller_track);
2075 PeerConnectionInterface::RTCOfferAnswerOptions options;
2076 options.offer_to_receive_video = 0;
2077 caller()->SetOfferAnswerOptions(options);
2078 caller()->CreateAndSetAndSignalOffer();
2079 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2080 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
2081
2082 // Expect video to be received in one direction.
2083 MediaExpectations media_expectations;
2084 media_expectations.CallerExpectsNoVideo();
2085 media_expectations.CalleeExpectsSomeVideo();
2086
2087 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2088}
2089
2090// Tests that receive only works without the caller having an encoder factory
2091// and the callee having a decoder factory.
2092TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithReceiveOnlyVideo) {
2093 ASSERT_TRUE(
2094 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/false));
2095 ConnectFakeSignaling();
2096 // Add one-directional video, from callee to caller.
2097 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2098 callee()->CreateLocalVideoTrack();
2099 callee()->AddTrack(callee_track);
2100 PeerConnectionInterface::RTCOfferAnswerOptions options;
2101 options.offer_to_receive_video = 1;
2102 caller()->SetOfferAnswerOptions(options);
2103 caller()->CreateAndSetAndSignalOffer();
2104 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2105 ASSERT_EQ(caller()->pc()->GetReceivers().size(), 1u);
2106
2107 // Expect video to be received in one direction.
2108 MediaExpectations media_expectations;
2109 media_expectations.CallerExpectsSomeVideo();
2110 media_expectations.CalleeExpectsNoVideo();
2111
2112 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2113}
2114
2115TEST_P(PeerConnectionIntegrationTest,
2116 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2117 ASSERT_TRUE(CreatePeerConnectionWrappers());
2118 ConnectFakeSignaling();
2119 // Add one-directional video, from caller to callee.
2120 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2121 caller()->CreateLocalVideoTrack();
2122 caller()->AddTrack(caller_track);
2123 caller()->CreateAndSetAndSignalOffer();
2124 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2125
2126 // Add receive video.
2127 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2128 callee()->CreateLocalVideoTrack();
2129 callee()->AddTrack(callee_track);
2130 caller()->CreateAndSetAndSignalOffer();
2131 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2132
2133 // Ensure that video frames are received end-to-end.
2134 MediaExpectations media_expectations;
2135 media_expectations.ExpectBidirectionalVideo();
2136 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2137}
2138
2139TEST_P(PeerConnectionIntegrationTest,
2140 EndToEndCallAddSendVideoToReceiveOnlyCall) {
2141 ASSERT_TRUE(CreatePeerConnectionWrappers());
2142 ConnectFakeSignaling();
2143 // Add one-directional video, from callee to caller.
2144 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2145 callee()->CreateLocalVideoTrack();
2146 callee()->AddTrack(callee_track);
2147 caller()->CreateAndSetAndSignalOffer();
2148 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2149
2150 // Add send video.
2151 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2152 caller()->CreateLocalVideoTrack();
2153 caller()->AddTrack(caller_track);
2154 caller()->CreateAndSetAndSignalOffer();
2155 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2156
2157 // Expect video to be received in one direction.
2158 MediaExpectations media_expectations;
2159 media_expectations.ExpectBidirectionalVideo();
2160 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2161}
2162
2163TEST_P(PeerConnectionIntegrationTest,
2164 EndToEndCallRemoveReceiveVideoFromSendReceiveCall) {
2165 ASSERT_TRUE(CreatePeerConnectionWrappers());
2166 ConnectFakeSignaling();
2167 // Add send video, from caller to callee.
2168 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2169 caller()->CreateLocalVideoTrack();
2170 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2171 caller()->AddTrack(caller_track);
2172 // Add receive video, from callee to caller.
2173 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2174 callee()->CreateLocalVideoTrack();
2175
2176 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2177 callee()->AddTrack(callee_track);
2178 caller()->CreateAndSetAndSignalOffer();
2179 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2180
2181 // Remove receive video (i.e., callee sender track).
2182 callee()->pc()->RemoveTrack(callee_sender);
2183
2184 caller()->CreateAndSetAndSignalOffer();
2185 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2186
2187 // Expect one-directional video.
2188 MediaExpectations media_expectations;
2189 media_expectations.CallerExpectsNoVideo();
2190 media_expectations.CalleeExpectsSomeVideo();
2191
2192 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2193}
2194
2195TEST_P(PeerConnectionIntegrationTest,
2196 EndToEndCallRemoveSendVideoFromSendReceiveCall) {
2197 ASSERT_TRUE(CreatePeerConnectionWrappers());
2198 ConnectFakeSignaling();
2199 // Add send video, from caller to callee.
2200 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2201 caller()->CreateLocalVideoTrack();
2202 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2203 caller()->AddTrack(caller_track);
2204 // Add receive video, from callee to caller.
2205 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2206 callee()->CreateLocalVideoTrack();
2207
2208 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2209 callee()->AddTrack(callee_track);
2210 caller()->CreateAndSetAndSignalOffer();
2211 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2212
2213 // Remove send video (i.e., caller sender track).
2214 caller()->pc()->RemoveTrack(caller_sender);
2215
2216 caller()->CreateAndSetAndSignalOffer();
2217 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2218
2219 // Expect one-directional video.
2220 MediaExpectations media_expectations;
2221 media_expectations.CalleeExpectsNoVideo();
2222 media_expectations.CallerExpectsSomeVideo();
2223
2224 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2225}
2226
deadbeef1dcb1642017-03-29 21:08:16 -07002227// This test sets up a audio call initially, with the callee rejecting video
2228// initially. Then later the callee decides to upgrade to audio/video, and
2229// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002230TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07002231 ASSERT_TRUE(CreatePeerConnectionWrappers());
2232 ConnectFakeSignaling();
2233 // Initially, offer an audio/video stream from the caller, but refuse to
2234 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08002235 caller()->AddAudioVideoTracks();
2236 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002237 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2238 PeerConnectionInterface::RTCOfferAnswerOptions options;
2239 options.offer_to_receive_video = 0;
2240 callee()->SetOfferAnswerOptions(options);
2241 } else {
2242 callee()->SetRemoteOfferHandler([this] {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002243 callee()
2244 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2245 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002246 });
2247 }
deadbeef1dcb1642017-03-29 21:08:16 -07002248 // Do offer/answer and make sure audio is still received end-to-end.
2249 caller()->CreateAndSetAndSignalOffer();
2250 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002251 {
2252 MediaExpectations media_expectations;
2253 media_expectations.ExpectBidirectionalAudio();
2254 media_expectations.ExpectNoVideo();
2255 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2256 }
deadbeef1dcb1642017-03-29 21:08:16 -07002257 // Sanity check that the callee's description has a rejected video section.
2258 ASSERT_NE(nullptr, callee()->pc()->local_description());
2259 const ContentInfo* callee_video_content =
2260 GetFirstVideoContent(callee()->pc()->local_description()->description());
2261 ASSERT_NE(nullptr, callee_video_content);
2262 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002263
deadbeef1dcb1642017-03-29 21:08:16 -07002264 // Now negotiate with video and ensure negotiation succeeds, with video
2265 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002266 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002267 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2268 PeerConnectionInterface::RTCOfferAnswerOptions options;
2269 options.offer_to_receive_video = 1;
2270 callee()->SetOfferAnswerOptions(options);
2271 } else {
2272 callee()->SetRemoteOfferHandler(nullptr);
2273 caller()->SetRemoteOfferHandler([this] {
2274 // The caller creates a new transceiver to receive video on when receiving
2275 // the offer, but by default it is send only.
2276 auto transceivers = caller()->pc()->GetTransceivers();
Harald Alvestrand6060df52020-08-11 09:54:02 +02002277 ASSERT_EQ(2U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002278 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
Harald Alvestrand6060df52020-08-11 09:54:02 +02002279 transceivers[1]->receiver()->media_type());
2280 transceivers[1]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2281 transceivers[1]->SetDirectionWithError(
2282 RtpTransceiverDirection::kSendRecv);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002283 });
2284 }
deadbeef1dcb1642017-03-29 21:08:16 -07002285 callee()->CreateAndSetAndSignalOffer();
2286 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002287 {
2288 // Expect additional audio frames to be received after the upgrade.
2289 MediaExpectations media_expectations;
2290 media_expectations.ExpectBidirectionalAudioAndVideo();
2291 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2292 }
deadbeef1dcb1642017-03-29 21:08:16 -07002293}
2294
deadbeef4389b4d2017-09-07 09:07:36 -07002295// Simpler than the above test; just add an audio track to an established
2296// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002297TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002298 ASSERT_TRUE(CreatePeerConnectionWrappers());
2299 ConnectFakeSignaling();
2300 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002301 caller()->AddVideoTrack();
2302 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002303 caller()->CreateAndSetAndSignalOffer();
2304 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2305 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002306 caller()->AddAudioTrack();
2307 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002308 caller()->CreateAndSetAndSignalOffer();
2309 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2310 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002311 MediaExpectations media_expectations;
2312 media_expectations.ExpectBidirectionalAudioAndVideo();
2313 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002314}
2315
deadbeef1dcb1642017-03-29 21:08:16 -07002316// This test sets up a call that's transferred to a new caller with a different
2317// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002318TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002319 ASSERT_TRUE(CreatePeerConnectionWrappers());
2320 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002321 caller()->AddAudioVideoTracks();
2322 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002323 caller()->CreateAndSetAndSignalOffer();
2324 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2325
2326 // Keep the original peer around which will still send packets to the
2327 // receiving client. These SRTP packets will be dropped.
2328 std::unique_ptr<PeerConnectionWrapper> original_peer(
2329 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002330 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002331 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2332 // directly above.
2333 original_peer->pc()->Close();
2334
2335 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002336 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002337 caller()->CreateAndSetAndSignalOffer();
2338 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2339 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002340 MediaExpectations media_expectations;
2341 media_expectations.ExpectBidirectionalAudioAndVideo();
2342 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002343}
2344
2345// This test sets up a call that's transferred to a new callee with a different
2346// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002347TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002348 ASSERT_TRUE(CreatePeerConnectionWrappers());
2349 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002350 caller()->AddAudioVideoTracks();
2351 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002352 caller()->CreateAndSetAndSignalOffer();
2353 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2354
2355 // Keep the original peer around which will still send packets to the
2356 // receiving client. These SRTP packets will be dropped.
2357 std::unique_ptr<PeerConnectionWrapper> original_peer(
2358 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002359 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002360 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2361 // directly above.
2362 original_peer->pc()->Close();
2363
2364 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002365 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002366 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2367 caller()->CreateAndSetAndSignalOffer();
2368 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2369 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002370 MediaExpectations media_expectations;
2371 media_expectations.ExpectBidirectionalAudioAndVideo();
2372 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002373}
2374
2375// This test sets up a non-bundled call and negotiates bundling at the same
2376// time as starting an ICE restart. When bundling is in effect in the restart,
2377// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002378TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002379 ASSERT_TRUE(CreatePeerConnectionWrappers());
2380 ConnectFakeSignaling();
2381
Steve Anton15324772018-01-16 10:26:49 -08002382 caller()->AddAudioVideoTracks();
2383 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002384 // Remove the bundle group from the SDP received by the callee.
2385 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2386 desc->RemoveGroupByName("BUNDLE");
2387 });
2388 caller()->CreateAndSetAndSignalOffer();
2389 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002390 {
2391 MediaExpectations media_expectations;
2392 media_expectations.ExpectBidirectionalAudioAndVideo();
2393 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2394 }
deadbeef1dcb1642017-03-29 21:08:16 -07002395 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2396 callee()->SetReceivedSdpMunger(nullptr);
2397 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2398 caller()->CreateAndSetAndSignalOffer();
2399 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2400
2401 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002402 {
2403 MediaExpectations media_expectations;
2404 media_expectations.ExpectBidirectionalAudioAndVideo();
2405 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2406 }
deadbeef1dcb1642017-03-29 21:08:16 -07002407}
2408
2409// Test CVO (Coordination of Video Orientation). If a video source is rotated
2410// and both peers support the CVO RTP header extension, the actual video frames
2411// don't need to be encoded in different resolutions, since the rotation is
2412// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002413TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002414 ASSERT_TRUE(CreatePeerConnectionWrappers());
2415 ConnectFakeSignaling();
2416 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002417 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002418 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002419 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002420 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2421
2422 // Wait for video frames to be received by both sides.
2423 caller()->CreateAndSetAndSignalOffer();
2424 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2425 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2426 callee()->min_video_frames_received_per_track() > 0,
2427 kMaxWaitForFramesMs);
2428
2429 // Ensure that the aspect ratio is unmodified.
2430 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2431 // not just assumed.
2432 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2433 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2434 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2435 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2436 // Ensure that the CVO bits were surfaced to the renderer.
2437 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2438 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2439}
2440
2441// Test that when the CVO extension isn't supported, video is rotated the
2442// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002443TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002444 ASSERT_TRUE(CreatePeerConnectionWrappers());
2445 ConnectFakeSignaling();
2446 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002447 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002448 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002449 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002450 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2451
2452 // Remove the CVO extension from the offered SDP.
2453 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2454 cricket::VideoContentDescription* video =
2455 GetFirstVideoContentDescription(desc);
2456 video->ClearRtpHeaderExtensions();
2457 });
2458 // Wait for video frames to be received by both sides.
2459 caller()->CreateAndSetAndSignalOffer();
2460 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2461 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2462 callee()->min_video_frames_received_per_track() > 0,
2463 kMaxWaitForFramesMs);
2464
2465 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2466 // rotation.
2467 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2468 // not just assumed.
2469 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2470 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2471 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2472 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2473 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2474 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2475 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2476}
2477
deadbeef1dcb1642017-03-29 21:08:16 -07002478// Test that if the answerer rejects the audio m= section, no audio is sent or
2479// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002480TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002481 ASSERT_TRUE(CreatePeerConnectionWrappers());
2482 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002483 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002484 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2485 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2486 // it will reject the audio m= section completely.
2487 PeerConnectionInterface::RTCOfferAnswerOptions options;
2488 options.offer_to_receive_audio = 0;
2489 callee()->SetOfferAnswerOptions(options);
2490 } else {
2491 // Stopping the audio RtpTransceiver will cause the media section to be
2492 // rejected in the answer.
2493 callee()->SetRemoteOfferHandler([this] {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002494 callee()
2495 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2496 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002497 });
2498 }
Steve Anton15324772018-01-16 10:26:49 -08002499 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002500 // Do offer/answer and wait for successful end-to-end video frames.
2501 caller()->CreateAndSetAndSignalOffer();
2502 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002503 MediaExpectations media_expectations;
2504 media_expectations.ExpectBidirectionalVideo();
2505 media_expectations.ExpectNoAudio();
2506 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2507
deadbeef1dcb1642017-03-29 21:08:16 -07002508 // Sanity check that the callee's description has a rejected audio section.
2509 ASSERT_NE(nullptr, callee()->pc()->local_description());
2510 const ContentInfo* callee_audio_content =
2511 GetFirstAudioContent(callee()->pc()->local_description()->description());
2512 ASSERT_NE(nullptr, callee_audio_content);
2513 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002514 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002515 // The caller's transceiver should have stopped after receiving the answer,
2516 // and thus no longer listed in transceivers.
2517 EXPECT_EQ(nullptr,
2518 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO));
Seth Hampson2f0d7022018-02-20 11:54:42 -08002519 }
deadbeef1dcb1642017-03-29 21:08:16 -07002520}
2521
2522// Test that if the answerer rejects the video m= section, no video is sent or
2523// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002524TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002525 ASSERT_TRUE(CreatePeerConnectionWrappers());
2526 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002527 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002528 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2529 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2530 // it will reject the video m= section completely.
2531 PeerConnectionInterface::RTCOfferAnswerOptions options;
2532 options.offer_to_receive_video = 0;
2533 callee()->SetOfferAnswerOptions(options);
2534 } else {
2535 // Stopping the video RtpTransceiver will cause the media section to be
2536 // rejected in the answer.
2537 callee()->SetRemoteOfferHandler([this] {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002538 callee()
2539 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2540 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002541 });
2542 }
Steve Anton15324772018-01-16 10:26:49 -08002543 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002544 // Do offer/answer and wait for successful end-to-end audio frames.
2545 caller()->CreateAndSetAndSignalOffer();
2546 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002547 MediaExpectations media_expectations;
2548 media_expectations.ExpectBidirectionalAudio();
2549 media_expectations.ExpectNoVideo();
2550 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2551
deadbeef1dcb1642017-03-29 21:08:16 -07002552 // Sanity check that the callee's description has a rejected video section.
2553 ASSERT_NE(nullptr, callee()->pc()->local_description());
2554 const ContentInfo* callee_video_content =
2555 GetFirstVideoContent(callee()->pc()->local_description()->description());
2556 ASSERT_NE(nullptr, callee_video_content);
2557 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002558 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002559 // The caller's transceiver should have stopped after receiving the answer,
2560 // and thus is no longer present.
2561 EXPECT_EQ(nullptr,
2562 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO));
Seth Hampson2f0d7022018-02-20 11:54:42 -08002563 }
deadbeef1dcb1642017-03-29 21:08:16 -07002564}
2565
2566// Test that if the answerer rejects both audio and video m= sections, nothing
2567// bad happens.
2568// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2569// test anything but the fact that negotiation succeeds, which doesn't mean
2570// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002571TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002572 ASSERT_TRUE(CreatePeerConnectionWrappers());
2573 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002574 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002575 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2576 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2577 // will reject both audio and video m= sections.
2578 PeerConnectionInterface::RTCOfferAnswerOptions options;
2579 options.offer_to_receive_audio = 0;
2580 options.offer_to_receive_video = 0;
2581 callee()->SetOfferAnswerOptions(options);
2582 } else {
2583 callee()->SetRemoteOfferHandler([this] {
2584 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002585 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002586 transceiver->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002587 }
2588 });
2589 }
deadbeef1dcb1642017-03-29 21:08:16 -07002590 // Do offer/answer and wait for stable signaling state.
2591 caller()->CreateAndSetAndSignalOffer();
2592 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002593
deadbeef1dcb1642017-03-29 21:08:16 -07002594 // Sanity check that the callee's description has rejected m= sections.
2595 ASSERT_NE(nullptr, callee()->pc()->local_description());
2596 const ContentInfo* callee_audio_content =
2597 GetFirstAudioContent(callee()->pc()->local_description()->description());
2598 ASSERT_NE(nullptr, callee_audio_content);
2599 EXPECT_TRUE(callee_audio_content->rejected);
2600 const ContentInfo* callee_video_content =
2601 GetFirstVideoContent(callee()->pc()->local_description()->description());
2602 ASSERT_NE(nullptr, callee_video_content);
2603 EXPECT_TRUE(callee_video_content->rejected);
2604}
2605
2606// This test sets up an audio and video call between two parties. After the
2607// call runs for a while, the caller sends an updated offer with video being
2608// rejected. Once the re-negotiation is done, the video flow should stop and
2609// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002610TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002611 ASSERT_TRUE(CreatePeerConnectionWrappers());
2612 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002613 caller()->AddAudioVideoTracks();
2614 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002615 caller()->CreateAndSetAndSignalOffer();
2616 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002617 {
2618 MediaExpectations media_expectations;
2619 media_expectations.ExpectBidirectionalAudioAndVideo();
2620 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2621 }
deadbeef1dcb1642017-03-29 21:08:16 -07002622 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002623 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2624 caller()->SetGeneratedSdpMunger(
2625 [](cricket::SessionDescription* description) {
2626 for (cricket::ContentInfo& content : description->contents()) {
2627 if (cricket::IsVideoContent(&content)) {
2628 content.rejected = true;
2629 }
2630 }
2631 });
2632 } else {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002633 caller()
2634 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2635 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002636 }
deadbeef1dcb1642017-03-29 21:08:16 -07002637 caller()->CreateAndSetAndSignalOffer();
2638 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2639
2640 // Sanity check that the caller's description has a rejected video section.
2641 ASSERT_NE(nullptr, caller()->pc()->local_description());
2642 const ContentInfo* caller_video_content =
2643 GetFirstVideoContent(caller()->pc()->local_description()->description());
2644 ASSERT_NE(nullptr, caller_video_content);
2645 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002646 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002647 {
2648 MediaExpectations media_expectations;
2649 media_expectations.ExpectBidirectionalAudio();
2650 media_expectations.ExpectNoVideo();
2651 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2652 }
deadbeef1dcb1642017-03-29 21:08:16 -07002653}
2654
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002655// Do one offer/answer with audio, another that disables it (rejecting the m=
2656// section), and another that re-enables it. Regression test for:
2657// bugs.webrtc.org/6023
2658TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2659 ASSERT_TRUE(CreatePeerConnectionWrappers());
2660 ConnectFakeSignaling();
2661
2662 // Add audio track, do normal offer/answer.
2663 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2664 caller()->CreateLocalAudioTrack();
2665 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2666 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2667 caller()->CreateAndSetAndSignalOffer();
2668 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2669
2670 // Remove audio track, and set offer_to_receive_audio to false to cause the
2671 // m= section to be completely disabled, not just "recvonly".
2672 caller()->pc()->RemoveTrack(sender);
2673 PeerConnectionInterface::RTCOfferAnswerOptions options;
2674 options.offer_to_receive_audio = 0;
2675 caller()->SetOfferAnswerOptions(options);
2676 caller()->CreateAndSetAndSignalOffer();
2677 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2678
2679 // Add the audio track again, expecting negotiation to succeed and frames to
2680 // flow.
2681 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2682 options.offer_to_receive_audio = 1;
2683 caller()->SetOfferAnswerOptions(options);
2684 caller()->CreateAndSetAndSignalOffer();
2685 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2686
2687 MediaExpectations media_expectations;
2688 media_expectations.CalleeExpectsSomeAudio();
2689 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2690}
2691
deadbeef1dcb1642017-03-29 21:08:16 -07002692// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2693// is needed to support legacy endpoints.
2694// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2695// add a test for an end-to-end test without MID signaling either (basically,
2696// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002697TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002698 ASSERT_TRUE(CreatePeerConnectionWrappers());
2699 ConnectFakeSignaling();
2700 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002701 caller()->AddAudioVideoTracks();
2702 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002703 // Remove SSRCs and MSIDs from the received offer SDP.
2704 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002705 caller()->CreateAndSetAndSignalOffer();
2706 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002707 MediaExpectations media_expectations;
2708 media_expectations.ExpectBidirectionalAudioAndVideo();
2709 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002710}
2711
Seth Hampson5897a6e2018-04-03 11:16:33 -07002712// Basic end-to-end test, without SSRC signaling. This means that the track
2713// was created properly and frames are delivered when the MSIDs are communicated
2714// with a=msid lines and no a=ssrc lines.
2715TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2716 EndToEndCallWithoutSsrcSignaling) {
2717 const char kStreamId[] = "streamId";
2718 ASSERT_TRUE(CreatePeerConnectionWrappers());
2719 ConnectFakeSignaling();
2720 // Add just audio tracks.
2721 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2722 callee()->AddAudioTrack();
2723
2724 // Remove SSRCs from the received offer SDP.
2725 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2726 caller()->CreateAndSetAndSignalOffer();
2727 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2728 MediaExpectations media_expectations;
2729 media_expectations.ExpectBidirectionalAudio();
2730 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2731}
2732
Johannes Kron3e983682020-03-29 22:17:00 +02002733TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2734 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2735 ASSERT_TRUE(CreatePeerConnectionWrappers());
2736 ConnectFakeSignaling();
2737 // Add one-directional video, from caller to callee.
2738 rtc::scoped_refptr<webrtc::VideoTrackInterface> track =
2739 caller()->CreateLocalVideoTrack();
2740
2741 RtpTransceiverInit video_transceiver_init;
2742 video_transceiver_init.stream_ids = {"video1"};
2743 video_transceiver_init.direction = RtpTransceiverDirection::kSendOnly;
2744 auto video_sender =
2745 caller()->pc()->AddTransceiver(track, video_transceiver_init).MoveValue();
2746 caller()->CreateAndSetAndSignalOffer();
2747 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2748
2749 // Add receive direction.
Harald Alvestrand6060df52020-08-11 09:54:02 +02002750 video_sender->SetDirectionWithError(RtpTransceiverDirection::kSendRecv);
Johannes Kron3e983682020-03-29 22:17:00 +02002751
2752 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2753 callee()->CreateLocalVideoTrack();
2754
2755 callee()->AddTrack(callee_track);
2756 caller()->CreateAndSetAndSignalOffer();
2757 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2758 // Ensure that video frames are received end-to-end.
2759 MediaExpectations media_expectations;
2760 media_expectations.ExpectBidirectionalVideo();
2761 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2762}
2763
Steve Antondf527fd2018-04-27 15:52:03 -07002764// Tests that video flows between multiple video tracks when SSRCs are not
2765// signaled. This exercises the MID RTP header extension which is needed to
2766// demux the incoming video tracks.
2767TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2768 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2769 ASSERT_TRUE(CreatePeerConnectionWrappers());
2770 ConnectFakeSignaling();
2771 caller()->AddVideoTrack();
2772 caller()->AddVideoTrack();
2773 callee()->AddVideoTrack();
2774 callee()->AddVideoTrack();
2775
2776 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2777 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2778 caller()->CreateAndSetAndSignalOffer();
2779 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2780 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2781 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2782
2783 // Expect video to be received in both directions on both tracks.
2784 MediaExpectations media_expectations;
2785 media_expectations.ExpectBidirectionalVideo();
2786 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2787}
2788
Henrik Boström5b147782018-12-04 11:25:05 +01002789TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2790 ASSERT_TRUE(CreatePeerConnectionWrappers());
2791 ConnectFakeSignaling();
2792 caller()->AddAudioTrack();
2793 caller()->AddVideoTrack();
2794 caller()->CreateAndSetAndSignalOffer();
2795 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2796 auto callee_receivers = callee()->pc()->GetReceivers();
2797 ASSERT_EQ(2u, callee_receivers.size());
2798 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2799 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2800}
2801
2802TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2803 ASSERT_TRUE(CreatePeerConnectionWrappers());
2804 ConnectFakeSignaling();
2805 caller()->AddAudioTrack();
2806 caller()->AddVideoTrack();
2807 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2808 caller()->CreateAndSetAndSignalOffer();
2809 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2810 auto callee_receivers = callee()->pc()->GetReceivers();
2811 ASSERT_EQ(2u, callee_receivers.size());
2812 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2813 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2814 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2815 callee_receivers[1]->stream_ids()[0]);
2816 EXPECT_EQ(callee_receivers[0]->streams()[0],
2817 callee_receivers[1]->streams()[0]);
2818}
2819
deadbeef1dcb1642017-03-29 21:08:16 -07002820// Test that if two video tracks are sent (from caller to callee, in this test),
2821// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002822TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002823 ASSERT_TRUE(CreatePeerConnectionWrappers());
2824 ConnectFakeSignaling();
2825 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002826 caller()->AddAudioVideoTracks();
2827 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002828 caller()->CreateAndSetAndSignalOffer();
2829 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002830 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002831
2832 MediaExpectations media_expectations;
2833 media_expectations.CalleeExpectsSomeAudioAndVideo();
2834 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002835}
2836
2837static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2838 bool first = true;
2839 for (cricket::ContentInfo& content : desc->contents()) {
2840 if (first) {
2841 first = false;
2842 continue;
2843 }
2844 content.bundle_only = true;
2845 }
2846 first = true;
2847 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2848 if (first) {
2849 first = false;
2850 continue;
2851 }
2852 transport.description.ice_ufrag.clear();
2853 transport.description.ice_pwd.clear();
2854 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2855 transport.description.identity_fingerprint.reset(nullptr);
2856 }
2857}
2858
2859// Test that if applying a true "max bundle" offer, which uses ports of 0,
2860// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2861// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2862// successfully and media flows.
2863// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2864// TODO(deadbeef): Won't need this test once we start generating actual
2865// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002866TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002867 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2868 ASSERT_TRUE(CreatePeerConnectionWrappers());
2869 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002870 caller()->AddAudioVideoTracks();
2871 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002872 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2873 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2874 // but the first m= section.
2875 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2876 caller()->CreateAndSetAndSignalOffer();
2877 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002878 MediaExpectations media_expectations;
2879 media_expectations.ExpectBidirectionalAudioAndVideo();
2880 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002881}
2882
2883// Test that we can receive the audio output level from a remote audio track.
2884// TODO(deadbeef): Use a fake audio source and verify that the output level is
2885// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002886TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002887 ASSERT_TRUE(CreatePeerConnectionWrappers());
2888 ConnectFakeSignaling();
2889 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002890 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002891 caller()->CreateAndSetAndSignalOffer();
2892 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2893
2894 // Get the audio output level stats. Note that the level is not available
2895 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002896 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002897 kMaxWaitForFramesMs);
2898}
2899
2900// Test that an audio input level is reported.
2901// TODO(deadbeef): Use a fake audio source and verify that the input level is
2902// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002903TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002904 ASSERT_TRUE(CreatePeerConnectionWrappers());
2905 ConnectFakeSignaling();
2906 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002907 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002908 caller()->CreateAndSetAndSignalOffer();
2909 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2910
2911 // Get the audio input level stats. The level should be available very
2912 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002913 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002914 kMaxWaitForStatsMs);
2915}
2916
2917// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002918TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002919 ASSERT_TRUE(CreatePeerConnectionWrappers());
2920 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002921 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002922 // Do offer/answer, wait for the callee to receive some frames.
2923 caller()->CreateAndSetAndSignalOffer();
2924 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002925
2926 MediaExpectations media_expectations;
2927 media_expectations.CalleeExpectsSomeAudioAndVideo();
2928 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002929
2930 // Get a handle to the remote tracks created, so they can be used as GetStats
2931 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002932 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002933 // We received frames, so we definitely should have nonzero "received bytes"
2934 // stats at this point.
2935 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2936 0);
2937 }
deadbeef1dcb1642017-03-29 21:08:16 -07002938}
2939
2940// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002941TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002942 ASSERT_TRUE(CreatePeerConnectionWrappers());
2943 ConnectFakeSignaling();
2944 auto audio_track = caller()->CreateLocalAudioTrack();
2945 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002946 caller()->AddTrack(audio_track);
2947 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002948 // Do offer/answer, wait for the callee to receive some frames.
2949 caller()->CreateAndSetAndSignalOffer();
2950 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002951 MediaExpectations media_expectations;
2952 media_expectations.CalleeExpectsSomeAudioAndVideo();
2953 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002954
2955 // The callee received frames, so we definitely should have nonzero "sent
2956 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002957 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2958 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2959}
2960
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002961// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002962TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002963 ASSERT_TRUE(CreatePeerConnectionWrappers());
2964 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002965 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002966
Steve Anton15324772018-01-16 10:26:49 -08002967 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002968
2969 // Do offer/answer, wait for the callee to receive some frames.
2970 caller()->CreateAndSetAndSignalOffer();
2971 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2972
2973 // Get the remote audio track created on the receiver, so they can be used as
2974 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002975 auto receivers = callee()->pc()->GetReceivers();
2976 ASSERT_EQ(1u, receivers.size());
2977 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002978
2979 // Get the audio output level stats. Note that the level is not available
2980 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002981 EXPECT_TRUE_WAIT(
2982 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2983 0,
2984 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002985}
2986
Steve Antona41959e2018-11-28 11:15:33 -08002987// Test that the track ID is associated with all local and remote SSRC stats
2988// using the old GetStats() and more than 1 audio and more than 1 video track.
2989// This is a regression test for crbug.com/906988
2990TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2991 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2992 ASSERT_TRUE(CreatePeerConnectionWrappers());
2993 ConnectFakeSignaling();
2994 auto audio_sender_1 = caller()->AddAudioTrack();
2995 auto video_sender_1 = caller()->AddVideoTrack();
2996 auto audio_sender_2 = caller()->AddAudioTrack();
2997 auto video_sender_2 = caller()->AddVideoTrack();
2998 caller()->CreateAndSetAndSignalOffer();
2999 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3000
3001 MediaExpectations media_expectations;
3002 media_expectations.CalleeExpectsSomeAudioAndVideo();
3003 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3004
3005 std::vector<std::string> track_ids = {
3006 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3007 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3008
3009 auto caller_stats = caller()->OldGetStats();
3010 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3011 auto callee_stats = callee()->OldGetStats();
3012 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3013}
3014
Steve Antonffa6ce42018-11-30 09:26:08 -08003015// Test that the new GetStats() returns stats for all outgoing/incoming streams
3016// with the correct track IDs if there are more than one audio and more than one
3017// video senders/receivers.
3018TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
3019 ASSERT_TRUE(CreatePeerConnectionWrappers());
3020 ConnectFakeSignaling();
3021 auto audio_sender_1 = caller()->AddAudioTrack();
3022 auto video_sender_1 = caller()->AddVideoTrack();
3023 auto audio_sender_2 = caller()->AddAudioTrack();
3024 auto video_sender_2 = caller()->AddVideoTrack();
3025 caller()->CreateAndSetAndSignalOffer();
3026 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3027
3028 MediaExpectations media_expectations;
3029 media_expectations.CalleeExpectsSomeAudioAndVideo();
3030 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3031
3032 std::vector<std::string> track_ids = {
3033 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3034 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3035
3036 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
3037 caller()->NewGetStats();
3038 ASSERT_TRUE(caller_report);
3039 auto outbound_stream_stats =
3040 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
Henrik Boströma0ff50c2020-05-05 15:54:46 +02003041 ASSERT_EQ(outbound_stream_stats.size(), 4u);
Steve Antonffa6ce42018-11-30 09:26:08 -08003042 std::vector<std::string> outbound_track_ids;
3043 for (const auto& stat : outbound_stream_stats) {
3044 ASSERT_TRUE(stat->bytes_sent.is_defined());
3045 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02003046 if (*stat->kind == "video") {
3047 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
3048 EXPECT_GT(*stat->key_frames_encoded, 0u);
3049 ASSERT_TRUE(stat->frames_encoded.is_defined());
3050 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
3051 }
Steve Antonffa6ce42018-11-30 09:26:08 -08003052 ASSERT_TRUE(stat->track_id.is_defined());
3053 const auto* track_stat =
3054 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3055 ASSERT_TRUE(track_stat);
3056 outbound_track_ids.push_back(*track_stat->track_identifier);
3057 }
3058 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
3059
3060 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
3061 callee()->NewGetStats();
3062 ASSERT_TRUE(callee_report);
3063 auto inbound_stream_stats =
3064 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3065 ASSERT_EQ(4u, inbound_stream_stats.size());
3066 std::vector<std::string> inbound_track_ids;
3067 for (const auto& stat : inbound_stream_stats) {
3068 ASSERT_TRUE(stat->bytes_received.is_defined());
3069 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02003070 if (*stat->kind == "video") {
3071 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
3072 EXPECT_GT(*stat->key_frames_decoded, 0u);
3073 ASSERT_TRUE(stat->frames_decoded.is_defined());
3074 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
3075 }
Steve Antonffa6ce42018-11-30 09:26:08 -08003076 ASSERT_TRUE(stat->track_id.is_defined());
3077 const auto* track_stat =
3078 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3079 ASSERT_TRUE(track_stat);
3080 inbound_track_ids.push_back(*track_stat->track_identifier);
3081 }
3082 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
3083}
3084
3085// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07003086// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
3087// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003088TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07003089 GetStatsForUnsignaledStreamWithNewStatsApi) {
3090 ASSERT_TRUE(CreatePeerConnectionWrappers());
3091 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003092 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07003093 // Remove SSRCs and MSIDs from the received offer SDP.
3094 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3095 caller()->CreateAndSetAndSignalOffer();
3096 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003097 MediaExpectations media_expectations;
3098 media_expectations.CalleeExpectsSomeAudio(1);
3099 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07003100
3101 // We received a frame, so we should have nonzero "bytes received" stats for
3102 // the unsignaled stream, if stats are working for it.
3103 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3104 callee()->NewGetStats();
3105 ASSERT_NE(nullptr, report);
3106 auto inbound_stream_stats =
3107 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3108 ASSERT_EQ(1U, inbound_stream_stats.size());
3109 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
3110 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07003111 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
3112}
3113
Taylor Brandstettera4653442018-06-19 09:44:26 -07003114// Same as above but for the legacy stats implementation.
3115TEST_P(PeerConnectionIntegrationTest,
3116 GetStatsForUnsignaledStreamWithOldStatsApi) {
3117 ASSERT_TRUE(CreatePeerConnectionWrappers());
3118 ConnectFakeSignaling();
3119 caller()->AddAudioTrack();
3120 // Remove SSRCs and MSIDs from the received offer SDP.
3121 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3122 caller()->CreateAndSetAndSignalOffer();
3123 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3124
3125 // Note that, since the old stats implementation associates SSRCs with tracks
3126 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
3127 // associated track ID. So we can't use the track "selector" argument.
3128 //
3129 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
3130 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003131 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07003132 kDefaultTimeout);
3133}
3134
zhihuangf8164932017-05-19 13:09:47 -07003135// Test that we can successfully get the media related stats (audio level
3136// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003137TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07003138 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
3139 ASSERT_TRUE(CreatePeerConnectionWrappers());
3140 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003141 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07003142 // Remove SSRCs and MSIDs from the received offer SDP.
3143 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3144 caller()->CreateAndSetAndSignalOffer();
3145 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003146 MediaExpectations media_expectations;
3147 media_expectations.CalleeExpectsSomeAudio(1);
3148 media_expectations.CalleeExpectsSomeVideo(1);
3149 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07003150
3151 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3152 callee()->NewGetStats();
3153 ASSERT_NE(nullptr, report);
3154
3155 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3156 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
3157 ASSERT_GE(audio_index, 0);
3158 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07003159}
3160
deadbeef4e2deab2017-09-20 13:56:21 -07003161// Helper for test below.
3162void ModifySsrcs(cricket::SessionDescription* desc) {
3163 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07003164 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08003165 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07003166 for (uint32_t& ssrc : stream.ssrcs) {
3167 ssrc = rtc::CreateRandomId();
3168 }
3169 }
3170 }
3171}
3172
3173// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
3174// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
3175// This should result in two "RTCInboundRTPStreamStats", but only one
3176// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
3177// being reset to 0 once the SSRC change occurs.
3178//
3179// Regression test for this bug:
3180// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
3181//
3182// The bug causes the track stats to only represent one of the two streams:
3183// whichever one has the higher SSRC. So with this bug, there was a 50% chance
3184// that the track stat counters would reset to 0 when the new stream is
3185// received, and a 50% chance that they'll stop updating (while
3186// "concealed_samples" continues increasing, due to silence being generated for
3187// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003188TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003189 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07003190 ASSERT_TRUE(CreatePeerConnectionWrappers());
3191 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003192 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07003193 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
3194 // that doesn't signal SSRCs (from the callee's perspective).
3195 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3196 caller()->CreateAndSetAndSignalOffer();
3197 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3198 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003199 {
3200 MediaExpectations media_expectations;
3201 media_expectations.CalleeExpectsSomeAudio(50);
3202 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3203 }
deadbeef4e2deab2017-09-20 13:56:21 -07003204 // Some audio frames were received, so we should have nonzero "samples
3205 // received" for the track.
3206 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3207 callee()->NewGetStats();
3208 ASSERT_NE(nullptr, report);
3209 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3210 ASSERT_EQ(1U, track_stats.size());
3211 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3212 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
3213 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
3214
3215 // Create a new offer and munge it to cause the caller to use a new SSRC.
3216 caller()->SetGeneratedSdpMunger(ModifySsrcs);
3217 caller()->CreateAndSetAndSignalOffer();
3218 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3219 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
3220 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003221 {
3222 MediaExpectations media_expectations;
3223 media_expectations.CalleeExpectsSomeAudio(25);
3224 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3225 }
deadbeef4e2deab2017-09-20 13:56:21 -07003226
3227 report = callee()->NewGetStats();
3228 ASSERT_NE(nullptr, report);
3229 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3230 ASSERT_EQ(1U, track_stats.size());
3231 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3232 // The "total samples received" stat should only be greater than it was
3233 // before.
3234 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
3235 // Right now, the new SSRC will cause the counters to reset to 0.
3236 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
3237
3238 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08003239 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07003240 // good sign that we're seeing stats from the old stream that's no longer
3241 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08003242 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07003243 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
3244 EXPECT_LT(*track_stats[0]->concealed_samples,
3245 *track_stats[0]->total_samples_received *
3246 kAcceptableConcealedSamplesPercentage);
3247
3248 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
3249 // sanity check that the SSRC really changed.
3250 // TODO(deadbeef): This isn't working right now, because we're not returning
3251 // *any* stats for the inactive stream. Uncomment when the bug is completely
3252 // fixed.
3253 // auto inbound_stream_stats =
3254 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3255 // ASSERT_EQ(2U, inbound_stream_stats.size());
3256}
3257
deadbeef1dcb1642017-03-29 21:08:16 -07003258// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003259TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003260 PeerConnectionFactory::Options dtls_10_options;
3261 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3262 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3263 dtls_10_options));
3264 ConnectFakeSignaling();
3265 // Do normal offer/answer and wait for some frames to be received in each
3266 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003267 caller()->AddAudioVideoTracks();
3268 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003269 caller()->CreateAndSetAndSignalOffer();
3270 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003271 MediaExpectations media_expectations;
3272 media_expectations.ExpectBidirectionalAudioAndVideo();
3273 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003274}
3275
3276// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003277TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003278 PeerConnectionFactory::Options dtls_10_options;
3279 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3280 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3281 dtls_10_options));
3282 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003283 caller()->AddAudioVideoTracks();
3284 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003285 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003286 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003287 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003288 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003289 kDefaultTimeout);
3290 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003291 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003292 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003293 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3294 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3295 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003296}
3297
3298// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003299TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003300 PeerConnectionFactory::Options dtls_12_options;
3301 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3302 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3303 dtls_12_options));
3304 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003305 caller()->AddAudioVideoTracks();
3306 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003307 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003308 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003309 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003310 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003311 kDefaultTimeout);
3312 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003313 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003314 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003315 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3316 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3317 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003318}
3319
3320// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3321// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003322TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003323 PeerConnectionFactory::Options caller_options;
3324 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3325 PeerConnectionFactory::Options callee_options;
3326 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3327 ASSERT_TRUE(
3328 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3329 ConnectFakeSignaling();
3330 // Do normal offer/answer and wait for some frames to be received in each
3331 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003332 caller()->AddAudioVideoTracks();
3333 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003334 caller()->CreateAndSetAndSignalOffer();
3335 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003336 MediaExpectations media_expectations;
3337 media_expectations.ExpectBidirectionalAudioAndVideo();
3338 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003339}
3340
3341// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3342// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003343TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003344 PeerConnectionFactory::Options caller_options;
3345 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3346 PeerConnectionFactory::Options callee_options;
3347 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3348 ASSERT_TRUE(
3349 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3350 ConnectFakeSignaling();
3351 // Do normal offer/answer and wait for some frames to be received in each
3352 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003353 caller()->AddAudioVideoTracks();
3354 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003355 caller()->CreateAndSetAndSignalOffer();
3356 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003357 MediaExpectations media_expectations;
3358 media_expectations.ExpectBidirectionalAudioAndVideo();
3359 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003360}
3361
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003362// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3363// works as expected; the cipher should only be used if enabled by both sides.
3364TEST_P(PeerConnectionIntegrationTest,
3365 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3366 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003367 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003368 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003369 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3370 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003371 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3372 TestNegotiatedCipherSuite(caller_options, callee_options,
3373 expected_cipher_suite);
3374}
3375
3376TEST_P(PeerConnectionIntegrationTest,
3377 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3378 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003379 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3380 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003381 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003382 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003383 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3384 TestNegotiatedCipherSuite(caller_options, callee_options,
3385 expected_cipher_suite);
3386}
3387
3388TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3389 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003390 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003391 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003392 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003393 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3394 TestNegotiatedCipherSuite(caller_options, callee_options,
3395 expected_cipher_suite);
3396}
3397
deadbeef1dcb1642017-03-29 21:08:16 -07003398// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003399TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003400 bool local_gcm_enabled = false;
3401 bool remote_gcm_enabled = false;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003402 bool aes_ctr_enabled = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003403 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3404 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003405 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003406}
3407
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003408// Test that a GCM cipher is used if both ends support it and non-GCM is
3409// disabled.
3410TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenOnlyGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003411 bool local_gcm_enabled = true;
3412 bool remote_gcm_enabled = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003413 bool aes_ctr_enabled = false;
deadbeef1dcb1642017-03-29 21:08:16 -07003414 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3415 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003416 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003417}
3418
deadbeef7914b8c2017-04-21 03:23:33 -07003419// Verify that media can be transmitted end-to-end when GCM crypto suites are
3420// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3421// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3422// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003423TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003424 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003425 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003426 gcm_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher = false;
deadbeef7914b8c2017-04-21 03:23:33 -07003427 ASSERT_TRUE(
3428 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3429 ConnectFakeSignaling();
3430 // Do normal offer/answer and wait for some frames to be received in each
3431 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003432 caller()->AddAudioVideoTracks();
3433 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003434 caller()->CreateAndSetAndSignalOffer();
3435 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003436 MediaExpectations media_expectations;
3437 media_expectations.ExpectBidirectionalAudioAndVideo();
3438 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003439}
3440
deadbeef1dcb1642017-03-29 21:08:16 -07003441// This test sets up a call between two parties with audio, video and an RTP
3442// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003443TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003444 PeerConnectionInterface::RTCConfiguration rtc_config;
3445 rtc_config.enable_rtp_data_channel = true;
3446 rtc_config.enable_dtls_srtp = false;
3447 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003448 ConnectFakeSignaling();
3449 // Expect that data channel created on caller side will show up for callee as
3450 // well.
3451 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003452 caller()->AddAudioVideoTracks();
3453 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003454 caller()->CreateAndSetAndSignalOffer();
3455 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3456 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003457 MediaExpectations media_expectations;
3458 media_expectations.ExpectBidirectionalAudioAndVideo();
3459 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003460 ASSERT_NE(nullptr, caller()->data_channel());
3461 ASSERT_NE(nullptr, callee()->data_channel());
3462 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3463 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3464
3465 // Ensure data can be sent in both directions.
3466 std::string data = "hello world";
3467 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3468 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3469 kDefaultTimeout);
3470 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3471 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3472 kDefaultTimeout);
3473}
3474
Eldar Rellod9ebe012020-03-18 20:41:45 +02003475TEST_P(PeerConnectionIntegrationTest, RtpDataChannelWorksAfterRollback) {
3476 PeerConnectionInterface::RTCConfiguration rtc_config;
3477 rtc_config.enable_rtp_data_channel = true;
3478 rtc_config.enable_dtls_srtp = false;
3479 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
3480 ConnectFakeSignaling();
3481 auto data_channel = caller()->pc()->CreateDataChannel("label_1", nullptr);
3482 ASSERT_TRUE(data_channel.get() != nullptr);
3483 caller()->CreateAndSetAndSignalOffer();
3484 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3485
3486 caller()->CreateDataChannel("label_2", nullptr);
3487 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
3488 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
3489 caller()->pc()->SetLocalDescription(observer,
3490 caller()->CreateOfferAndWait().release());
3491 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
3492 caller()->Rollback();
3493
3494 std::string data = "hello world";
3495 SendRtpDataWithRetries(data_channel, data, 5);
3496 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3497 kDefaultTimeout);
3498}
3499
deadbeef1dcb1642017-03-29 21:08:16 -07003500// Ensure that an RTP data channel is signaled as closed for the caller when
3501// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003502TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003503 RtpDataChannelSignaledClosedInCalleeOffer) {
3504 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003505 PeerConnectionInterface::RTCConfiguration rtc_config;
3506 rtc_config.enable_rtp_data_channel = true;
3507 rtc_config.enable_dtls_srtp = false;
3508 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003509 ConnectFakeSignaling();
3510 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003511 caller()->AddAudioVideoTracks();
3512 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003513 caller()->CreateAndSetAndSignalOffer();
3514 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3515 ASSERT_NE(nullptr, caller()->data_channel());
3516 ASSERT_NE(nullptr, callee()->data_channel());
3517 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3518 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3519
3520 // Close the data channel on the callee, and do an updated offer/answer.
3521 callee()->data_channel()->Close();
3522 callee()->CreateAndSetAndSignalOffer();
3523 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3524 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3525 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3526}
3527
3528// Tests that data is buffered in an RTP data channel until an observer is
3529// registered for it.
3530//
3531// NOTE: RTP data channels can receive data before the underlying
3532// transport has detected that a channel is writable and thus data can be
3533// received before the data channel state changes to open. That is hard to test
3534// but the same buffering is expected to be used in that case.
Yves Gerey100fe632020-01-17 19:15:53 +01003535//
3536// Use fake clock and simulated network delay so that we predictably can wait
3537// until an SCTP message has been delivered without "sleep()"ing.
3538TEST_P(PeerConnectionIntegrationTestWithFakeClock,
deadbeef1dcb1642017-03-29 21:08:16 -07003539 DataBufferedUntilRtpDataChannelObserverRegistered) {
deadbeef1dcb1642017-03-29 21:08:16 -07003540 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3541 virtual_socket_server()->UpdateDelayDistribution();
3542
Niels Möllerf06f9232018-08-07 12:32:18 +02003543 PeerConnectionInterface::RTCConfiguration rtc_config;
3544 rtc_config.enable_rtp_data_channel = true;
3545 rtc_config.enable_dtls_srtp = false;
3546 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003547 ConnectFakeSignaling();
3548 caller()->CreateDataChannel();
3549 caller()->CreateAndSetAndSignalOffer();
3550 ASSERT_TRUE(caller()->data_channel() != nullptr);
3551 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
Yves Gerey100fe632020-01-17 19:15:53 +01003552 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003553 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
Yves Gerey100fe632020-01-17 19:15:53 +01003554 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003555 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3556 callee()->data_channel()->state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003557 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003558
3559 // Unregister the observer which is normally automatically registered.
3560 callee()->data_channel()->UnregisterObserver();
3561 // Send data and advance fake clock until it should have been received.
3562 std::string data = "hello world";
3563 caller()->data_channel()->Send(DataBuffer(data));
Yves Gerey100fe632020-01-17 19:15:53 +01003564 SIMULATED_WAIT(false, 50, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003565
3566 // Attach data channel and expect data to be received immediately. Note that
3567 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3568 // further, but data can be received even if the callback is asynchronous.
3569 MockDataChannelObserver new_observer(callee()->data_channel());
3570 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003571 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003572}
3573
3574// This test sets up a call between two parties with audio, video and but only
3575// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003576TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003577 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3578 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003579 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003580 rtc_config_1.enable_dtls_srtp = false;
3581 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3582 rtc_config_2.enable_dtls_srtp = false;
3583 rtc_config_2.enable_dtls_srtp = false;
3584 ASSERT_TRUE(
3585 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003586 ConnectFakeSignaling();
3587 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003588 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003589 caller()->AddAudioVideoTracks();
3590 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003591 caller()->CreateAndSetAndSignalOffer();
3592 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3593 // The caller should still have a data channel, but it should be closed, and
3594 // one should ever have been created for the callee.
3595 EXPECT_TRUE(caller()->data_channel() != nullptr);
3596 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3597 EXPECT_EQ(nullptr, callee()->data_channel());
3598}
3599
3600// This test sets up a call between two parties with audio, and video. When
3601// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003602TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003603 PeerConnectionInterface::RTCConfiguration rtc_config;
3604 rtc_config.enable_rtp_data_channel = true;
3605 rtc_config.enable_dtls_srtp = false;
3606 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003607 ConnectFakeSignaling();
3608 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003609 caller()->AddAudioVideoTracks();
3610 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003611 caller()->CreateAndSetAndSignalOffer();
3612 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3613 // Create data channel and do new offer and answer.
3614 caller()->CreateDataChannel();
3615 caller()->CreateAndSetAndSignalOffer();
3616 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3617 ASSERT_NE(nullptr, caller()->data_channel());
3618 ASSERT_NE(nullptr, callee()->data_channel());
3619 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3620 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3621 // Ensure data can be sent in both directions.
3622 std::string data = "hello world";
3623 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3624 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3625 kDefaultTimeout);
3626 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3627 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3628 kDefaultTimeout);
3629}
3630
3631#ifdef HAVE_SCTP
3632
3633// This test sets up a call between two parties with audio, video and an SCTP
3634// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003635TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003636 ASSERT_TRUE(CreatePeerConnectionWrappers());
3637 ConnectFakeSignaling();
3638 // Expect that data channel created on caller side will show up for callee as
3639 // well.
3640 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003641 caller()->AddAudioVideoTracks();
3642 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003643 caller()->CreateAndSetAndSignalOffer();
3644 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3645 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003646 MediaExpectations media_expectations;
3647 media_expectations.ExpectBidirectionalAudioAndVideo();
3648 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003649 // Caller data channel should already exist (it created one). Callee data
3650 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3651 ASSERT_NE(nullptr, caller()->data_channel());
3652 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3653 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3654 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3655
3656 // Ensure data can be sent in both directions.
3657 std::string data = "hello world";
3658 caller()->data_channel()->Send(DataBuffer(data));
3659 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3660 kDefaultTimeout);
3661 callee()->data_channel()->Send(DataBuffer(data));
3662 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3663 kDefaultTimeout);
3664}
3665
3666// Ensure that when the callee closes an SCTP data channel, the closing
3667// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003668TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003669 // Same procedure as above test.
3670 ASSERT_TRUE(CreatePeerConnectionWrappers());
3671 ConnectFakeSignaling();
3672 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003673 caller()->AddAudioVideoTracks();
3674 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003675 caller()->CreateAndSetAndSignalOffer();
3676 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3677 ASSERT_NE(nullptr, caller()->data_channel());
3678 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3679 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3680 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3681
3682 // Close the data channel on the callee side, and wait for it to reach the
3683 // "closed" state on both sides.
3684 callee()->data_channel()->Close();
3685 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3686 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3687}
3688
Seth Hampson2f0d7022018-02-20 11:54:42 -08003689TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003690 ASSERT_TRUE(CreatePeerConnectionWrappers());
3691 ConnectFakeSignaling();
3692 webrtc::DataChannelInit init;
3693 init.id = 53;
3694 init.maxRetransmits = 52;
3695 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003696 caller()->AddAudioVideoTracks();
3697 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003698 caller()->CreateAndSetAndSignalOffer();
3699 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003700 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3701 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003702 // Since "negotiated" is false, the "id" parameter should be ignored.
3703 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003704 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3705 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3706 EXPECT_FALSE(callee()->data_channel()->negotiated());
3707}
3708
deadbeef1dcb1642017-03-29 21:08:16 -07003709// Test usrsctp's ability to process unordered data stream, where data actually
3710// arrives out of order using simulated delays. Previously there have been some
3711// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003712TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003713 // Introduce random network delays.
3714 // Otherwise it's not a true "unordered" test.
3715 virtual_socket_server()->set_delay_mean(20);
3716 virtual_socket_server()->set_delay_stddev(5);
3717 virtual_socket_server()->UpdateDelayDistribution();
3718 // Normal procedure, but with unordered data channel config.
3719 ASSERT_TRUE(CreatePeerConnectionWrappers());
3720 ConnectFakeSignaling();
3721 webrtc::DataChannelInit init;
3722 init.ordered = false;
3723 caller()->CreateDataChannel(&init);
3724 caller()->CreateAndSetAndSignalOffer();
3725 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3726 ASSERT_NE(nullptr, caller()->data_channel());
3727 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3728 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3729 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3730
3731 static constexpr int kNumMessages = 100;
3732 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3733 static constexpr size_t kMaxMessageSize = 4096;
3734 // Create and send random messages.
3735 std::vector<std::string> sent_messages;
3736 for (int i = 0; i < kNumMessages; ++i) {
3737 size_t length =
3738 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3739 std::string message;
3740 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3741 caller()->data_channel()->Send(DataBuffer(message));
3742 callee()->data_channel()->Send(DataBuffer(message));
3743 sent_messages.push_back(message);
3744 }
3745
3746 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003747 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003748 caller()->data_observer()->received_message_count(),
3749 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003750 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003751 callee()->data_observer()->received_message_count(),
3752 kDefaultTimeout);
3753
3754 // Sort and compare to make sure none of the messages were corrupted.
3755 std::vector<std::string> caller_received_messages =
3756 caller()->data_observer()->messages();
3757 std::vector<std::string> callee_received_messages =
3758 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003759 absl::c_sort(sent_messages);
3760 absl::c_sort(caller_received_messages);
3761 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003762 EXPECT_EQ(sent_messages, caller_received_messages);
3763 EXPECT_EQ(sent_messages, callee_received_messages);
3764}
3765
3766// This test sets up a call between two parties with audio, and video. When
3767// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003768TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003769 ASSERT_TRUE(CreatePeerConnectionWrappers());
3770 ConnectFakeSignaling();
3771 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003772 caller()->AddAudioVideoTracks();
3773 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003774 caller()->CreateAndSetAndSignalOffer();
3775 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3776 // Create data channel and do new offer and answer.
3777 caller()->CreateDataChannel();
3778 caller()->CreateAndSetAndSignalOffer();
3779 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3780 // Caller data channel should already exist (it created one). Callee data
3781 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3782 ASSERT_NE(nullptr, caller()->data_channel());
3783 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3784 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3785 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3786 // Ensure data can be sent in both directions.
3787 std::string data = "hello world";
3788 caller()->data_channel()->Send(DataBuffer(data));
3789 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3790 kDefaultTimeout);
3791 callee()->data_channel()->Send(DataBuffer(data));
3792 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3793 kDefaultTimeout);
3794}
3795
deadbeef7914b8c2017-04-21 03:23:33 -07003796// Set up a connection initially just using SCTP data channels, later upgrading
3797// to audio/video, ensuring frames are received end-to-end. Effectively the
3798// inverse of the test above.
3799// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003800TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003801 ASSERT_TRUE(CreatePeerConnectionWrappers());
3802 ConnectFakeSignaling();
3803 // Do initial offer/answer with just data channel.
3804 caller()->CreateDataChannel();
3805 caller()->CreateAndSetAndSignalOffer();
3806 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3807 // Wait until data can be sent over the data channel.
3808 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3809 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3810 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3811
3812 // Do subsequent offer/answer with two-way audio and video. Audio and video
3813 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003814 caller()->AddAudioVideoTracks();
3815 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003816 caller()->CreateAndSetAndSignalOffer();
3817 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003818 MediaExpectations media_expectations;
3819 media_expectations.ExpectBidirectionalAudioAndVideo();
3820 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003821}
3822
deadbeef8b7e9ad2017-05-25 09:38:55 -07003823static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003824 cricket::SctpDataContentDescription* dcd_offer =
3825 GetFirstSctpDataContentDescription(desc);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01003826 // See https://crbug.com/webrtc/11211 - this function is a no-op
Steve Antonb1c1de12017-12-21 15:14:30 -08003827 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003828 dcd_offer->set_use_sctpmap(false);
3829 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3830}
3831
3832// Test that the data channel works when a spec-compliant SCTP m= section is
3833// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3834// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003835TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003836 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3837 ASSERT_TRUE(CreatePeerConnectionWrappers());
3838 ConnectFakeSignaling();
3839 caller()->CreateDataChannel();
3840 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3841 caller()->CreateAndSetAndSignalOffer();
3842 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3843 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3844 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3845 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3846
3847 // Ensure data can be sent in both directions.
3848 std::string data = "hello world";
3849 caller()->data_channel()->Send(DataBuffer(data));
3850 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3851 kDefaultTimeout);
3852 callee()->data_channel()->Send(DataBuffer(data));
3853 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3854 kDefaultTimeout);
3855}
3856
deadbeef1dcb1642017-03-29 21:08:16 -07003857#endif // HAVE_SCTP
3858
3859// Test that the ICE connection and gathering states eventually reach
3860// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003861TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003862 ASSERT_TRUE(CreatePeerConnectionWrappers());
3863 ConnectFakeSignaling();
3864 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003865 caller()->AddAudioVideoTracks();
3866 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003867 caller()->CreateAndSetAndSignalOffer();
3868 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3869 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3870 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3871 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3872 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3873 // After the best candidate pair is selected and all candidates are signaled,
3874 // the ICE connection state should reach "complete".
3875 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3876 // answerer/"callee" by default) only reaches "connected". When this is
3877 // fixed, this test should be updated.
3878 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3879 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00003880 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3881 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003882}
3883
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003884constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
3885 cricket::PORTALLOCATOR_DISABLE_RELAY |
3886 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003887
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003888// Use a mock resolver to resolve the hostname back to the original IP on both
3889// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003890TEST_P(PeerConnectionIntegrationTest,
3891 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003892 auto caller_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02003893 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003894 auto callee_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02003895 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003896 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
3897 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003898
3899 // This also verifies that the injected AsyncResolverFactory is used by
3900 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003901 EXPECT_CALL(*caller_resolver_factory, Create())
3902 .WillOnce(Return(&caller_async_resolver));
3903 webrtc::PeerConnectionDependencies caller_deps(nullptr);
3904 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
3905
3906 EXPECT_CALL(*callee_resolver_factory, Create())
3907 .WillOnce(Return(&callee_async_resolver));
3908 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3909 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
3910
3911 PeerConnectionInterface::RTCConfiguration config;
3912 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3913 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3914
3915 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3916 config, std::move(caller_deps), config, std::move(callee_deps)));
3917
3918 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
3919 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
3920
3921 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07003922 caller()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02003923 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wangecd30542019-05-22 14:34:56 -07003924 callee()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02003925 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003926
3927 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003928
3929 ConnectFakeSignaling();
3930 caller()->AddAudioVideoTracks();
3931 callee()->AddAudioVideoTracks();
3932 caller()->CreateAndSetAndSignalOffer();
3933 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3934 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3935 caller()->ice_connection_state(), kDefaultTimeout);
3936 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3937 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08003938
Ying Wangef3998f2019-12-09 13:06:53 +01003939 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3940 "WebRTC.PeerConnection.CandidatePairType_UDP",
3941 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003942}
3943
Steve Antonede9ca52017-10-16 13:04:27 -07003944// Test that firewalling the ICE connection causes the clients to identify the
3945// disconnected state and then removing the firewall causes them to reconnect.
3946class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003947 : public PeerConnectionIntegrationBaseTest,
3948 public ::testing::WithParamInterface<
3949 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003950 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003951 PeerConnectionIntegrationIceStatesTest()
3952 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3953 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003954 }
3955
3956 void StartStunServer(const SocketAddress& server_address) {
3957 stun_server_.reset(
3958 cricket::TestStunServer::Create(network_thread(), server_address));
3959 }
3960
3961 bool TestIPv6() {
3962 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3963 }
3964
3965 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003966 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
3967 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07003968 }
3969
3970 std::vector<SocketAddress> CallerAddresses() {
3971 std::vector<SocketAddress> addresses;
3972 addresses.push_back(SocketAddress("1.1.1.1", 0));
3973 if (TestIPv6()) {
3974 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3975 }
3976 return addresses;
3977 }
3978
3979 std::vector<SocketAddress> CalleeAddresses() {
3980 std::vector<SocketAddress> addresses;
3981 addresses.push_back(SocketAddress("2.2.2.2", 0));
3982 if (TestIPv6()) {
3983 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3984 }
3985 return addresses;
3986 }
3987
3988 void SetUpNetworkInterfaces() {
3989 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07003990 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
3991 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07003992
3993 // Add network addresses for test.
3994 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003995 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003996 }
3997 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003998 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003999 }
4000 }
4001
4002 private:
4003 uint32_t port_allocator_flags_;
4004 std::unique_ptr<cricket::TestStunServer> stun_server_;
4005};
4006
Yves Gerey100fe632020-01-17 19:15:53 +01004007// Ensure FakeClockForTest is constructed first (see class for rationale).
4008class PeerConnectionIntegrationIceStatesTestWithFakeClock
4009 : public FakeClockForTest,
4010 public PeerConnectionIntegrationIceStatesTest {};
4011
Steve Antonede9ca52017-10-16 13:04:27 -07004012// Tests that the PeerConnection goes through all the ICE gathering/connection
4013// states over the duration of the call. This includes Disconnected and Failed
4014// states, induced by putting a firewall between the peers and waiting for them
4015// to time out.
Yves Gerey100fe632020-01-17 19:15:53 +01004016TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock, VerifyIceStates) {
Steve Antonede9ca52017-10-16 13:04:27 -07004017 const SocketAddress kStunServerAddress =
4018 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
4019 StartStunServer(kStunServerAddress);
4020
4021 PeerConnectionInterface::RTCConfiguration config;
4022 PeerConnectionInterface::IceServer ice_stun_server;
4023 ice_stun_server.urls.push_back(
4024 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4025 kStunServerAddress.PortAsString());
4026 config.servers.push_back(ice_stun_server);
4027
4028 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4029 ConnectFakeSignaling();
4030 SetPortAllocatorFlags();
4031 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004032 caller()->AddAudioVideoTracks();
4033 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004034
4035 // Initial state before anything happens.
4036 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4037 caller()->ice_gathering_state());
4038 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4039 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004040 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4041 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004042
4043 // Start the call by creating the offer, setting it as the local description,
4044 // then sending it to the peer who will respond with an answer. This happens
4045 // asynchronously so that we can watch the states as it runs in the
4046 // background.
4047 caller()->CreateAndSetAndSignalOffer();
4048
Steve Antona9b67ce2020-01-16 14:00:44 -08004049 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4050 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004051 FakeClock());
Steve Antona9b67ce2020-01-16 14:00:44 -08004052 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4053 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004054 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004055
4056 // Verify that the observer was notified of the intermediate transitions.
4057 EXPECT_THAT(caller()->ice_connection_state_history(),
4058 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4059 PeerConnectionInterface::kIceConnectionConnected,
4060 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004061 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4062 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4063 PeerConnectionInterface::kIceConnectionConnected,
4064 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004065 EXPECT_THAT(
4066 caller()->peer_connection_state_history(),
4067 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004068 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004069 EXPECT_THAT(caller()->ice_gathering_state_history(),
4070 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4071 PeerConnectionInterface::kIceGatheringComplete));
4072
4073 // Block connections to/from the caller and wait for ICE to become
4074 // disconnected.
4075 for (const auto& caller_address : CallerAddresses()) {
4076 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4077 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004078 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004079 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4080 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004081 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004082 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4083 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004084 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004085
4086 // Let ICE re-establish by removing the firewall rules.
4087 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004088 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004089 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4090 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004091 FakeClock());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004092 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004093 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004094 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004095
4096 // According to RFC7675, if there is no response within 30 seconds then the
4097 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004098 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004099 constexpr int kConsentTimeout = 30000;
4100 for (const auto& caller_address : CallerAddresses()) {
4101 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4102 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004103 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004104 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4105 caller()->ice_connection_state(), kConsentTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004106 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004107 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4108 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004109 kConsentTimeout, FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004110}
4111
4112// Tests that if the connection doesn't get set up properly we eventually reach
4113// the "failed" iceConnectionState.
Yves Gerey100fe632020-01-17 19:15:53 +01004114TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock,
4115 IceStateSetupFailure) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004116 // Block connections to/from the caller and wait for ICE to become
4117 // disconnected.
4118 for (const auto& caller_address : CallerAddresses()) {
4119 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4120 }
4121
4122 ASSERT_TRUE(CreatePeerConnectionWrappers());
4123 ConnectFakeSignaling();
4124 SetPortAllocatorFlags();
4125 SetUpNetworkInterfaces();
4126 caller()->AddAudioVideoTracks();
4127 caller()->CreateAndSetAndSignalOffer();
4128
4129 // According to RFC7675, if there is no response within 30 seconds then the
4130 // peer should consider the other side to have rejected the connection. This
4131 // is signaled by the state transitioning to "failed".
4132 constexpr int kConsentTimeout = 30000;
4133 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4134 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004135 kConsentTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004136}
4137
4138// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4139// and that the statistics in the metric observers are updated correctly.
4140TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4141 ASSERT_TRUE(CreatePeerConnectionWrappers());
4142 ConnectFakeSignaling();
4143 SetPortAllocatorFlags();
4144 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004145 caller()->AddAudioVideoTracks();
4146 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004147 caller()->CreateAndSetAndSignalOffer();
4148
4149 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton692f3c72020-01-16 14:12:31 -08004150 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4151 caller()->ice_connection_state(), kDefaultTimeout);
4152 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4153 callee()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07004154
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004155 // TODO(bugs.webrtc.org/9456): Fix it.
4156 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4157 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4158 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4159 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004160 if (TestIPv6()) {
4161 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4162 // connection.
Ying Wangef3998f2019-12-09 13:06:53 +01004163 EXPECT_METRIC_EQ(0, num_best_ipv4);
4164 EXPECT_METRIC_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004165 } else {
Ying Wangef3998f2019-12-09 13:06:53 +01004166 EXPECT_METRIC_EQ(1, num_best_ipv4);
4167 EXPECT_METRIC_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004168 }
4169
Ying Wangef3998f2019-12-09 13:06:53 +01004170 EXPECT_METRIC_EQ(0, webrtc::metrics::NumEvents(
4171 "WebRTC.PeerConnection.CandidatePairType_UDP",
4172 webrtc::kIceCandidatePairHostHost));
4173 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
4174 "WebRTC.PeerConnection.CandidatePairType_UDP",
4175 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004176}
4177
4178constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4179 cricket::PORTALLOCATOR_DISABLE_STUN |
4180 cricket::PORTALLOCATOR_DISABLE_RELAY;
4181constexpr uint32_t kFlagsIPv6NoStun =
4182 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4183 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4184constexpr uint32_t kFlagsIPv4Stun =
4185 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4186
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004187INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004188 PeerConnectionIntegrationTest,
4189 PeerConnectionIntegrationIceStatesTest,
4190 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4191 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4192 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4193 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004194
Yves Gerey100fe632020-01-17 19:15:53 +01004195INSTANTIATE_TEST_SUITE_P(
4196 PeerConnectionIntegrationTest,
4197 PeerConnectionIntegrationIceStatesTestWithFakeClock,
4198 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4199 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4200 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4201 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
4202
deadbeef1dcb1642017-03-29 21:08:16 -07004203// This test sets up a call between two parties with audio and video.
4204// During the call, the caller restarts ICE and the test verifies that
4205// new ICE candidates are generated and audio and video still can flow, and the
4206// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004207TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004208 ASSERT_TRUE(CreatePeerConnectionWrappers());
4209 ConnectFakeSignaling();
4210 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004211 caller()->AddAudioVideoTracks();
4212 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004213 caller()->CreateAndSetAndSignalOffer();
4214 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4215 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4216 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004217 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4218 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004219
4220 // To verify that the ICE restart actually occurs, get
4221 // ufrag/password/candidates before and after restart.
4222 // Create an SDP string of the first audio candidate for both clients.
4223 const webrtc::IceCandidateCollection* audio_candidates_caller =
4224 caller()->pc()->local_description()->candidates(0);
4225 const webrtc::IceCandidateCollection* audio_candidates_callee =
4226 callee()->pc()->local_description()->candidates(0);
4227 ASSERT_GT(audio_candidates_caller->count(), 0u);
4228 ASSERT_GT(audio_candidates_callee->count(), 0u);
4229 std::string caller_candidate_pre_restart;
4230 ASSERT_TRUE(
4231 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4232 std::string callee_candidate_pre_restart;
4233 ASSERT_TRUE(
4234 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4235 const cricket::SessionDescription* desc =
4236 caller()->pc()->local_description()->description();
4237 std::string caller_ufrag_pre_restart =
4238 desc->transport_infos()[0].description.ice_ufrag;
4239 desc = callee()->pc()->local_description()->description();
4240 std::string callee_ufrag_pre_restart =
4241 desc->transport_infos()[0].description.ice_ufrag;
4242
Alex Drake00c7ecf2019-08-06 10:54:47 -07004243 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004244 // Have the caller initiate an ICE restart.
4245 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4246 caller()->CreateAndSetAndSignalOffer();
4247 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4248 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4249 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004250 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004251 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4252
4253 // Grab the ufrags/candidates again.
4254 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4255 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4256 ASSERT_GT(audio_candidates_caller->count(), 0u);
4257 ASSERT_GT(audio_candidates_callee->count(), 0u);
4258 std::string caller_candidate_post_restart;
4259 ASSERT_TRUE(
4260 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4261 std::string callee_candidate_post_restart;
4262 ASSERT_TRUE(
4263 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4264 desc = caller()->pc()->local_description()->description();
4265 std::string caller_ufrag_post_restart =
4266 desc->transport_infos()[0].description.ice_ufrag;
4267 desc = callee()->pc()->local_description()->description();
4268 std::string callee_ufrag_post_restart =
4269 desc->transport_infos()[0].description.ice_ufrag;
4270 // Sanity check that an ICE restart was actually negotiated in SDP.
4271 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4272 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4273 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4274 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07004275 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004276
4277 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004278 MediaExpectations media_expectations;
4279 media_expectations.ExpectBidirectionalAudioAndVideo();
4280 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004281}
4282
4283// Verify that audio/video can be received end-to-end when ICE renomination is
4284// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004285TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004286 PeerConnectionInterface::RTCConfiguration config;
4287 config.enable_ice_renomination = true;
4288 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4289 ConnectFakeSignaling();
4290 // Do normal offer/answer and wait for some frames to be received in each
4291 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004292 caller()->AddAudioVideoTracks();
4293 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004294 caller()->CreateAndSetAndSignalOffer();
4295 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4296 // Sanity check that ICE renomination was actually negotiated.
4297 const cricket::SessionDescription* desc =
4298 caller()->pc()->local_description()->description();
4299 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004300 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004301 }
4302 desc = callee()->pc()->local_description()->description();
4303 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004304 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004305 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004306 MediaExpectations media_expectations;
4307 media_expectations.ExpectBidirectionalAudioAndVideo();
4308 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004309}
4310
Steve Anton6f25b092017-10-23 09:39:20 -07004311// With a max bundle policy and RTCP muxing, adding a new media description to
4312// the connection should not affect ICE at all because the new media will use
4313// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004314TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004315 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004316 PeerConnectionInterface::RTCConfiguration config;
4317 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4318 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4319 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4320 config, PeerConnectionInterface::RTCConfiguration()));
4321 ConnectFakeSignaling();
4322
Steve Anton15324772018-01-16 10:26:49 -08004323 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004324 caller()->CreateAndSetAndSignalOffer();
4325 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004326 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4327 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004328
4329 caller()->clear_ice_connection_state_history();
4330
Steve Anton15324772018-01-16 10:26:49 -08004331 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004332 caller()->CreateAndSetAndSignalOffer();
4333 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4334
4335 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4336}
4337
deadbeef1dcb1642017-03-29 21:08:16 -07004338// This test sets up a call between two parties with audio and video. It then
4339// renegotiates setting the video m-line to "port 0", then later renegotiates
4340// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004341TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004342 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4343 ASSERT_TRUE(CreatePeerConnectionWrappers());
4344 ConnectFakeSignaling();
4345
4346 // Do initial negotiation, only sending media from the caller. Will result in
4347 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004348 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004349 caller()->CreateAndSetAndSignalOffer();
4350 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4351
4352 // Negotiate again, disabling the video "m=" section (the callee will set the
4353 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004354 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4355 PeerConnectionInterface::RTCOfferAnswerOptions options;
4356 options.offer_to_receive_video = 0;
4357 callee()->SetOfferAnswerOptions(options);
4358 } else {
4359 callee()->SetRemoteOfferHandler([this] {
Harald Alvestrand6060df52020-08-11 09:54:02 +02004360 callee()
4361 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
4362 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08004363 });
4364 }
deadbeef1dcb1642017-03-29 21:08:16 -07004365 caller()->CreateAndSetAndSignalOffer();
4366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4367 // Sanity check that video "m=" section was actually rejected.
4368 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4369 callee()->pc()->local_description()->description());
4370 ASSERT_NE(nullptr, answer_video_content);
4371 ASSERT_TRUE(answer_video_content->rejected);
4372
4373 // Enable video and do negotiation again, making sure video is received
4374 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004375 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4376 PeerConnectionInterface::RTCOfferAnswerOptions options;
4377 options.offer_to_receive_video = 1;
4378 callee()->SetOfferAnswerOptions(options);
4379 } else {
4380 // The caller's transceiver is stopped, so we need to add another track.
4381 auto caller_transceiver =
4382 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
Harald Alvestrand6060df52020-08-11 09:54:02 +02004383 EXPECT_EQ(nullptr, caller_transceiver.get());
Seth Hampson2f0d7022018-02-20 11:54:42 -08004384 caller()->AddVideoTrack();
4385 }
4386 callee()->AddVideoTrack();
4387 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004388 caller()->CreateAndSetAndSignalOffer();
4389 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004390
deadbeef1dcb1642017-03-29 21:08:16 -07004391 // Verify the caller receives frames from the newly added stream, and the
4392 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004393 MediaExpectations media_expectations;
4394 media_expectations.CalleeExpectsSomeAudio();
4395 media_expectations.ExpectBidirectionalVideo();
4396 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004397}
4398
deadbeef1dcb1642017-03-29 21:08:16 -07004399// This tests that if we negotiate after calling CreateSender but before we
4400// have a track, then set a track later, frames from the newly-set track are
4401// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004402TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004403 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4404 ASSERT_TRUE(CreatePeerConnectionWrappers());
4405 ConnectFakeSignaling();
4406 auto caller_audio_sender =
4407 caller()->pc()->CreateSender("audio", "caller_stream");
4408 auto caller_video_sender =
4409 caller()->pc()->CreateSender("video", "caller_stream");
4410 auto callee_audio_sender =
4411 callee()->pc()->CreateSender("audio", "callee_stream");
4412 auto callee_video_sender =
4413 callee()->pc()->CreateSender("video", "callee_stream");
4414 caller()->CreateAndSetAndSignalOffer();
4415 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4416 // Wait for ICE to complete, without any tracks being set.
4417 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4418 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4419 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4420 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4421 // Now set the tracks, and expect frames to immediately start flowing.
4422 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4423 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4424 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4425 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004426 MediaExpectations media_expectations;
4427 media_expectations.ExpectBidirectionalAudioAndVideo();
4428 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4429}
4430
4431// This tests that if we negotiate after calling AddTransceiver but before we
4432// have a track, then set a track later, frames from the newly-set tracks are
4433// received end-to-end.
4434TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4435 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4436 ASSERT_TRUE(CreatePeerConnectionWrappers());
4437 ConnectFakeSignaling();
4438 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4439 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4440 auto caller_audio_sender = audio_result.MoveValue()->sender();
4441 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4442 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4443 auto caller_video_sender = video_result.MoveValue()->sender();
4444 callee()->SetRemoteOfferHandler([this] {
4445 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
Harald Alvestrand6060df52020-08-11 09:54:02 +02004446 callee()->pc()->GetTransceivers()[0]->SetDirectionWithError(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004447 RtpTransceiverDirection::kSendRecv);
Harald Alvestrand6060df52020-08-11 09:54:02 +02004448 callee()->pc()->GetTransceivers()[1]->SetDirectionWithError(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004449 RtpTransceiverDirection::kSendRecv);
4450 });
4451 caller()->CreateAndSetAndSignalOffer();
4452 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4453 // Wait for ICE to complete, without any tracks being set.
4454 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4455 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4456 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4457 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4458 // Now set the tracks, and expect frames to immediately start flowing.
4459 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4460 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4461 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4462 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4463 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4464 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4465 MediaExpectations media_expectations;
4466 media_expectations.ExpectBidirectionalAudioAndVideo();
4467 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004468}
4469
4470// This test verifies that a remote video track can be added via AddStream,
4471// and sent end-to-end. For this particular test, it's simply echoed back
4472// from the caller to the callee, rather than being forwarded to a third
4473// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004474TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004475 ASSERT_TRUE(CreatePeerConnectionWrappers());
4476 ConnectFakeSignaling();
4477 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004478 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004479 caller()->CreateAndSetAndSignalOffer();
4480 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004481 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004482
4483 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4484 // time).
4485 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4486 callee()->CreateAndSetAndSignalOffer();
4487 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4488
Seth Hampson2f0d7022018-02-20 11:54:42 -08004489 MediaExpectations media_expectations;
4490 media_expectations.ExpectBidirectionalVideo();
4491 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004492}
4493
4494// Test that we achieve the expected end-to-end connection time, using a
4495// fake clock and simulated latency on the media and signaling paths.
4496// We use a TURN<->TURN connection because this is usually the quickest to
4497// set up initially, especially when we're confident the connection will work
4498// and can start sending media before we get a STUN response.
4499//
4500// With various optimizations enabled, here are the network delays we expect to
4501// be on the critical path:
4502// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4503// signaling answer (with DTLS fingerprint).
4504// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4505// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4506// the first of which should have arrived before the answer.
Yves Gerey100fe632020-01-17 19:15:53 +01004507TEST_P(PeerConnectionIntegrationTestWithFakeClock,
4508 EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004509 static constexpr int media_hop_delay_ms = 50;
4510 static constexpr int signaling_trip_delay_ms = 500;
4511 // For explanation of these values, see comment above.
4512 static constexpr int required_media_hops = 9;
4513 static constexpr int required_signaling_trips = 2;
4514 // For internal delays (such as posting an event asychronously).
4515 static constexpr int allowed_internal_delay_ms = 20;
4516 static constexpr int total_connection_time_ms =
4517 media_hop_delay_ms * required_media_hops +
4518 signaling_trip_delay_ms * required_signaling_trips +
4519 allowed_internal_delay_ms;
4520
4521 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4522 3478};
4523 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4524 0};
4525 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4526 3478};
4527 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4528 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004529 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4530 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004531
Seth Hampsonaed71642018-06-11 07:41:32 -07004532 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4533 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004534 // Bypass permission check on received packets so media can be sent before
4535 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004536 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4537 turn_server_1->set_enable_permission_checks(false);
4538 });
4539 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4540 turn_server_2->set_enable_permission_checks(false);
4541 });
deadbeef1dcb1642017-03-29 21:08:16 -07004542
4543 PeerConnectionInterface::RTCConfiguration client_1_config;
4544 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4545 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4546 ice_server_1.username = "test";
4547 ice_server_1.password = "test";
4548 client_1_config.servers.push_back(ice_server_1);
4549 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4550 client_1_config.presume_writable_when_fully_relayed = true;
4551
4552 PeerConnectionInterface::RTCConfiguration client_2_config;
4553 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4554 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4555 ice_server_2.username = "test";
4556 ice_server_2.password = "test";
4557 client_2_config.servers.push_back(ice_server_2);
4558 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4559 client_2_config.presume_writable_when_fully_relayed = true;
4560
4561 ASSERT_TRUE(
4562 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4563 // Set up the simulated delays.
4564 SetSignalingDelayMs(signaling_trip_delay_ms);
4565 ConnectFakeSignaling();
4566 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4567 virtual_socket_server()->UpdateDelayDistribution();
4568
4569 // Set "offer to receive audio/video" without adding any tracks, so we just
4570 // set up ICE/DTLS with no media.
4571 PeerConnectionInterface::RTCOfferAnswerOptions options;
4572 options.offer_to_receive_audio = 1;
4573 options.offer_to_receive_video = 1;
4574 caller()->SetOfferAnswerOptions(options);
4575 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004576 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
Yves Gerey100fe632020-01-17 19:15:53 +01004577 FakeClock());
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004578 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4579 // If this is not done a DCHECK can be hit in ports.cc, because a large
4580 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07004581 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07004582}
4583
Jonas Orelandbdcee282017-10-10 14:01:40 +02004584// Verify that a TurnCustomizer passed in through RTCConfiguration
4585// is actually used by the underlying TURN candidate pair.
4586// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004587TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004588 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4589 3478};
4590 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4591 0};
4592 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4593 3478};
4594 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4595 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004596 CreateTurnServer(turn_server_1_internal_address,
4597 turn_server_1_external_address);
4598 CreateTurnServer(turn_server_2_internal_address,
4599 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004600
4601 PeerConnectionInterface::RTCConfiguration client_1_config;
4602 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4603 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4604 ice_server_1.username = "test";
4605 ice_server_1.password = "test";
4606 client_1_config.servers.push_back(ice_server_1);
4607 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004608 auto* customizer1 = CreateTurnCustomizer();
4609 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004610
4611 PeerConnectionInterface::RTCConfiguration client_2_config;
4612 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4613 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4614 ice_server_2.username = "test";
4615 ice_server_2.password = "test";
4616 client_2_config.servers.push_back(ice_server_2);
4617 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004618 auto* customizer2 = CreateTurnCustomizer();
4619 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004620
4621 ASSERT_TRUE(
4622 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4623 ConnectFakeSignaling();
4624
4625 // Set "offer to receive audio/video" without adding any tracks, so we just
4626 // set up ICE/DTLS with no media.
4627 PeerConnectionInterface::RTCOfferAnswerOptions options;
4628 options.offer_to_receive_audio = 1;
4629 options.offer_to_receive_video = 1;
4630 caller()->SetOfferAnswerOptions(options);
4631 caller()->CreateAndSetAndSignalOffer();
4632 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4633
Seth Hampsonaed71642018-06-11 07:41:32 -07004634 ExpectTurnCustomizerCountersIncremented(customizer1);
4635 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004636}
4637
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004638// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4639// send media between the caller and the callee.
4640TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4641 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4642 3478};
4643 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4644
4645 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004646 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4647 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004648
4649 webrtc::PeerConnectionInterface::IceServer ice_server;
4650 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4651 ice_server.username = "test";
4652 ice_server.password = "test";
4653
4654 PeerConnectionInterface::RTCConfiguration client_1_config;
4655 client_1_config.servers.push_back(ice_server);
4656 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4657
4658 PeerConnectionInterface::RTCConfiguration client_2_config;
4659 client_2_config.servers.push_back(ice_server);
4660 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4661
4662 ASSERT_TRUE(
4663 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4664
4665 // Do normal offer/answer and wait for ICE to complete.
4666 ConnectFakeSignaling();
4667 caller()->AddAudioVideoTracks();
4668 callee()->AddAudioVideoTracks();
4669 caller()->CreateAndSetAndSignalOffer();
4670 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4671 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4672 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4673
4674 MediaExpectations media_expectations;
4675 media_expectations.ExpectBidirectionalAudioAndVideo();
4676 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4677}
4678
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004679// Verify that a SSLCertificateVerifier passed in through
4680// PeerConnectionDependencies is actually used by the underlying SSL
4681// implementation to determine whether a certificate presented by the TURN
4682// server is accepted by the client. Note that openssladapter_unittest.cc
4683// contains more detailed, lower-level tests.
4684TEST_P(PeerConnectionIntegrationTest,
4685 SSLCertificateVerifierUsedForTurnConnections) {
4686 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4687 3478};
4688 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4689
4690 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4691 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004692 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4693 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004694
4695 webrtc::PeerConnectionInterface::IceServer ice_server;
4696 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4697 ice_server.username = "test";
4698 ice_server.password = "test";
4699
4700 PeerConnectionInterface::RTCConfiguration client_1_config;
4701 client_1_config.servers.push_back(ice_server);
4702 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4703
4704 PeerConnectionInterface::RTCConfiguration client_2_config;
4705 client_2_config.servers.push_back(ice_server);
4706 // Setting the type to kRelay forces the connection to go through a TURN
4707 // server.
4708 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4709
4710 // Get a copy to the pointer so we can verify calls later.
4711 rtc::TestCertificateVerifier* client_1_cert_verifier =
4712 new rtc::TestCertificateVerifier();
4713 client_1_cert_verifier->verify_certificate_ = true;
4714 rtc::TestCertificateVerifier* client_2_cert_verifier =
4715 new rtc::TestCertificateVerifier();
4716 client_2_cert_verifier->verify_certificate_ = true;
4717
4718 // Create the dependencies with the test certificate verifier.
4719 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4720 client_1_deps.tls_cert_verifier =
4721 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4722 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4723 client_2_deps.tls_cert_verifier =
4724 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4725
4726 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4727 client_1_config, std::move(client_1_deps), client_2_config,
4728 std::move(client_2_deps)));
4729 ConnectFakeSignaling();
4730
4731 // Set "offer to receive audio/video" without adding any tracks, so we just
4732 // set up ICE/DTLS with no media.
4733 PeerConnectionInterface::RTCOfferAnswerOptions options;
4734 options.offer_to_receive_audio = 1;
4735 options.offer_to_receive_video = 1;
4736 caller()->SetOfferAnswerOptions(options);
4737 caller()->CreateAndSetAndSignalOffer();
4738 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4739
4740 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4741 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004742}
4743
4744TEST_P(PeerConnectionIntegrationTest,
4745 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4746 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4747 3478};
4748 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4749
4750 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4751 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004752 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4753 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004754
4755 webrtc::PeerConnectionInterface::IceServer ice_server;
4756 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4757 ice_server.username = "test";
4758 ice_server.password = "test";
4759
4760 PeerConnectionInterface::RTCConfiguration client_1_config;
4761 client_1_config.servers.push_back(ice_server);
4762 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4763
4764 PeerConnectionInterface::RTCConfiguration client_2_config;
4765 client_2_config.servers.push_back(ice_server);
4766 // Setting the type to kRelay forces the connection to go through a TURN
4767 // server.
4768 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4769
4770 // Get a copy to the pointer so we can verify calls later.
4771 rtc::TestCertificateVerifier* client_1_cert_verifier =
4772 new rtc::TestCertificateVerifier();
4773 client_1_cert_verifier->verify_certificate_ = false;
4774 rtc::TestCertificateVerifier* client_2_cert_verifier =
4775 new rtc::TestCertificateVerifier();
4776 client_2_cert_verifier->verify_certificate_ = false;
4777
4778 // Create the dependencies with the test certificate verifier.
4779 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4780 client_1_deps.tls_cert_verifier =
4781 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4782 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4783 client_2_deps.tls_cert_verifier =
4784 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4785
4786 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4787 client_1_config, std::move(client_1_deps), client_2_config,
4788 std::move(client_2_deps)));
4789 ConnectFakeSignaling();
4790
4791 // Set "offer to receive audio/video" without adding any tracks, so we just
4792 // set up ICE/DTLS with no media.
4793 PeerConnectionInterface::RTCOfferAnswerOptions options;
4794 options.offer_to_receive_audio = 1;
4795 options.offer_to_receive_video = 1;
4796 caller()->SetOfferAnswerOptions(options);
4797 caller()->CreateAndSetAndSignalOffer();
4798 bool wait_res = true;
4799 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4800 // properly, should be able to just wait for a state of "failed" instead of
4801 // waiting a fixed 10 seconds.
4802 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4803 ASSERT_FALSE(wait_res);
4804
4805 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4806 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004807}
4808
Qingsi Wang25ec8882019-11-15 12:33:05 -08004809// Test that the injected ICE transport factory is used to create ICE transports
4810// for WebRTC connections.
4811TEST_P(PeerConnectionIntegrationTest, IceTransportFactoryUsedForConnections) {
4812 PeerConnectionInterface::RTCConfiguration default_config;
4813 PeerConnectionDependencies dependencies(nullptr);
4814 auto ice_transport_factory = std::make_unique<MockIceTransportFactory>();
4815 EXPECT_CALL(*ice_transport_factory, RecordIceTransportCreated()).Times(1);
4816 dependencies.ice_transport_factory = std::move(ice_transport_factory);
Niels Möller2a707032020-06-16 16:39:13 +02004817 auto wrapper = CreatePeerConnectionWrapper("Caller", nullptr, &default_config,
4818 std::move(dependencies), nullptr,
4819 /*reset_encoder_factory=*/false,
4820 /*reset_decoder_factory=*/false);
Qingsi Wang25ec8882019-11-15 12:33:05 -08004821 ASSERT_TRUE(wrapper);
4822 wrapper->CreateDataChannel();
4823 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
4824 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
4825 wrapper->pc()->SetLocalDescription(observer,
4826 wrapper->CreateOfferAndWait().release());
4827}
4828
deadbeefc964d0b2017-04-03 10:03:35 -07004829// Test that audio and video flow end-to-end when codec names don't use the
4830// expected casing, given that they're supposed to be case insensitive. To test
4831// this, all but one codec is removed from each media description, and its
4832// casing is changed.
4833//
4834// In the past, this has regressed and caused crashes/black video, due to the
4835// fact that code at some layers was doing case-insensitive comparisons and
4836// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004837TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004838 ASSERT_TRUE(CreatePeerConnectionWrappers());
4839 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004840 caller()->AddAudioVideoTracks();
4841 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004842
4843 // Remove all but one audio/video codec (opus and VP8), and change the
4844 // casing of the caller's generated offer.
4845 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4846 cricket::AudioContentDescription* audio =
4847 GetFirstAudioContentDescription(description);
4848 ASSERT_NE(nullptr, audio);
4849 auto audio_codecs = audio->codecs();
4850 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4851 [](const cricket::AudioCodec& codec) {
4852 return codec.name != "opus";
4853 }),
4854 audio_codecs.end());
4855 ASSERT_EQ(1u, audio_codecs.size());
4856 audio_codecs[0].name = "OpUs";
4857 audio->set_codecs(audio_codecs);
4858
4859 cricket::VideoContentDescription* video =
4860 GetFirstVideoContentDescription(description);
4861 ASSERT_NE(nullptr, video);
4862 auto video_codecs = video->codecs();
4863 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4864 [](const cricket::VideoCodec& codec) {
4865 return codec.name != "VP8";
4866 }),
4867 video_codecs.end());
4868 ASSERT_EQ(1u, video_codecs.size());
4869 video_codecs[0].name = "vP8";
4870 video->set_codecs(video_codecs);
4871 });
4872
4873 caller()->CreateAndSetAndSignalOffer();
4874 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4875
4876 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004877 MediaExpectations media_expectations;
4878 media_expectations.ExpectBidirectionalAudioAndVideo();
4879 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004880}
4881
Jonas Oreland49ac5952018-09-26 16:04:32 +02004882TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004883 ASSERT_TRUE(CreatePeerConnectionWrappers());
4884 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004885 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004886 caller()->CreateAndSetAndSignalOffer();
4887 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004888 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004889 MediaExpectations media_expectations;
4890 media_expectations.CalleeExpectsSomeAudio(1);
4891 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004892 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004893 auto receiver = callee()->pc()->GetReceivers()[0];
4894 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004895 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004896 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4897 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004898 sources[0].source_id());
4899 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4900}
4901
4902TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4903 ASSERT_TRUE(CreatePeerConnectionWrappers());
4904 ConnectFakeSignaling();
4905 caller()->AddVideoTrack();
4906 caller()->CreateAndSetAndSignalOffer();
4907 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4908 // Wait for one video frame to be received by the callee.
4909 MediaExpectations media_expectations;
4910 media_expectations.CalleeExpectsSomeVideo(1);
4911 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4912 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4913 auto receiver = callee()->pc()->GetReceivers()[0];
4914 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4915 auto sources = receiver->GetSources();
4916 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02004917 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004918 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4919 sources[0].source_id());
4920 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004921}
4922
deadbeef2f425aa2017-04-14 10:41:32 -07004923// Test that if a track is removed and added again with a different stream ID,
4924// the new stream ID is successfully communicated in SDP and media continues to
4925// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004926// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4927// it will not reuse a transceiver that has already been sending. After creating
4928// a new transceiver it tries to create an offer with two senders of the same
4929// track ids and it fails.
4930TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004931 ASSERT_TRUE(CreatePeerConnectionWrappers());
4932 ConnectFakeSignaling();
4933
deadbeef2f425aa2017-04-14 10:41:32 -07004934 // Add track using stream 1, do offer/answer.
4935 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4936 caller()->CreateLocalAudioTrack();
4937 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004938 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004939 caller()->CreateAndSetAndSignalOffer();
4940 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004941 {
4942 MediaExpectations media_expectations;
4943 media_expectations.CalleeExpectsSomeAudio(1);
4944 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4945 }
deadbeef2f425aa2017-04-14 10:41:32 -07004946 // Remove the sender, and create a new one with the new stream.
4947 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004948 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004949 caller()->CreateAndSetAndSignalOffer();
4950 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4951 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004952 {
4953 MediaExpectations media_expectations;
4954 media_expectations.CalleeExpectsSomeAudio();
4955 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4956 }
deadbeef2f425aa2017-04-14 10:41:32 -07004957}
4958
Seth Hampson2f0d7022018-02-20 11:54:42 -08004959TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004960 ASSERT_TRUE(CreatePeerConnectionWrappers());
4961 ConnectFakeSignaling();
4962
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004963 auto output = std::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02004964 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
4965 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02004966 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004967 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4968 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004969
Steve Anton15324772018-01-16 10:26:49 -08004970 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004971 caller()->CreateAndSetAndSignalOffer();
4972 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4973}
4974
Steve Antonede9ca52017-10-16 13:04:27 -07004975// Test that if candidates are only signaled by applying full session
4976// descriptions (instead of using AddIceCandidate), the peers can connect to
4977// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004978TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004979 ASSERT_TRUE(CreatePeerConnectionWrappers());
4980 // Each side will signal the session descriptions but not candidates.
4981 ConnectFakeSignalingForSdpOnly();
4982
4983 // Add audio video track and exchange the initial offer/answer with media
4984 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004985 caller()->AddAudioVideoTracks();
4986 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004987 caller()->CreateAndSetAndSignalOffer();
4988
4989 // Wait for all candidates to be gathered on both the caller and callee.
4990 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4991 caller()->ice_gathering_state(), kDefaultTimeout);
4992 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4993 callee()->ice_gathering_state(), kDefaultTimeout);
4994
4995 // The candidates will now be included in the session description, so
4996 // signaling them will start the ICE connection.
4997 caller()->CreateAndSetAndSignalOffer();
4998 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4999
5000 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005001 MediaExpectations media_expectations;
5002 media_expectations.ExpectBidirectionalAudioAndVideo();
5003 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07005004}
5005
henrika5f6bf242017-11-01 11:06:56 +01005006// Test that SetAudioPlayout can be used to disable audio playout from the
5007// start, then later enable it. This may be useful, for example, if the caller
5008// needs to play a local ringtone until some event occurs, after which it
5009// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005010TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01005011 ASSERT_TRUE(CreatePeerConnectionWrappers());
5012 ConnectFakeSignaling();
5013
5014 // Set up audio-only call where audio playout is disabled on caller's side.
5015 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08005016 caller()->AddAudioTrack();
5017 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005018 caller()->CreateAndSetAndSignalOffer();
5019 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5020
5021 // Pump messages for a second.
5022 WAIT(false, 1000);
5023 // Since audio playout is disabled, the caller shouldn't have received
5024 // anything (at the playout level, at least).
5025 EXPECT_EQ(0, caller()->audio_frames_received());
5026 // As a sanity check, make sure the callee (for which playout isn't disabled)
5027 // did still see frames on its audio level.
5028 ASSERT_GT(callee()->audio_frames_received(), 0);
5029
5030 // Enable playout again, and ensure audio starts flowing.
5031 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005032 MediaExpectations media_expectations;
5033 media_expectations.ExpectBidirectionalAudio();
5034 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01005035}
5036
5037double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5038 auto report = pc->NewGetStats();
5039 auto track_stats_list =
5040 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5041 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5042 for (const auto* track_stats : track_stats_list) {
5043 if (track_stats->remote_source.is_defined() &&
5044 *track_stats->remote_source) {
5045 remote_track_stats = track_stats;
5046 break;
5047 }
5048 }
5049
5050 if (!remote_track_stats->total_audio_energy.is_defined()) {
5051 return 0.0;
5052 }
5053 return *remote_track_stats->total_audio_energy;
5054}
5055
5056// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5057// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005058TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005059 DisableAudioPlayoutStillGeneratesAudioStats) {
5060 ASSERT_TRUE(CreatePeerConnectionWrappers());
5061 ConnectFakeSignaling();
5062
5063 // Set up audio-only call where playout is disabled but audio-processing is
5064 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005065 caller()->AddAudioTrack();
5066 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005067 caller()->pc()->SetAudioPlayout(false);
5068
5069 caller()->CreateAndSetAndSignalOffer();
5070 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5071
5072 // Wait for the callee to receive audio stats.
5073 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5074}
5075
henrika4f167df2017-11-01 14:45:55 +01005076// Test that SetAudioRecording can be used to disable audio recording from the
5077// start, then later enable it. This may be useful, for example, if the caller
5078// wants to ensure that no audio resources are active before a certain state
5079// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005080TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005081 ASSERT_TRUE(CreatePeerConnectionWrappers());
5082 ConnectFakeSignaling();
5083
5084 // Set up audio-only call where audio recording is disabled on caller's side.
5085 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005086 caller()->AddAudioTrack();
5087 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005088 caller()->CreateAndSetAndSignalOffer();
5089 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5090
5091 // Pump messages for a second.
5092 WAIT(false, 1000);
5093 // Since caller has disabled audio recording, the callee shouldn't have
5094 // received anything.
5095 EXPECT_EQ(0, callee()->audio_frames_received());
5096 // As a sanity check, make sure the caller did still see frames on its
5097 // audio level since audio recording is enabled on the calle side.
5098 ASSERT_GT(caller()->audio_frames_received(), 0);
5099
5100 // Enable audio recording again, and ensure audio starts flowing.
5101 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005102 MediaExpectations media_expectations;
5103 media_expectations.ExpectBidirectionalAudio();
5104 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005105}
5106
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005107// Test that after closing PeerConnections, they stop sending any packets (ICE,
5108// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005109TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005110 // Set up audio/video/data, wait for some frames to be received.
5111 ASSERT_TRUE(CreatePeerConnectionWrappers());
5112 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005113 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005114#ifdef HAVE_SCTP
5115 caller()->CreateDataChannel();
5116#endif
5117 caller()->CreateAndSetAndSignalOffer();
5118 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005119 MediaExpectations media_expectations;
5120 media_expectations.CalleeExpectsSomeAudioAndVideo();
5121 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005122 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005123 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005124 // Pump messages for a second, and ensure no new packets end up sent.
5125 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5126 WAIT(false, 1000);
5127 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5128 EXPECT_EQ(sent_packets_a, sent_packets_b);
5129}
5130
Steve Anton7eca0932018-03-30 15:18:41 -07005131// Test that transport stats are generated by the RTCStatsCollector for a
5132// connection that only involves data channels. This is a regression test for
5133// crbug.com/826972.
5134#ifdef HAVE_SCTP
5135TEST_P(PeerConnectionIntegrationTest,
5136 TransportStatsReportedForDataChannelOnlyConnection) {
5137 ASSERT_TRUE(CreatePeerConnectionWrappers());
5138 ConnectFakeSignaling();
5139 caller()->CreateDataChannel();
5140
5141 caller()->CreateAndSetAndSignalOffer();
5142 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5143 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5144
5145 auto caller_report = caller()->NewGetStats();
5146 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5147 auto callee_report = callee()->NewGetStats();
5148 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5149}
5150#endif // HAVE_SCTP
5151
Qingsi Wang7685e862018-06-11 20:15:46 -07005152TEST_P(PeerConnectionIntegrationTest,
5153 IceEventsGeneratedAndLoggedInRtcEventLog) {
5154 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5155 ConnectFakeSignaling();
5156 PeerConnectionInterface::RTCOfferAnswerOptions options;
5157 options.offer_to_receive_audio = 1;
5158 caller()->SetOfferAnswerOptions(options);
5159 caller()->CreateAndSetAndSignalOffer();
5160 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5161 ASSERT_NE(nullptr, caller()->event_log_factory());
5162 ASSERT_NE(nullptr, callee()->event_log_factory());
5163 webrtc::FakeRtcEventLog* caller_event_log =
5164 static_cast<webrtc::FakeRtcEventLog*>(
5165 caller()->event_log_factory()->last_log_created());
5166 webrtc::FakeRtcEventLog* callee_event_log =
5167 static_cast<webrtc::FakeRtcEventLog*>(
5168 callee()->event_log_factory()->last_log_created());
5169 ASSERT_NE(nullptr, caller_event_log);
5170 ASSERT_NE(nullptr, callee_event_log);
5171 int caller_ice_config_count = caller_event_log->GetEventCount(
5172 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5173 int caller_ice_event_count = caller_event_log->GetEventCount(
5174 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5175 int callee_ice_config_count = callee_event_log->GetEventCount(
5176 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5177 int callee_ice_event_count = callee_event_log->GetEventCount(
5178 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5179 EXPECT_LT(0, caller_ice_config_count);
5180 EXPECT_LT(0, caller_ice_event_count);
5181 EXPECT_LT(0, callee_ice_config_count);
5182 EXPECT_LT(0, callee_ice_event_count);
5183}
5184
Qingsi Wangc129c352019-04-18 10:41:58 -07005185TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005186 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5187 3478};
5188 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5189
5190 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5191
5192 webrtc::PeerConnectionInterface::IceServer ice_server;
5193 ice_server.urls.push_back("turn:88.88.88.0:3478");
5194 ice_server.username = "test";
5195 ice_server.password = "test";
5196
5197 PeerConnectionInterface::RTCConfiguration caller_config;
5198 caller_config.servers.push_back(ice_server);
5199 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5200 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005201 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005202
5203 PeerConnectionInterface::RTCConfiguration callee_config;
5204 callee_config.servers.push_back(ice_server);
5205 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5206 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005207 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005208
5209 ASSERT_TRUE(
5210 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5211
5212 // Do normal offer/answer and wait for ICE to complete.
5213 ConnectFakeSignaling();
5214 caller()->AddAudioVideoTracks();
5215 callee()->AddAudioVideoTracks();
5216 caller()->CreateAndSetAndSignalOffer();
5217 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5218 // Since we are doing continual gathering, the ICE transport does not reach
5219 // kIceGatheringComplete (see
5220 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5221 // kIceConnectionComplete.
5222 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5223 caller()->ice_connection_state(), kDefaultTimeout);
5224 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5225 callee()->ice_connection_state(), kDefaultTimeout);
5226 // Note that we cannot use the metric
5227 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5228 // metric is only populated when we reach kIceConnectionComplete in the
5229 // current implementation.
5230 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5231 caller()->last_candidate_gathered().type());
5232 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5233 callee()->last_candidate_gathered().type());
5234
5235 // Loosen the caller's candidate filter.
5236 caller_config = caller()->pc()->GetConfiguration();
5237 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5238 caller()->pc()->SetConfiguration(caller_config);
5239 // We should have gathered a new host candidate.
5240 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5241 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5242
5243 // Loosen the callee's candidate filter.
5244 callee_config = callee()->pc()->GetConfiguration();
5245 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5246 callee()->pc()->SetConfiguration(callee_config);
5247 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5248 callee()->last_candidate_gathered().type(), kDefaultTimeout);
Jonas Orelande3096512020-05-27 09:01:05 +02005249
5250 // Create an offer and verify that it does not contain an ICE restart (i.e new
5251 // ice credentials).
5252 std::string caller_ufrag_pre_offer = caller()
5253 ->pc()
5254 ->local_description()
5255 ->description()
5256 ->transport_infos()[0]
5257 .description.ice_ufrag;
5258 caller()->CreateAndSetAndSignalOffer();
5259 std::string caller_ufrag_post_offer = caller()
5260 ->pc()
5261 ->local_description()
5262 ->description()
5263 ->transport_infos()[0]
5264 .description.ice_ufrag;
5265 EXPECT_EQ(caller_ufrag_pre_offer, caller_ufrag_post_offer);
Qingsi Wangc129c352019-04-18 10:41:58 -07005266}
5267
Eldar Relloda13ea22019-06-01 12:23:43 +03005268TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03005269 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5270 3478};
5271 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5272
5273 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5274
5275 webrtc::PeerConnectionInterface::IceServer ice_server;
5276 ice_server.urls.push_back("turn:88.88.88.0:3478");
5277 ice_server.username = "test";
5278 ice_server.password = "123";
5279
5280 PeerConnectionInterface::RTCConfiguration caller_config;
5281 caller_config.servers.push_back(ice_server);
5282 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5283 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5284
5285 PeerConnectionInterface::RTCConfiguration callee_config;
5286 callee_config.servers.push_back(ice_server);
5287 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5288 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5289
5290 ASSERT_TRUE(
5291 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5292
5293 // Do normal offer/answer and wait for ICE to complete.
5294 ConnectFakeSignaling();
5295 caller()->AddAudioVideoTracks();
5296 callee()->AddAudioVideoTracks();
5297 caller()->CreateAndSetAndSignalOffer();
5298 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5299 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5300 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5301 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
Eldar Rello0095d372019-12-02 22:22:07 +02005302 EXPECT_NE(caller()->error_event().address, "");
Eldar Relloda13ea22019-06-01 12:23:43 +03005303}
5304
Eldar Rellofa8019c2020-05-14 11:59:33 +03005305TEST_P(PeerConnectionIntegrationTest, OnIceCandidateErrorWithEmptyAddress) {
5306 webrtc::PeerConnectionInterface::IceServer ice_server;
5307 ice_server.urls.push_back("turn:127.0.0.1:3478?transport=tcp");
5308 ice_server.username = "test";
5309 ice_server.password = "test";
5310
5311 PeerConnectionInterface::RTCConfiguration caller_config;
5312 caller_config.servers.push_back(ice_server);
5313 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5314 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5315
5316 PeerConnectionInterface::RTCConfiguration callee_config;
5317 callee_config.servers.push_back(ice_server);
5318 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5319 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5320
5321 ASSERT_TRUE(
5322 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5323
5324 // Do normal offer/answer and wait for ICE to complete.
5325 ConnectFakeSignaling();
5326 caller()->AddAudioVideoTracks();
5327 callee()->AddAudioVideoTracks();
5328 caller()->CreateAndSetAndSignalOffer();
5329 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5330 EXPECT_EQ_WAIT(701, caller()->error_event().error_code, kDefaultTimeout);
5331 EXPECT_EQ(caller()->error_event().address, "");
5332}
5333
Eldar Rello5ab79e62019-10-09 18:29:44 +03005334TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5335 AudioKeepsFlowingAfterImplicitRollback) {
5336 PeerConnectionInterface::RTCConfiguration config;
5337 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5338 config.enable_implicit_rollback = true;
5339 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5340 ConnectFakeSignaling();
5341 caller()->AddAudioTrack();
5342 callee()->AddAudioTrack();
5343 caller()->CreateAndSetAndSignalOffer();
5344 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5345 MediaExpectations media_expectations;
5346 media_expectations.ExpectBidirectionalAudio();
5347 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5348 SetSignalIceCandidates(false); // Workaround candidate outrace sdp.
5349 caller()->AddVideoTrack();
5350 callee()->AddVideoTrack();
5351 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5352 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5353 callee()->pc()->SetLocalDescription(observer,
5354 callee()->CreateOfferAndWait().release());
5355 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
5356 caller()->CreateAndSetAndSignalOffer(); // Implicit rollback.
5357 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5358 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5359}
5360
5361TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5362 ImplicitRollbackVisitsStableState) {
5363 RTCConfiguration config;
5364 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5365 config.enable_implicit_rollback = true;
5366
5367 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5368
5369 rtc::scoped_refptr<MockSetSessionDescriptionObserver> sld_observer(
5370 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5371 callee()->pc()->SetLocalDescription(sld_observer,
5372 callee()->CreateOfferAndWait().release());
5373 EXPECT_TRUE_WAIT(sld_observer->called(), kDefaultTimeout);
5374 EXPECT_EQ(sld_observer->error(), "");
5375
5376 rtc::scoped_refptr<MockSetSessionDescriptionObserver> srd_observer(
5377 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5378 callee()->pc()->SetRemoteDescription(
5379 srd_observer, caller()->CreateOfferAndWait().release());
5380 EXPECT_TRUE_WAIT(srd_observer->called(), kDefaultTimeout);
5381 EXPECT_EQ(srd_observer->error(), "");
5382
5383 EXPECT_THAT(callee()->peer_connection_signaling_state_history(),
5384 ElementsAre(PeerConnectionInterface::kHaveLocalOffer,
5385 PeerConnectionInterface::kStable,
5386 PeerConnectionInterface::kHaveRemoteOffer));
5387}
5388
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005389INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5390 PeerConnectionIntegrationTest,
5391 Values(SdpSemantics::kPlanB,
5392 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005393
Yves Gerey100fe632020-01-17 19:15:53 +01005394INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5395 PeerConnectionIntegrationTestWithFakeClock,
5396 Values(SdpSemantics::kPlanB,
5397 SdpSemantics::kUnifiedPlan));
5398
Steve Anton74255ff2018-01-24 18:32:57 -08005399// Tests that verify interoperability between Plan B and Unified Plan
5400// PeerConnections.
5401class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08005402 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08005403 public ::testing::WithParamInterface<
5404 std::tuple<SdpSemantics, SdpSemantics>> {
5405 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08005406 // Setting the SdpSemantics for the base test to kDefault does not matter
5407 // because we specify not to use the test semantics when creating
5408 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08005409 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07005410 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08005411 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08005412 callee_semantics_(std::get<1>(GetParam())) {}
5413
5414 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07005415 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5416 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08005417 }
5418
5419 const SdpSemantics caller_semantics_;
5420 const SdpSemantics callee_semantics_;
5421};
5422
5423TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5424 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5425 ConnectFakeSignaling();
5426
5427 caller()->CreateAndSetAndSignalOffer();
5428 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5429}
5430
5431TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
5432 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5433 ConnectFakeSignaling();
5434 auto audio_sender = caller()->AddAudioTrack();
5435
5436 caller()->CreateAndSetAndSignalOffer();
5437 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5438
5439 // Verify that one audio receiver has been created on the remote and that it
5440 // has the same track ID as the sending track.
5441 auto receivers = callee()->pc()->GetReceivers();
5442 ASSERT_EQ(1u, receivers.size());
5443 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
5444 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
5445
Seth Hampson2f0d7022018-02-20 11:54:42 -08005446 MediaExpectations media_expectations;
5447 media_expectations.CalleeExpectsSomeAudio();
5448 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005449}
5450
5451TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
5452 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5453 ConnectFakeSignaling();
5454 auto video_sender = caller()->AddVideoTrack();
5455 auto audio_sender = caller()->AddAudioTrack();
5456
5457 caller()->CreateAndSetAndSignalOffer();
5458 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5459
5460 // Verify that one audio and one video receiver have been created on the
5461 // remote and that they have the same track IDs as the sending tracks.
5462 auto audio_receivers =
5463 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5464 ASSERT_EQ(1u, audio_receivers.size());
5465 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5466 auto video_receivers =
5467 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5468 ASSERT_EQ(1u, video_receivers.size());
5469 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5470
Seth Hampson2f0d7022018-02-20 11:54:42 -08005471 MediaExpectations media_expectations;
5472 media_expectations.CalleeExpectsSomeAudioAndVideo();
5473 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005474}
5475
5476TEST_P(PeerConnectionIntegrationInteropTest,
5477 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5478 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5479 ConnectFakeSignaling();
5480 caller()->AddAudioVideoTracks();
5481 callee()->AddAudioVideoTracks();
5482
5483 caller()->CreateAndSetAndSignalOffer();
5484 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5485
Seth Hampson2f0d7022018-02-20 11:54:42 -08005486 MediaExpectations media_expectations;
5487 media_expectations.ExpectBidirectionalAudioAndVideo();
5488 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005489}
5490
5491TEST_P(PeerConnectionIntegrationInteropTest,
5492 ReverseRolesOneAudioLocalToOneVideoRemote) {
5493 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5494 ConnectFakeSignaling();
5495 caller()->AddAudioTrack();
5496 callee()->AddVideoTrack();
5497
5498 caller()->CreateAndSetAndSignalOffer();
5499 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5500
5501 // Verify that only the audio track has been negotiated.
5502 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5503 // Might also check that the callee's NegotiationNeeded flag is set.
5504
5505 // Reverse roles.
5506 callee()->CreateAndSetAndSignalOffer();
5507 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5508
Seth Hampson2f0d7022018-02-20 11:54:42 -08005509 MediaExpectations media_expectations;
5510 media_expectations.CallerExpectsSomeVideo();
5511 media_expectations.CalleeExpectsSomeAudio();
5512 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005513}
5514
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005515INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07005516 PeerConnectionIntegrationTest,
5517 PeerConnectionIntegrationInteropTest,
5518 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5519 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5520
5521// Test that if the Unified Plan side offers two video tracks then the Plan B
5522// side will only see the first one and ignore the second.
5523TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005524 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5525 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005526 ConnectFakeSignaling();
5527 auto first_sender = caller()->AddVideoTrack();
5528 caller()->AddVideoTrack();
5529
5530 caller()->CreateAndSetAndSignalOffer();
5531 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5532
5533 // Verify that there is only one receiver and it corresponds to the first
5534 // added track.
5535 auto receivers = callee()->pc()->GetReceivers();
5536 ASSERT_EQ(1u, receivers.size());
5537 EXPECT_TRUE(receivers[0]->track()->enabled());
5538 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5539
Seth Hampson2f0d7022018-02-20 11:54:42 -08005540 MediaExpectations media_expectations;
5541 media_expectations.CalleeExpectsSomeVideo();
5542 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005543}
5544
Steve Anton2bed3972019-01-04 17:04:30 -08005545// Test that if the initial offer tagged BUNDLE section is rejected due to its
5546// associated RtpTransceiver being stopped and another transceiver is added,
5547// then renegotiation causes the callee to receive the new video track without
5548// error.
5549// This is a regression test for bugs.webrtc.org/9954
5550TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5551 ReOfferWithStoppedBundleTaggedTransceiver) {
5552 RTCConfiguration config;
5553 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5554 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5555 ConnectFakeSignaling();
5556 auto audio_transceiver_or_error =
5557 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5558 ASSERT_TRUE(audio_transceiver_or_error.ok());
5559 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5560
5561 caller()->CreateAndSetAndSignalOffer();
5562 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5563 {
5564 MediaExpectations media_expectations;
5565 media_expectations.CalleeExpectsSomeAudio();
5566 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5567 }
5568
Harald Alvestrand6060df52020-08-11 09:54:02 +02005569 audio_transceiver->StopInternal();
Steve Anton2bed3972019-01-04 17:04:30 -08005570 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5571
5572 caller()->CreateAndSetAndSignalOffer();
5573 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5574 {
5575 MediaExpectations media_expectations;
5576 media_expectations.CalleeExpectsSomeVideo();
5577 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5578 }
5579}
5580
Harald Alvestrandbedb6052020-08-20 14:50:10 +02005581TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5582 StopTransceiverRemovesDtlsTransports) {
5583 RTCConfiguration config;
5584 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5585 ConnectFakeSignaling();
5586 auto audio_transceiver_or_error =
5587 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5588 ASSERT_TRUE(audio_transceiver_or_error.ok());
5589 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5590
5591 caller()->CreateAndSetAndSignalOffer();
5592 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5593
5594 audio_transceiver->StopStandard();
5595 caller()->CreateAndSetAndSignalOffer();
5596 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5597 ASSERT_EQ(0U, caller()->pc()->GetTransceivers().size());
5598 EXPECT_EQ(PeerConnectionInterface::kIceGatheringNew,
5599 caller()->pc()->ice_gathering_state());
5600 EXPECT_THAT(caller()->ice_gathering_state_history(),
5601 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
5602 PeerConnectionInterface::kIceGatheringComplete,
5603 PeerConnectionInterface::kIceGatheringNew));
5604}
5605
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005606#ifdef HAVE_SCTP
5607
5608TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5609 EndToEndCallWithBundledSctpDataChannel) {
5610 ASSERT_TRUE(CreatePeerConnectionWrappers());
5611 ConnectFakeSignaling();
5612 caller()->CreateDataChannel();
5613 caller()->AddAudioVideoTracks();
5614 callee()->AddAudioVideoTracks();
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005615 caller()->CreateAndSetAndSignalOffer();
5616 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01005617 ASSERT_EQ_WAIT(SctpTransportState::kConnected,
5618 caller()->pc()->GetSctpTransport()->Information().state(),
5619 kDefaultTimeout);
5620 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5621 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5622}
5623
5624TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5625 EndToEndCallWithDataChannelOnlyConnects) {
5626 ASSERT_TRUE(CreatePeerConnectionWrappers());
5627 ConnectFakeSignaling();
5628 caller()->CreateDataChannel();
5629 caller()->CreateAndSetAndSignalOffer();
5630 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5631 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5632 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5633 ASSERT_TRUE(caller()->data_observer()->IsOpen());
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005634}
5635
Harald Alvestrand2697ac12019-12-16 10:37:04 +01005636TEST_F(PeerConnectionIntegrationTestUnifiedPlan, DataChannelClosesWhenClosed) {
5637 ASSERT_TRUE(CreatePeerConnectionWrappers());
5638 ConnectFakeSignaling();
5639 caller()->CreateDataChannel();
5640 caller()->CreateAndSetAndSignalOffer();
5641 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5642 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
5643 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5644 caller()->data_channel()->Close();
5645 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
5646}
5647
5648TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5649 DataChannelClosesWhenClosedReverse) {
5650 ASSERT_TRUE(CreatePeerConnectionWrappers());
5651 ConnectFakeSignaling();
5652 caller()->CreateDataChannel();
5653 caller()->CreateAndSetAndSignalOffer();
5654 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5655 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
5656 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5657 callee()->data_channel()->Close();
5658 ASSERT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
5659}
5660
5661TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5662 DataChannelClosesWhenPeerConnectionClosed) {
5663 ASSERT_TRUE(CreatePeerConnectionWrappers());
5664 ConnectFakeSignaling();
5665 caller()->CreateDataChannel();
5666 caller()->CreateAndSetAndSignalOffer();
5667 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5668 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
5669 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5670 caller()->pc()->Close();
5671 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
5672}
5673
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005674#endif // HAVE_SCTP
5675
deadbeef1dcb1642017-03-29 21:08:16 -07005676} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01005677} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07005678
5679#endif // if !defined(THREAD_SANITIZER)