blob: 054091e0e866d3f3235492f4e04ba61eb61c9e98 [file] [log] [blame]
deadbeef1dcb1642017-03-29 21:08:16 -07001/*
2 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11// Disable for TSan v2, see
12// https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
13#if !defined(THREAD_SANITIZER)
14
15#include <stdio.h>
16
deadbeef1dcb1642017-03-29 21:08:16 -070017#include <functional>
18#include <list>
19#include <map>
20#include <memory>
21#include <utility>
22#include <vector>
23
Steve Anton64b626b2019-01-28 17:25:26 -080024#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080025#include "api/media_stream_interface.h"
26#include "api/peer_connection_interface.h"
27#include "api/peer_connection_proxy.h"
Danil Chapovalov9da25bd2019-06-20 10:19:42 +020028#include "api/rtc_event_log/rtc_event_log_factory.h"
Steve Anton10542f22019-01-11 09:11:00 -080029#include "api/rtp_receiver_interface.h"
Danil Chapovalov9da25bd2019-06-20 10:19:42 +020030#include "api/task_queue/default_task_queue_factory.h"
Bjorn Mellem175aa2e2018-11-08 11:23:22 -080031#include "api/test/loopback_media_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "api/uma_metrics.h"
Anders Carlsson67537952018-05-03 11:28:29 +020033#include "api/video_codecs/sdp_video_format.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070034#include "call/call.h"
35#include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
Steve Anton10542f22019-01-11 09:11:00 -080036#include "media/engine/fake_webrtc_video_engine.h"
37#include "media/engine/webrtc_media_engine.h"
Danil Chapovalov9da25bd2019-06-20 10:19:42 +020038#include "media/engine/webrtc_media_engine_defaults.h"
Qingsi Wang25ec8882019-11-15 12:33:05 -080039#include "p2p/base/fake_ice_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "p2p/base/mock_async_resolver.h"
41#include "p2p/base/p2p_constants.h"
42#include "p2p/base/port_interface.h"
43#include "p2p/base/test_stun_server.h"
44#include "p2p/base/test_turn_customizer.h"
45#include "p2p/base/test_turn_server.h"
46#include "p2p/client/basic_port_allocator.h"
47#include "pc/dtmf_sender.h"
48#include "pc/local_audio_source.h"
49#include "pc/media_session.h"
50#include "pc/peer_connection.h"
51#include "pc/peer_connection_factory.h"
52#include "pc/rtp_media_utils.h"
53#include "pc/session_description.h"
54#include "pc/test/fake_audio_capture_module.h"
55#include "pc/test/fake_periodic_video_track_source.h"
56#include "pc/test/fake_rtc_certificate_generator.h"
57#include "pc/test/fake_video_track_renderer.h"
58#include "pc/test/mock_peer_connection_observers.h"
Jonas Olssonb75d9e92019-02-22 10:33:29 +010059#include "rtc_base/fake_clock.h"
Qingsi Wangecd30542019-05-22 14:34:56 -070060#include "rtc_base/fake_mdns_responder.h"
Steve Anton10542f22019-01-11 09:11:00 -080061#include "rtc_base/fake_network.h"
62#include "rtc_base/firewall_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020063#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020064#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080065#include "rtc_base/test_certificate_verifier.h"
66#include "rtc_base/time_utils.h"
67#include "rtc_base/virtual_socket_server.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020068#include "system_wrappers/include/metrics.h"
Qingsi Wangc129c352019-04-18 10:41:58 -070069#include "test/field_trial.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020070#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070071
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010072namespace webrtc {
73namespace {
74
75using ::cricket::ContentInfo;
76using ::cricket::StreamParams;
77using ::rtc::SocketAddress;
78using ::testing::_;
Seth Hampson2f0d7022018-02-20 11:54:42 -080079using ::testing::Combine;
Steve Anton64b626b2019-01-28 17:25:26 -080080using ::testing::Contains;
Mirko Bonadeie46f5db2019-03-26 20:14:46 +010081using ::testing::DoAll;
Steve Antonede9ca52017-10-16 13:04:27 -070082using ::testing::ElementsAre;
Qingsi Wang1dac6d82018-12-12 15:28:47 -080083using ::testing::NiceMock;
Steve Anton64b626b2019-01-28 17:25:26 -080084using ::testing::Return;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070085using ::testing::SetArgPointee;
Steve Antonffa6ce42018-11-30 09:26:08 -080086using ::testing::UnorderedElementsAreArray;
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010087using ::testing::Values;
Steve Anton74255ff2018-01-24 18:32:57 -080088using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -070089
90static const int kDefaultTimeout = 10000;
91static const int kMaxWaitForStatsMs = 3000;
92static const int kMaxWaitForActivationMs = 5000;
93static const int kMaxWaitForFramesMs = 10000;
94// Default number of audio/video frames to wait for before considering a test
95// successful.
96static const int kDefaultExpectedAudioFrameCount = 3;
97static const int kDefaultExpectedVideoFrameCount = 3;
98
deadbeef1dcb1642017-03-29 21:08:16 -070099static const char kDataChannelLabel[] = "data_channel";
100
101// SRTP cipher name negotiated by the tests. This must be updated if the
102// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700103static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700104static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
105
Steve Antonede9ca52017-10-16 13:04:27 -0700106static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
107
deadbeef1dcb1642017-03-29 21:08:16 -0700108// Helper function for constructing offer/answer options to initiate an ICE
109// restart.
110PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
111 PeerConnectionInterface::RTCOfferAnswerOptions options;
112 options.ice_restart = true;
113 return options;
114}
115
deadbeefd8ad7882017-04-18 16:01:17 -0700116// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
117// attribute from received SDP, simulating a legacy endpoint.
118void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
119 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800120 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700121 }
122 desc->set_msid_supported(false);
Henrik Boström5b147782018-12-04 11:25:05 +0100123 desc->set_msid_signaling(0);
deadbeefd8ad7882017-04-18 16:01:17 -0700124}
125
Seth Hampson5897a6e2018-04-03 11:16:33 -0700126// Removes all stream information besides the stream ids, simulating an
127// endpoint that only signals a=msid lines to convey stream_ids.
128void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
129 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700130 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700131 std::vector<std::string> stream_ids;
132 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700133 const StreamParams& first_stream =
134 content.media_description()->streams()[0];
135 track_id = first_stream.id;
136 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700137 }
138 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700139 StreamParams new_stream;
140 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700141 new_stream.set_stream_ids(stream_ids);
142 content.media_description()->AddStream(new_stream);
143 }
144}
145
zhihuangf8164932017-05-19 13:09:47 -0700146int FindFirstMediaStatsIndexByKind(
147 const std::string& kind,
148 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
149 media_stats_vec) {
150 for (size_t i = 0; i < media_stats_vec.size(); i++) {
151 if (media_stats_vec[i]->kind.ValueToString() == kind) {
152 return i;
153 }
154 }
155 return -1;
156}
157
deadbeef1dcb1642017-03-29 21:08:16 -0700158class SignalingMessageReceiver {
159 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800160 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700161 virtual void ReceiveIceMessage(const std::string& sdp_mid,
162 int sdp_mline_index,
163 const std::string& msg) = 0;
164
165 protected:
166 SignalingMessageReceiver() {}
167 virtual ~SignalingMessageReceiver() {}
168};
169
170class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
171 public:
172 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
173 : expected_media_type_(media_type) {}
174
175 void OnFirstPacketReceived(cricket::MediaType media_type) override {
176 ASSERT_EQ(expected_media_type_, media_type);
177 first_packet_received_ = true;
178 }
179
180 bool first_packet_received() const { return first_packet_received_; }
181
182 virtual ~MockRtpReceiverObserver() {}
183
184 private:
185 bool first_packet_received_ = false;
186 cricket::MediaType expected_media_type_;
187};
188
189// Helper class that wraps a peer connection, observes it, and can accept
190// signaling messages from another wrapper.
191//
192// Uses a fake network, fake A/V capture, and optionally fake
193// encoders/decoders, though they aren't used by default since they don't
194// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700195// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800196// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700197class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800198 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700199 public:
200 // Different factory methods for convenience.
201 // TODO(deadbeef): Could use the pattern of:
202 //
203 // PeerConnectionWrapper =
204 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
205 //
206 // To reduce some code duplication.
207 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
208 const std::string& debug_name,
209 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
210 rtc::Thread* network_thread,
211 rtc::Thread* worker_thread) {
212 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700213 webrtc::PeerConnectionDependencies dependencies(nullptr);
214 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200215 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800216 worker_thread, nullptr,
Johannes Kron8e8b36a2020-02-07 14:23:45 +0000217 /*media_transport_factory=*/nullptr)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700218 delete client;
219 return nullptr;
220 }
221 return client;
222 }
223
deadbeef2f425aa2017-04-14 10:41:32 -0700224 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
225 return peer_connection_factory_.get();
226 }
227
deadbeef1dcb1642017-03-29 21:08:16 -0700228 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
229
230 // If a signaling message receiver is set (via ConnectFakeSignaling), this
231 // will set the whole offer/answer exchange in motion. Just need to wait for
232 // the signaling state to reach "stable".
233 void CreateAndSetAndSignalOffer() {
Eldar Rello5ab79e62019-10-09 18:29:44 +0300234 auto offer = CreateOfferAndWait();
deadbeef1dcb1642017-03-29 21:08:16 -0700235 ASSERT_NE(nullptr, offer);
236 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
237 }
238
239 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
240 // when a remote offer is received (via fake signaling) and an answer is
241 // generated. By default, uses default options.
242 void SetOfferAnswerOptions(
243 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
244 offer_answer_options_ = options;
245 }
246
247 // Set a callback to be invoked when SDP is received via the fake signaling
248 // channel, which provides an opportunity to munge (modify) the SDP. This is
249 // used to test SDP being applied that a PeerConnection would normally not
250 // generate, but a non-JSEP endpoint might.
251 void SetReceivedSdpMunger(
252 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100253 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700254 }
255
deadbeefc964d0b2017-04-03 10:03:35 -0700256 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700257 // generated.
258 void SetGeneratedSdpMunger(
259 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100260 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700261 }
262
Seth Hampson2f0d7022018-02-20 11:54:42 -0800263 // Set a callback to be invoked when a remote offer is received via the fake
264 // signaling channel. This provides an opportunity to change the
265 // PeerConnection state before an answer is created and sent to the caller.
266 void SetRemoteOfferHandler(std::function<void()> handler) {
267 remote_offer_handler_ = std::move(handler);
268 }
269
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800270 void SetRemoteAsyncResolver(rtc::MockAsyncResolver* resolver) {
271 remote_async_resolver_ = resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700272 }
273
Steve Antonede9ca52017-10-16 13:04:27 -0700274 // Every ICE connection state in order that has been seen by the observer.
275 std::vector<PeerConnectionInterface::IceConnectionState>
276 ice_connection_state_history() const {
277 return ice_connection_state_history_;
278 }
Steve Anton6f25b092017-10-23 09:39:20 -0700279 void clear_ice_connection_state_history() {
280 ice_connection_state_history_.clear();
281 }
Steve Antonede9ca52017-10-16 13:04:27 -0700282
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100283 // Every standardized ICE connection state in order that has been seen by the
284 // observer.
285 std::vector<PeerConnectionInterface::IceConnectionState>
286 standardized_ice_connection_state_history() const {
287 return standardized_ice_connection_state_history_;
288 }
289
Jonas Olsson635474e2018-10-18 15:58:17 +0200290 // Every PeerConnection state in order that has been seen by the observer.
291 std::vector<PeerConnectionInterface::PeerConnectionState>
292 peer_connection_state_history() const {
293 return peer_connection_state_history_;
294 }
295
Steve Antonede9ca52017-10-16 13:04:27 -0700296 // Every ICE gathering state in order that has been seen by the observer.
297 std::vector<PeerConnectionInterface::IceGatheringState>
298 ice_gathering_state_history() const {
299 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700300 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700301 std::vector<cricket::CandidatePairChangeEvent>
302 ice_candidate_pair_change_history() const {
303 return ice_candidate_pair_change_history_;
304 }
deadbeef1dcb1642017-03-29 21:08:16 -0700305
Eldar Rello5ab79e62019-10-09 18:29:44 +0300306 // Every PeerConnection signaling state in order that has been seen by the
307 // observer.
308 std::vector<PeerConnectionInterface::SignalingState>
309 peer_connection_signaling_state_history() const {
310 return peer_connection_signaling_state_history_;
311 }
312
Steve Anton15324772018-01-16 10:26:49 -0800313 void AddAudioVideoTracks() {
314 AddAudioTrack();
315 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700316 }
317
Steve Anton74255ff2018-01-24 18:32:57 -0800318 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
319 return AddTrack(CreateLocalAudioTrack());
320 }
deadbeef1dcb1642017-03-29 21:08:16 -0700321
Steve Anton74255ff2018-01-24 18:32:57 -0800322 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
323 return AddTrack(CreateLocalVideoTrack());
324 }
deadbeef1dcb1642017-03-29 21:08:16 -0700325
326 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200327 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700328 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200329 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700330 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200331 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700332 // TODO(perkj): Test audio source when it is implemented. Currently audio
333 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700334 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700335 source);
336 }
337
338 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200339 webrtc::FakePeriodicVideoSource::Config config;
340 config.timestamp_offset_ms = rtc::TimeMillis();
341 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700342 }
343
344 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200345 CreateLocalVideoTrackWithConfig(
346 webrtc::FakePeriodicVideoSource::Config config) {
347 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700348 }
349
350 rtc::scoped_refptr<webrtc::VideoTrackInterface>
351 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200352 webrtc::FakePeriodicVideoSource::Config config;
353 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200354 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200355 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700356 }
357
Steve Anton74255ff2018-01-24 18:32:57 -0800358 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
359 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800360 const std::vector<std::string>& stream_ids = {}) {
361 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800362 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800363 return result.MoveValue();
364 }
365
366 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
367 cricket::MediaType media_type) {
368 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +0100369 for (const auto& receiver : pc()->GetReceivers()) {
Steve Anton74255ff2018-01-24 18:32:57 -0800370 if (receiver->media_type() == media_type) {
371 receivers.push_back(receiver);
372 }
373 }
374 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700375 }
376
Seth Hampson2f0d7022018-02-20 11:54:42 -0800377 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
378 cricket::MediaType media_type) {
379 for (auto transceiver : pc()->GetTransceivers()) {
380 if (transceiver->receiver()->media_type() == media_type) {
381 return transceiver;
382 }
383 }
384 return nullptr;
385 }
386
deadbeef1dcb1642017-03-29 21:08:16 -0700387 bool SignalingStateStable() {
388 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
389 }
390
391 void CreateDataChannel() { CreateDataChannel(nullptr); }
392
393 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700394 CreateDataChannel(kDataChannelLabel, init);
395 }
396
397 void CreateDataChannel(const std::string& label,
398 const webrtc::DataChannelInit* init) {
399 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700400 ASSERT_TRUE(data_channel_.get() != nullptr);
401 data_observer_.reset(new MockDataChannelObserver(data_channel_));
402 }
403
404 DataChannelInterface* data_channel() { return data_channel_; }
405 const MockDataChannelObserver* data_observer() const {
406 return data_observer_.get();
407 }
408
409 int audio_frames_received() const {
410 return fake_audio_capture_module_->frames_received();
411 }
412
413 // Takes minimum of video frames received for each track.
414 //
415 // Can be used like:
416 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
417 //
418 // To ensure that all video tracks received at least a certain number of
419 // frames.
420 int min_video_frames_received_per_track() const {
421 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200422 if (fake_video_renderers_.empty()) {
423 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700424 }
deadbeef1dcb1642017-03-29 21:08:16 -0700425
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200426 for (const auto& pair : fake_video_renderers_) {
427 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700428 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200429 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700430 }
431
432 // Returns a MockStatsObserver in a state after stats gathering finished,
433 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700434 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700435 webrtc::MediaStreamTrackInterface* track) {
436 rtc::scoped_refptr<MockStatsObserver> observer(
437 new rtc::RefCountedObject<MockStatsObserver>());
438 EXPECT_TRUE(peer_connection_->GetStats(
439 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
440 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
441 return observer;
442 }
443
444 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700445 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
446 return OldGetStatsForTrack(nullptr);
447 }
448
449 // Synchronously gets stats and returns them. If it times out, fails the test
450 // and returns null.
451 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
452 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
453 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
454 peer_connection_->GetStats(callback);
455 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
456 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700457 }
458
459 int rendered_width() {
460 EXPECT_FALSE(fake_video_renderers_.empty());
461 return fake_video_renderers_.empty()
462 ? 0
463 : fake_video_renderers_.begin()->second->width();
464 }
465
466 int rendered_height() {
467 EXPECT_FALSE(fake_video_renderers_.empty());
468 return fake_video_renderers_.empty()
469 ? 0
470 : fake_video_renderers_.begin()->second->height();
471 }
472
473 double rendered_aspect_ratio() {
474 if (rendered_height() == 0) {
475 return 0.0;
476 }
477 return static_cast<double>(rendered_width()) / rendered_height();
478 }
479
480 webrtc::VideoRotation rendered_rotation() {
481 EXPECT_FALSE(fake_video_renderers_.empty());
482 return fake_video_renderers_.empty()
483 ? webrtc::kVideoRotation_0
484 : fake_video_renderers_.begin()->second->rotation();
485 }
486
487 int local_rendered_width() {
488 return local_video_renderer_ ? local_video_renderer_->width() : 0;
489 }
490
491 int local_rendered_height() {
492 return local_video_renderer_ ? local_video_renderer_->height() : 0;
493 }
494
495 double local_rendered_aspect_ratio() {
496 if (local_rendered_height() == 0) {
497 return 0.0;
498 }
499 return static_cast<double>(local_rendered_width()) /
500 local_rendered_height();
501 }
502
503 size_t number_of_remote_streams() {
504 if (!pc()) {
505 return 0;
506 }
507 return pc()->remote_streams()->count();
508 }
509
510 StreamCollectionInterface* remote_streams() const {
511 if (!pc()) {
512 ADD_FAILURE();
513 return nullptr;
514 }
515 return pc()->remote_streams();
516 }
517
518 StreamCollectionInterface* local_streams() {
519 if (!pc()) {
520 ADD_FAILURE();
521 return nullptr;
522 }
523 return pc()->local_streams();
524 }
525
526 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
527 return pc()->signaling_state();
528 }
529
530 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
531 return pc()->ice_connection_state();
532 }
533
Jonas Olsson7a6739e2019-01-15 16:31:55 +0100534 webrtc::PeerConnectionInterface::IceConnectionState
535 standardized_ice_connection_state() {
536 return pc()->standardized_ice_connection_state();
537 }
538
deadbeef1dcb1642017-03-29 21:08:16 -0700539 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
540 return pc()->ice_gathering_state();
541 }
542
543 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
544 // GetReceivers. They're updated automatically when a remote offer/answer
545 // from the fake signaling channel is applied, or when
546 // ResetRtpReceiverObservers below is called.
547 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
548 rtp_receiver_observers() {
549 return rtp_receiver_observers_;
550 }
551
552 void ResetRtpReceiverObservers() {
553 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100554 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
555 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700556 std::unique_ptr<MockRtpReceiverObserver> observer(
557 new MockRtpReceiverObserver(receiver->media_type()));
558 receiver->SetObserver(observer.get());
559 rtp_receiver_observers_.push_back(std::move(observer));
560 }
561 }
562
Qingsi Wangecd30542019-05-22 14:34:56 -0700563 rtc::FakeNetworkManager* network_manager() const {
Steve Antonede9ca52017-10-16 13:04:27 -0700564 return fake_network_manager_.get();
565 }
566 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
567
Qingsi Wang7685e862018-06-11 20:15:46 -0700568 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
569 return event_log_factory_;
570 }
571
Qingsi Wangc129c352019-04-18 10:41:58 -0700572 const cricket::Candidate& last_candidate_gathered() const {
573 return last_candidate_gathered_;
574 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300575 const cricket::IceCandidateErrorEvent& error_event() const {
576 return error_event_;
577 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700578
Qingsi Wangecd30542019-05-22 14:34:56 -0700579 // Sets the mDNS responder for the owned fake network manager and keeps a
580 // reference to the responder.
581 void SetMdnsResponder(
582 std::unique_ptr<webrtc::FakeMdnsResponder> mdns_responder) {
583 RTC_DCHECK(mdns_responder != nullptr);
584 mdns_responder_ = mdns_responder.get();
585 network_manager()->set_mdns_responder(std::move(mdns_responder));
586 }
587
Eldar Rello5ab79e62019-10-09 18:29:44 +0300588 // Returns null on failure.
589 std::unique_ptr<SessionDescriptionInterface> CreateOfferAndWait() {
590 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
591 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
592 pc()->CreateOffer(observer, offer_answer_options_);
593 return WaitForDescriptionFromObserver(observer);
594 }
Eldar Rellod9ebe012020-03-18 20:41:45 +0200595 bool Rollback() {
596 return SetRemoteDescription(
597 webrtc::CreateSessionDescription(SdpType::kRollback, ""));
598 }
Eldar Rello5ab79e62019-10-09 18:29:44 +0300599
deadbeef1dcb1642017-03-29 21:08:16 -0700600 private:
601 explicit PeerConnectionWrapper(const std::string& debug_name)
602 : debug_name_(debug_name) {}
603
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800604 bool Init(
605 const PeerConnectionFactory::Options* options,
606 const PeerConnectionInterface::RTCConfiguration* config,
607 webrtc::PeerConnectionDependencies dependencies,
608 rtc::Thread* network_thread,
609 rtc::Thread* worker_thread,
610 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron8e8b36a2020-02-07 14:23:45 +0000611 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700612 // There's an error in this test code if Init ends up being called twice.
613 RTC_DCHECK(!peer_connection_);
614 RTC_DCHECK(!peer_connection_factory_);
615
616 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700617 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700618
619 std::unique_ptr<cricket::PortAllocator> port_allocator(
620 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700621 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700622 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
623 if (!fake_audio_capture_module_) {
624 return false;
625 }
deadbeef1dcb1642017-03-29 21:08:16 -0700626 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700627
628 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
629 pc_factory_dependencies.network_thread = network_thread;
630 pc_factory_dependencies.worker_thread = worker_thread;
631 pc_factory_dependencies.signaling_thread = signaling_thread;
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200632 pc_factory_dependencies.task_queue_factory =
633 webrtc::CreateDefaultTaskQueueFactory();
634 cricket::MediaEngineDependencies media_deps;
635 media_deps.task_queue_factory =
636 pc_factory_dependencies.task_queue_factory.get();
637 media_deps.adm = fake_audio_capture_module_;
638 webrtc::SetMediaEngineDefaults(&media_deps);
Qingsi Wang7685e862018-06-11 20:15:46 -0700639 pc_factory_dependencies.media_engine =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200640 cricket::CreateMediaEngine(std::move(media_deps));
Qingsi Wang7685e862018-06-11 20:15:46 -0700641 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
642 if (event_log_factory) {
643 event_log_factory_ = event_log_factory.get();
644 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
645 } else {
646 pc_factory_dependencies.event_log_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200647 std::make_unique<webrtc::RtcEventLogFactory>(
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200648 pc_factory_dependencies.task_queue_factory.get());
Qingsi Wang7685e862018-06-11 20:15:46 -0700649 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800650 if (media_transport_factory) {
651 pc_factory_dependencies.media_transport_factory =
652 std::move(media_transport_factory);
653 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700654 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
655 std::move(pc_factory_dependencies));
656
deadbeef1dcb1642017-03-29 21:08:16 -0700657 if (!peer_connection_factory_) {
658 return false;
659 }
660 if (options) {
661 peer_connection_factory_->SetOptions(*options);
662 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800663 if (config) {
664 sdp_semantics_ = config->sdp_semantics;
665 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700666
667 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200668 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700669 return peer_connection_.get() != nullptr;
670 }
671
672 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700673 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700674 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700675 PeerConnectionInterface::RTCConfiguration modified_config;
676 // If |config| is null, this will result in a default configuration being
677 // used.
678 if (config) {
679 modified_config = *config;
680 }
681 // Disable resolution adaptation; we don't want it interfering with the
682 // test results.
683 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
684 // ratios and not specific resolutions, is this even necessary?
685 modified_config.set_cpu_adaptation(false);
686
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700687 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700688 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700689 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700690 }
691
692 void set_signaling_message_receiver(
693 SignalingMessageReceiver* signaling_message_receiver) {
694 signaling_message_receiver_ = signaling_message_receiver;
695 }
696
697 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
698
Steve Antonede9ca52017-10-16 13:04:27 -0700699 void set_signal_ice_candidates(bool signal) {
700 signal_ice_candidates_ = signal;
701 }
702
deadbeef1dcb1642017-03-29 21:08:16 -0700703 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200704 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700705 // Set max frame rate to 10fps to reduce the risk of test flakiness.
706 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200707 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700708
Niels Möller5c7efe72018-05-11 10:34:46 +0200709 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200710 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
711 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700712 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200713 peer_connection_factory_->CreateVideoTrack(
714 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700715 if (!local_video_renderer_) {
716 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
717 }
718 return track;
719 }
720
721 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100722 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800723 std::unique_ptr<SessionDescriptionInterface> desc =
724 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700725 if (received_sdp_munger_) {
726 received_sdp_munger_(desc->description());
727 }
728
729 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
730 // Setting a remote description may have changed the number of receivers,
731 // so reset the receiver observers.
732 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800733 if (remote_offer_handler_) {
734 remote_offer_handler_();
735 }
deadbeef1dcb1642017-03-29 21:08:16 -0700736 auto answer = CreateAnswer();
737 ASSERT_NE(nullptr, answer);
738 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
739 }
740
741 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100742 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800743 std::unique_ptr<SessionDescriptionInterface> desc =
744 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700745 if (received_sdp_munger_) {
746 received_sdp_munger_(desc->description());
747 }
748
749 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
750 // Set the RtpReceiverObserver after receivers are created.
751 ResetRtpReceiverObservers();
752 }
753
754 // Returns null on failure.
deadbeef1dcb1642017-03-29 21:08:16 -0700755 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
756 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
757 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
758 pc()->CreateAnswer(observer, offer_answer_options_);
759 return WaitForDescriptionFromObserver(observer);
760 }
761
762 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100763 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700764 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
765 if (!observer->result()) {
766 return nullptr;
767 }
768 auto description = observer->MoveDescription();
769 if (generated_sdp_munger_) {
770 generated_sdp_munger_(description->description());
771 }
772 return description;
773 }
774
775 // Setting the local description and sending the SDP message over the fake
776 // signaling channel are combined into the same method because the SDP
777 // message needs to be sent as soon as SetLocalDescription finishes, without
778 // waiting for the observer to be called. This ensures that ICE candidates
779 // don't outrace the description.
780 bool SetLocalDescriptionAndSendSdpMessage(
781 std::unique_ptr<SessionDescriptionInterface> desc) {
782 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
783 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100784 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800785 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700786 std::string sdp;
787 EXPECT_TRUE(desc->ToString(&sdp));
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700788 RTC_LOG(LS_INFO) << debug_name_ << ": local SDP contents=\n" << sdp;
deadbeef1dcb1642017-03-29 21:08:16 -0700789 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800790 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
791 RemoveUnusedVideoRenderers();
792 }
deadbeef1dcb1642017-03-29 21:08:16 -0700793 // As mentioned above, we need to send the message immediately after
794 // SetLocalDescription.
795 SendSdpMessage(type, sdp);
796 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
797 return true;
798 }
799
800 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
801 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
802 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100803 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700804 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800805 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
806 RemoveUnusedVideoRenderers();
807 }
deadbeef1dcb1642017-03-29 21:08:16 -0700808 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
809 return observer->result();
810 }
811
Seth Hampson2f0d7022018-02-20 11:54:42 -0800812 // This is a work around to remove unused fake_video_renderers from
813 // transceivers that have either stopped or are no longer receiving.
814 void RemoveUnusedVideoRenderers() {
815 auto transceivers = pc()->GetTransceivers();
816 for (auto& transceiver : transceivers) {
817 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
818 continue;
819 }
820 // Remove fake video renderers from any stopped transceivers.
821 if (transceiver->stopped()) {
822 auto it =
823 fake_video_renderers_.find(transceiver->receiver()->track()->id());
824 if (it != fake_video_renderers_.end()) {
825 fake_video_renderers_.erase(it);
826 }
827 }
828 // Remove fake video renderers from any transceivers that are no longer
829 // receiving.
830 if ((transceiver->current_direction() &&
831 !webrtc::RtpTransceiverDirectionHasRecv(
832 *transceiver->current_direction()))) {
833 auto it =
834 fake_video_renderers_.find(transceiver->receiver()->track()->id());
835 if (it != fake_video_renderers_.end()) {
836 fake_video_renderers_.erase(it);
837 }
838 }
839 }
840 }
841
deadbeef1dcb1642017-03-29 21:08:16 -0700842 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
843 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800844 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700845 if (signaling_delay_ms_ == 0) {
846 RelaySdpMessageIfReceiverExists(type, msg);
847 } else {
848 invoker_.AsyncInvokeDelayed<void>(
849 RTC_FROM_HERE, rtc::Thread::Current(),
850 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
851 this, type, msg),
852 signaling_delay_ms_);
853 }
854 }
855
Steve Antona3a92c22017-12-07 10:27:41 -0800856 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700857 if (signaling_message_receiver_) {
858 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
859 }
860 }
861
862 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
863 // default).
864 void SendIceMessage(const std::string& sdp_mid,
865 int sdp_mline_index,
866 const std::string& msg) {
867 if (signaling_delay_ms_ == 0) {
868 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
869 } else {
870 invoker_.AsyncInvokeDelayed<void>(
871 RTC_FROM_HERE, rtc::Thread::Current(),
872 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
873 this, sdp_mid, sdp_mline_index, msg),
874 signaling_delay_ms_);
875 }
876 }
877
878 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
879 int sdp_mline_index,
880 const std::string& msg) {
881 if (signaling_message_receiver_) {
882 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
883 msg);
884 }
885 }
886
887 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800888 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
889 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700890 HandleIncomingOffer(msg);
891 } else {
892 HandleIncomingAnswer(msg);
893 }
894 }
895
896 void ReceiveIceMessage(const std::string& sdp_mid,
897 int sdp_mline_index,
898 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100899 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700900 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
901 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
902 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
903 }
904
905 // PeerConnectionObserver callbacks.
906 void OnSignalingChange(
907 webrtc::PeerConnectionInterface::SignalingState new_state) override {
908 EXPECT_EQ(pc()->signaling_state(), new_state);
Eldar Rello5ab79e62019-10-09 18:29:44 +0300909 peer_connection_signaling_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700910 }
Steve Anton15324772018-01-16 10:26:49 -0800911 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
912 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
913 streams) override {
914 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
915 rtc::scoped_refptr<VideoTrackInterface> video_track(
916 static_cast<VideoTrackInterface*>(receiver->track().get()));
917 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700918 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800919 fake_video_renderers_[video_track->id()] =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200920 std::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700921 }
922 }
Steve Anton15324772018-01-16 10:26:49 -0800923 void OnRemoveTrack(
924 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
925 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
926 auto it = fake_video_renderers_.find(receiver->track()->id());
927 RTC_DCHECK(it != fake_video_renderers_.end());
928 fake_video_renderers_.erase(it);
929 }
930 }
deadbeef1dcb1642017-03-29 21:08:16 -0700931 void OnRenegotiationNeeded() override {}
932 void OnIceConnectionChange(
933 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
934 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700935 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700936 }
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100937 void OnStandardizedIceConnectionChange(
938 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
939 standardized_ice_connection_state_history_.push_back(new_state);
940 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200941 void OnConnectionChange(
942 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
943 peer_connection_state_history_.push_back(new_state);
944 }
945
deadbeef1dcb1642017-03-29 21:08:16 -0700946 void OnIceGatheringChange(
947 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700948 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700949 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700950 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700951
952 void OnIceSelectedCandidatePairChanged(
953 const cricket::CandidatePairChangeEvent& event) {
954 ice_candidate_pair_change_history_.push_back(event);
955 }
Alex Drake43faee02019-08-12 16:27:34 -0700956
deadbeef1dcb1642017-03-29 21:08:16 -0700957 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100958 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700959
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800960 if (remote_async_resolver_) {
961 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800962 if (local_candidate.address().IsUnresolvedIP()) {
963 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
964 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700965 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800966 local_candidate.address().hostname());
967 RTC_DCHECK(!resolved_ip.IsNil());
968 resolved_addr.SetResolvedIP(resolved_ip);
969 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
970 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
971 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700972 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700973 }
974
deadbeef1dcb1642017-03-29 21:08:16 -0700975 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800976 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700977 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700978 // Remote party may be deleted.
979 return;
980 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800981 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700982 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700983 }
Eldar Rello0095d372019-12-02 22:22:07 +0200984 void OnIceCandidateError(const std::string& address,
985 int port,
Eldar Relloda13ea22019-06-01 12:23:43 +0300986 const std::string& url,
987 int error_code,
988 const std::string& error_text) override {
Eldar Rello0095d372019-12-02 22:22:07 +0200989 error_event_ = cricket::IceCandidateErrorEvent(address, port, url,
Eldar Relloda13ea22019-06-01 12:23:43 +0300990 error_code, error_text);
991 }
deadbeef1dcb1642017-03-29 21:08:16 -0700992 void OnDataChannel(
993 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100994 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700995 data_channel_ = data_channel;
996 data_observer_.reset(new MockDataChannelObserver(data_channel));
997 }
998
deadbeef1dcb1642017-03-29 21:08:16 -0700999 std::string debug_name_;
1000
1001 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -07001002 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
1003 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001004
1005 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
1006 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
1007 peer_connection_factory_;
1008
Steve Antonede9ca52017-10-16 13:04:27 -07001009 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -07001010 // Needed to keep track of number of frames sent.
1011 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1012 // Needed to keep track of number of frames received.
1013 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1014 fake_video_renderers_;
1015 // Needed to ensure frames aren't received for removed tracks.
1016 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1017 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001018
1019 // For remote peer communication.
1020 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1021 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001022 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001023 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001024 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001025
Niels Möller5c7efe72018-05-11 10:34:46 +02001026 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001027 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001028 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1029 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001030 // |local_video_renderer_| attached to the first created local video track.
1031 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1032
Seth Hampson2f0d7022018-02-20 11:54:42 -08001033 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001034 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1035 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1036 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001037 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001038 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001039 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1040 std::unique_ptr<MockDataChannelObserver> data_observer_;
1041
1042 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1043
Steve Antonede9ca52017-10-16 13:04:27 -07001044 std::vector<PeerConnectionInterface::IceConnectionState>
1045 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001046 std::vector<PeerConnectionInterface::IceConnectionState>
1047 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001048 std::vector<PeerConnectionInterface::PeerConnectionState>
1049 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001050 std::vector<PeerConnectionInterface::IceGatheringState>
1051 ice_gathering_state_history_;
Alex Drake00c7ecf2019-08-06 10:54:47 -07001052 std::vector<cricket::CandidatePairChangeEvent>
1053 ice_candidate_pair_change_history_;
Eldar Rello5ab79e62019-10-09 18:29:44 +03001054 std::vector<PeerConnectionInterface::SignalingState>
1055 peer_connection_signaling_state_history_;
Qingsi Wang7685e862018-06-11 20:15:46 -07001056 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1057
deadbeef1dcb1642017-03-29 21:08:16 -07001058 rtc::AsyncInvoker invoker_;
1059
Seth Hampson2f0d7022018-02-20 11:54:42 -08001060 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001061};
1062
Elad Alon99c3fe52017-10-13 16:29:40 +02001063class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1064 public:
1065 virtual ~MockRtcEventLogOutput() = default;
1066 MOCK_CONST_METHOD0(IsActive, bool());
1067 MOCK_METHOD1(Write, bool(const std::string&));
1068};
1069
Seth Hampson2f0d7022018-02-20 11:54:42 -08001070// This helper object is used for both specifying how many audio/video frames
1071// are expected to be received for a caller/callee. It provides helper functions
1072// to specify these expectations. The object initially starts in a state of no
1073// expectations.
1074class MediaExpectations {
1075 public:
1076 enum ExpectFrames {
1077 kExpectSomeFrames,
1078 kExpectNoFrames,
1079 kNoExpectation,
1080 };
1081
1082 void ExpectBidirectionalAudioAndVideo() {
1083 ExpectBidirectionalAudio();
1084 ExpectBidirectionalVideo();
1085 }
1086
1087 void ExpectBidirectionalAudio() {
1088 CallerExpectsSomeAudio();
1089 CalleeExpectsSomeAudio();
1090 }
1091
1092 void ExpectNoAudio() {
1093 CallerExpectsNoAudio();
1094 CalleeExpectsNoAudio();
1095 }
1096
1097 void ExpectBidirectionalVideo() {
1098 CallerExpectsSomeVideo();
1099 CalleeExpectsSomeVideo();
1100 }
1101
1102 void ExpectNoVideo() {
1103 CallerExpectsNoVideo();
1104 CalleeExpectsNoVideo();
1105 }
1106
1107 void CallerExpectsSomeAudioAndVideo() {
1108 CallerExpectsSomeAudio();
1109 CallerExpectsSomeVideo();
1110 }
1111
1112 void CalleeExpectsSomeAudioAndVideo() {
1113 CalleeExpectsSomeAudio();
1114 CalleeExpectsSomeVideo();
1115 }
1116
1117 // Caller's audio functions.
1118 void CallerExpectsSomeAudio(
1119 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1120 caller_audio_expectation_ = kExpectSomeFrames;
1121 caller_audio_frames_expected_ = expected_audio_frames;
1122 }
1123
1124 void CallerExpectsNoAudio() {
1125 caller_audio_expectation_ = kExpectNoFrames;
1126 caller_audio_frames_expected_ = 0;
1127 }
1128
1129 // Caller's video functions.
1130 void CallerExpectsSomeVideo(
1131 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1132 caller_video_expectation_ = kExpectSomeFrames;
1133 caller_video_frames_expected_ = expected_video_frames;
1134 }
1135
1136 void CallerExpectsNoVideo() {
1137 caller_video_expectation_ = kExpectNoFrames;
1138 caller_video_frames_expected_ = 0;
1139 }
1140
1141 // Callee's audio functions.
1142 void CalleeExpectsSomeAudio(
1143 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1144 callee_audio_expectation_ = kExpectSomeFrames;
1145 callee_audio_frames_expected_ = expected_audio_frames;
1146 }
1147
1148 void CalleeExpectsNoAudio() {
1149 callee_audio_expectation_ = kExpectNoFrames;
1150 callee_audio_frames_expected_ = 0;
1151 }
1152
1153 // Callee's video functions.
1154 void CalleeExpectsSomeVideo(
1155 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1156 callee_video_expectation_ = kExpectSomeFrames;
1157 callee_video_frames_expected_ = expected_video_frames;
1158 }
1159
1160 void CalleeExpectsNoVideo() {
1161 callee_video_expectation_ = kExpectNoFrames;
1162 callee_video_frames_expected_ = 0;
1163 }
1164
1165 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1166 ExpectFrames caller_video_expectation_ = kNoExpectation;
1167 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1168 ExpectFrames callee_video_expectation_ = kNoExpectation;
1169 int caller_audio_frames_expected_ = 0;
1170 int caller_video_frames_expected_ = 0;
1171 int callee_audio_frames_expected_ = 0;
1172 int callee_video_frames_expected_ = 0;
1173};
1174
Qingsi Wang25ec8882019-11-15 12:33:05 -08001175class MockIceTransport : public webrtc::IceTransportInterface {
1176 public:
1177 MockIceTransport(const std::string& name, int component)
1178 : internal_(std::make_unique<cricket::FakeIceTransport>(
1179 name,
1180 component,
1181 nullptr /* network_thread */)) {}
1182 ~MockIceTransport() = default;
1183 cricket::IceTransportInternal* internal() { return internal_.get(); }
1184
1185 private:
1186 std::unique_ptr<cricket::FakeIceTransport> internal_;
1187};
1188
1189class MockIceTransportFactory : public IceTransportFactory {
1190 public:
1191 ~MockIceTransportFactory() override = default;
1192 rtc::scoped_refptr<IceTransportInterface> CreateIceTransport(
1193 const std::string& transport_name,
1194 int component,
1195 IceTransportInit init) {
1196 RecordIceTransportCreated();
1197 return new rtc::RefCountedObject<MockIceTransport>(transport_name,
1198 component);
1199 }
1200 MOCK_METHOD0(RecordIceTransportCreated, void());
1201};
1202
deadbeef1dcb1642017-03-29 21:08:16 -07001203// Tests two PeerConnections connecting to each other end-to-end, using a
1204// virtual network, fake A/V capture and fake encoder/decoders. The
1205// PeerConnections share the threads/socket servers, but use separate versions
1206// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001207class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001208 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001209 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1210 : sdp_semantics_(sdp_semantics),
1211 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001212 fss_(new rtc::FirewallSocketServer(ss_.get())),
1213 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001214 worker_thread_(rtc::Thread::Create()),
1215 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001216 network_thread_->SetName("PCNetworkThread", this);
1217 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001218 RTC_CHECK(network_thread_->Start());
1219 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001220 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001221 }
1222
Seth Hampson2f0d7022018-02-20 11:54:42 -08001223 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001224 // The PeerConnections should deleted before the TurnCustomizers.
1225 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1226 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1227 // that the TurnCustomizer outlives the life of the PeerConnection or else
1228 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001229 if (caller_) {
1230 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001231 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001232 }
1233 if (callee_) {
1234 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001235 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001236 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001237
1238 // If turn servers were created for the test they need to be destroyed on
1239 // the network thread.
1240 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1241 turn_servers_.clear();
1242 turn_customizers_.clear();
1243 });
deadbeef1dcb1642017-03-29 21:08:16 -07001244 }
1245
1246 bool SignalingStateStable() {
1247 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1248 }
1249
deadbeef71452802017-05-07 17:21:01 -07001250 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001251 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1252 // are connected. This is an important distinction. Once we have separate
1253 // ICE and DTLS state, this check needs to use the DTLS state.
1254 return (callee()->ice_connection_state() ==
1255 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1256 callee()->ice_connection_state() ==
1257 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1258 (caller()->ice_connection_state() ==
1259 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1260 caller()->ice_connection_state() ==
1261 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001262 }
1263
Qingsi Wang7685e862018-06-11 20:15:46 -07001264 // When |event_log_factory| is null, the default implementation of the event
1265 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001266 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1267 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001268 const PeerConnectionFactory::Options* options,
1269 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001270 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001271 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001272 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001273 RTCConfiguration modified_config;
1274 if (config) {
1275 modified_config = *config;
1276 }
Steve Anton3acffc32018-04-12 17:21:03 -07001277 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001278 if (!dependencies.cert_generator) {
1279 dependencies.cert_generator =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001280 std::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001281 }
1282 std::unique_ptr<PeerConnectionWrapper> client(
1283 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001284
Niels Möllerf06f9232018-08-07 12:32:18 +02001285 if (!client->Init(options, &modified_config, std::move(dependencies),
1286 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001287 std::move(event_log_factory),
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001288 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001289 return nullptr;
1290 }
1291 return client;
1292 }
1293
Qingsi Wang7685e862018-06-11 20:15:46 -07001294 std::unique_ptr<PeerConnectionWrapper>
1295 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1296 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001297 const PeerConnectionFactory::Options* options,
1298 const RTCConfiguration* config,
1299 webrtc::PeerConnectionDependencies dependencies) {
1300 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1301 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001302 return CreatePeerConnectionWrapper(debug_name, options, config,
1303 std::move(dependencies),
1304 std::move(event_log_factory),
1305 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001306 }
1307
deadbeef1dcb1642017-03-29 21:08:16 -07001308 bool CreatePeerConnectionWrappers() {
1309 return CreatePeerConnectionWrappersWithConfig(
1310 PeerConnectionInterface::RTCConfiguration(),
1311 PeerConnectionInterface::RTCConfiguration());
1312 }
1313
Steve Anton3acffc32018-04-12 17:21:03 -07001314 bool CreatePeerConnectionWrappersWithSdpSemantics(
1315 SdpSemantics caller_semantics,
1316 SdpSemantics callee_semantics) {
1317 // Can't specify the sdp_semantics in the passed-in configuration since it
1318 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1319 // stored in sdp_semantics_. So get around this by modifying the instance
1320 // variable before calling CreatePeerConnectionWrapper for the caller and
1321 // callee PeerConnections.
1322 SdpSemantics original_semantics = sdp_semantics_;
1323 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001324 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001325 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001326 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001327 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001328 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001329 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001330 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001331 sdp_semantics_ = original_semantics;
1332 return caller_ && callee_;
1333 }
1334
deadbeef1dcb1642017-03-29 21:08:16 -07001335 bool CreatePeerConnectionWrappersWithConfig(
1336 const PeerConnectionInterface::RTCConfiguration& caller_config,
1337 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001338 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001339 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001340 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001341 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001342 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001343 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001344 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001345 /*media_transport_factory=*/nullptr);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001346 return caller_ && callee_;
1347 }
1348
1349 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1350 const PeerConnectionInterface::RTCConfiguration& caller_config,
1351 const PeerConnectionInterface::RTCConfiguration& callee_config,
1352 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1353 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001354 caller_ =
1355 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1356 webrtc::PeerConnectionDependencies(nullptr),
1357 nullptr, std::move(caller_factory));
1358 callee_ =
1359 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1360 webrtc::PeerConnectionDependencies(nullptr),
1361 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001362 return caller_ && callee_;
1363 }
1364
1365 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1366 const PeerConnectionInterface::RTCConfiguration& caller_config,
1367 webrtc::PeerConnectionDependencies caller_dependencies,
1368 const PeerConnectionInterface::RTCConfiguration& callee_config,
1369 webrtc::PeerConnectionDependencies callee_dependencies) {
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001370 caller_ =
1371 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1372 std::move(caller_dependencies), nullptr,
1373 /*media_transport_factory=*/nullptr);
1374 callee_ =
1375 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1376 std::move(callee_dependencies), nullptr,
1377 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001378 return caller_ && callee_;
1379 }
1380
1381 bool CreatePeerConnectionWrappersWithOptions(
1382 const PeerConnectionFactory::Options& caller_options,
1383 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001384 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001385 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001386 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001387 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001388 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001389 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001390 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001391 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001392 return caller_ && callee_;
1393 }
1394
1395 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1396 PeerConnectionInterface::RTCConfiguration default_config;
1397 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001398 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001399 webrtc::PeerConnectionDependencies(nullptr));
1400 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001401 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001402 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001403 return caller_ && callee_;
1404 }
1405
Seth Hampson2f0d7022018-02-20 11:54:42 -08001406 std::unique_ptr<PeerConnectionWrapper>
1407 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001408 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1409 new FakeRTCCertificateGenerator());
1410 cert_generator->use_alternate_key();
1411
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001412 webrtc::PeerConnectionDependencies dependencies(nullptr);
1413 dependencies.cert_generator = std::move(cert_generator);
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001414 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
1415 std::move(dependencies), nullptr,
1416 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001417 }
1418
Seth Hampsonaed71642018-06-11 07:41:32 -07001419 cricket::TestTurnServer* CreateTurnServer(
1420 rtc::SocketAddress internal_address,
1421 rtc::SocketAddress external_address,
1422 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1423 const std::string& common_name = "test turn server") {
1424 rtc::Thread* thread = network_thread();
1425 std::unique_ptr<cricket::TestTurnServer> turn_server =
1426 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1427 RTC_FROM_HERE,
1428 [thread, internal_address, external_address, type, common_name] {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001429 return std::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001430 thread, internal_address, external_address, type,
1431 /*ignore_bad_certs=*/true, common_name);
1432 });
1433 turn_servers_.push_back(std::move(turn_server));
1434 // Interactions with the turn server should be done on the network thread.
1435 return turn_servers_.back().get();
1436 }
1437
1438 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1439 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1440 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1441 RTC_FROM_HERE,
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001442 [] { return std::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001443 turn_customizers_.push_back(std::move(turn_customizer));
1444 // Interactions with the turn customizer should be done on the network
1445 // thread.
1446 return turn_customizers_.back().get();
1447 }
1448
1449 // Checks that the function counters for a TestTurnCustomizer are greater than
1450 // 0.
1451 void ExpectTurnCustomizerCountersIncremented(
1452 cricket::TestTurnCustomizer* turn_customizer) {
1453 unsigned int allow_channel_data_counter =
1454 network_thread()->Invoke<unsigned int>(
1455 RTC_FROM_HERE, [turn_customizer] {
1456 return turn_customizer->allow_channel_data_cnt_;
1457 });
1458 EXPECT_GT(allow_channel_data_counter, 0u);
1459 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1460 RTC_FROM_HERE,
1461 [turn_customizer] { return turn_customizer->modify_cnt_; });
1462 EXPECT_GT(modify_counter, 0u);
1463 }
1464
deadbeef1dcb1642017-03-29 21:08:16 -07001465 // Once called, SDP blobs and ICE candidates will be automatically signaled
1466 // between PeerConnections.
1467 void ConnectFakeSignaling() {
1468 caller_->set_signaling_message_receiver(callee_.get());
1469 callee_->set_signaling_message_receiver(caller_.get());
1470 }
1471
Steve Antonede9ca52017-10-16 13:04:27 -07001472 // Once called, SDP blobs will be automatically signaled between
1473 // PeerConnections. Note that ICE candidates will not be signaled unless they
1474 // are in the exchanged SDP blobs.
1475 void ConnectFakeSignalingForSdpOnly() {
1476 ConnectFakeSignaling();
1477 SetSignalIceCandidates(false);
1478 }
1479
deadbeef1dcb1642017-03-29 21:08:16 -07001480 void SetSignalingDelayMs(int delay_ms) {
1481 caller_->set_signaling_delay_ms(delay_ms);
1482 callee_->set_signaling_delay_ms(delay_ms);
1483 }
1484
Steve Antonede9ca52017-10-16 13:04:27 -07001485 void SetSignalIceCandidates(bool signal) {
1486 caller_->set_signal_ice_candidates(signal);
1487 callee_->set_signal_ice_candidates(signal);
1488 }
1489
deadbeef1dcb1642017-03-29 21:08:16 -07001490 // Messages may get lost on the unreliable DataChannel, so we send multiple
1491 // times to avoid test flakiness.
1492 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1493 const std::string& data,
1494 int retries) {
1495 for (int i = 0; i < retries; ++i) {
1496 dc->Send(DataBuffer(data));
1497 }
1498 }
1499
1500 rtc::Thread* network_thread() { return network_thread_.get(); }
1501
1502 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1503
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001504 webrtc::MediaTransportPair* loopback_media_transports() {
1505 return &loopback_media_transports_;
1506 }
1507
deadbeef1dcb1642017-03-29 21:08:16 -07001508 PeerConnectionWrapper* caller() { return caller_.get(); }
1509
1510 // Set the |caller_| to the |wrapper| passed in and return the
1511 // original |caller_|.
1512 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1513 PeerConnectionWrapper* wrapper) {
1514 PeerConnectionWrapper* old = caller_.release();
1515 caller_.reset(wrapper);
1516 return old;
1517 }
1518
1519 PeerConnectionWrapper* callee() { return callee_.get(); }
1520
1521 // Set the |callee_| to the |wrapper| passed in and return the
1522 // original |callee_|.
1523 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1524 PeerConnectionWrapper* wrapper) {
1525 PeerConnectionWrapper* old = callee_.release();
1526 callee_.reset(wrapper);
1527 return old;
1528 }
1529
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001530 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1531 network_thread()->Invoke<void>(
1532 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1533 caller()->port_allocator(), caller_flags));
1534 network_thread()->Invoke<void>(
1535 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1536 callee()->port_allocator(), callee_flags));
1537 }
1538
Steve Antonede9ca52017-10-16 13:04:27 -07001539 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1540
Seth Hampson2f0d7022018-02-20 11:54:42 -08001541 // Expects the provided number of new frames to be received within
1542 // kMaxWaitForFramesMs. The new expected frames are specified in
1543 // |media_expectations|. Returns false if any of the expectations were
1544 // not met.
1545 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1546 // First initialize the expected frame counts based upon the current
1547 // frame count.
1548 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1549 if (media_expectations.caller_audio_expectation_ ==
1550 MediaExpectations::kExpectSomeFrames) {
1551 total_caller_audio_frames_expected +=
1552 media_expectations.caller_audio_frames_expected_;
1553 }
1554 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001555 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001556 if (media_expectations.caller_video_expectation_ ==
1557 MediaExpectations::kExpectSomeFrames) {
1558 total_caller_video_frames_expected +=
1559 media_expectations.caller_video_frames_expected_;
1560 }
1561 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1562 if (media_expectations.callee_audio_expectation_ ==
1563 MediaExpectations::kExpectSomeFrames) {
1564 total_callee_audio_frames_expected +=
1565 media_expectations.callee_audio_frames_expected_;
1566 }
1567 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001568 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001569 if (media_expectations.callee_video_expectation_ ==
1570 MediaExpectations::kExpectSomeFrames) {
1571 total_callee_video_frames_expected +=
1572 media_expectations.callee_video_frames_expected_;
1573 }
deadbeef1dcb1642017-03-29 21:08:16 -07001574
Seth Hampson2f0d7022018-02-20 11:54:42 -08001575 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001576 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001577 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001578 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001579 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001580 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001581 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001582 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001583 total_callee_video_frames_expected,
1584 kMaxWaitForFramesMs);
1585 bool expectations_correct =
1586 caller()->audio_frames_received() >=
1587 total_caller_audio_frames_expected &&
1588 caller()->min_video_frames_received_per_track() >=
1589 total_caller_video_frames_expected &&
1590 callee()->audio_frames_received() >=
1591 total_callee_audio_frames_expected &&
1592 callee()->min_video_frames_received_per_track() >=
1593 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001594
Seth Hampson2f0d7022018-02-20 11:54:42 -08001595 // After the combined wait, print out a more detailed message upon
1596 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001597 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001598 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001599 EXPECT_GE(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 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001602 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001603 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001604 total_callee_video_frames_expected);
1605
1606 // We want to make sure nothing unexpected was received.
1607 if (media_expectations.caller_audio_expectation_ ==
1608 MediaExpectations::kExpectNoFrames) {
1609 EXPECT_EQ(caller()->audio_frames_received(),
1610 total_caller_audio_frames_expected);
1611 if (caller()->audio_frames_received() !=
1612 total_caller_audio_frames_expected) {
1613 expectations_correct = false;
1614 }
1615 }
1616 if (media_expectations.caller_video_expectation_ ==
1617 MediaExpectations::kExpectNoFrames) {
1618 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1619 total_caller_video_frames_expected);
1620 if (caller()->min_video_frames_received_per_track() !=
1621 total_caller_video_frames_expected) {
1622 expectations_correct = false;
1623 }
1624 }
1625 if (media_expectations.callee_audio_expectation_ ==
1626 MediaExpectations::kExpectNoFrames) {
1627 EXPECT_EQ(callee()->audio_frames_received(),
1628 total_callee_audio_frames_expected);
1629 if (callee()->audio_frames_received() !=
1630 total_callee_audio_frames_expected) {
1631 expectations_correct = false;
1632 }
1633 }
1634 if (media_expectations.callee_video_expectation_ ==
1635 MediaExpectations::kExpectNoFrames) {
1636 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1637 total_callee_video_frames_expected);
1638 if (callee()->min_video_frames_received_per_track() !=
1639 total_callee_video_frames_expected) {
1640 expectations_correct = false;
1641 }
1642 }
1643 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001644 }
1645
Steve Antond91969e2019-05-30 12:27:03 -07001646 void ClosePeerConnections() {
1647 caller()->pc()->Close();
1648 callee()->pc()->Close();
1649 }
1650
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001651 void TestNegotiatedCipherSuite(
1652 const PeerConnectionFactory::Options& caller_options,
1653 const PeerConnectionFactory::Options& callee_options,
1654 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001655 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1656 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001657 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001658 caller()->AddAudioVideoTracks();
1659 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001660 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001661 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001662 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001663 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001664 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01001665 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
1666 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1667 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001668 }
1669
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001670 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1671 bool remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001672 bool aes_ctr_enabled,
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001673 int expected_cipher_suite) {
1674 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001675 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1676 local_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001677 caller_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1678 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001679 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001680 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1681 remote_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001682 callee_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1683 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001684 TestNegotiatedCipherSuite(caller_options, callee_options,
1685 expected_cipher_suite);
1686 }
1687
Seth Hampson2f0d7022018-02-20 11:54:42 -08001688 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001689 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001690
deadbeef1dcb1642017-03-29 21:08:16 -07001691 private:
1692 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001693 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001694 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001695 // |network_thread_| and |worker_thread_| are used by both
1696 // |caller_| and |callee_| so they must be destroyed
1697 // later.
1698 std::unique_ptr<rtc::Thread> network_thread_;
1699 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001700 // The turn servers and turn customizers should be accessed & deleted on the
1701 // network thread to avoid a race with the socket read/write that occurs
1702 // on the network thread.
1703 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1704 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001705 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001706 std::unique_ptr<PeerConnectionWrapper> caller_;
1707 std::unique_ptr<PeerConnectionWrapper> callee_;
1708};
1709
Seth Hampson2f0d7022018-02-20 11:54:42 -08001710class PeerConnectionIntegrationTest
1711 : public PeerConnectionIntegrationBaseTest,
1712 public ::testing::WithParamInterface<SdpSemantics> {
1713 protected:
1714 PeerConnectionIntegrationTest()
1715 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1716};
1717
Yves Gerey100fe632020-01-17 19:15:53 +01001718// Fake clock must be set before threads are started to prevent race on
1719// Set/GetClockForTesting().
1720// To achieve that, multiple inheritance is used as a mixin pattern
1721// where order of construction is finely controlled.
1722// This also ensures peerconnection is closed before switching back to non-fake
1723// clock, avoiding other races and DCHECK failures such as in rtp_sender.cc.
1724class FakeClockForTest : public rtc::ScopedFakeClock {
1725 protected:
1726 FakeClockForTest() {
1727 // Some things use a time of "0" as a special value, so we need to start out
1728 // the fake clock at a nonzero time.
1729 // TODO(deadbeef): Fix this.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001730 AdvanceTime(webrtc::TimeDelta::Seconds(1));
Yves Gerey100fe632020-01-17 19:15:53 +01001731 }
1732
1733 // Explicit handle.
1734 ScopedFakeClock& FakeClock() { return *this; }
1735};
1736
1737// Ensure FakeClockForTest is constructed first (see class for rationale).
1738class PeerConnectionIntegrationTestWithFakeClock
1739 : public FakeClockForTest,
1740 public PeerConnectionIntegrationTest {};
1741
Seth Hampson2f0d7022018-02-20 11:54:42 -08001742class PeerConnectionIntegrationTestPlanB
1743 : public PeerConnectionIntegrationBaseTest {
1744 protected:
1745 PeerConnectionIntegrationTestPlanB()
1746 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1747};
1748
1749class PeerConnectionIntegrationTestUnifiedPlan
1750 : public PeerConnectionIntegrationBaseTest {
1751 protected:
1752 PeerConnectionIntegrationTestUnifiedPlan()
1753 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1754};
1755
deadbeef1dcb1642017-03-29 21:08:16 -07001756// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1757// includes testing that the callback is invoked if an observer is connected
1758// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001759TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001760 RtpReceiverObserverOnFirstPacketReceived) {
1761 ASSERT_TRUE(CreatePeerConnectionWrappers());
1762 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001763 caller()->AddAudioVideoTracks();
1764 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001765 // Start offer/answer exchange and wait for it to complete.
1766 caller()->CreateAndSetAndSignalOffer();
1767 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1768 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001769 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1770 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001771 // Wait for all "first packet received" callbacks to be fired.
1772 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001773 absl::c_all_of(caller()->rtp_receiver_observers(),
1774 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1775 return o->first_packet_received();
1776 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001777 kMaxWaitForFramesMs);
1778 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001779 absl::c_all_of(callee()->rtp_receiver_observers(),
1780 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1781 return o->first_packet_received();
1782 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001783 kMaxWaitForFramesMs);
1784 // If new observers are set after the first packet was already received, the
1785 // callback should still be invoked.
1786 caller()->ResetRtpReceiverObservers();
1787 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001788 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1789 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001790 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001791 absl::c_all_of(caller()->rtp_receiver_observers(),
1792 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1793 return o->first_packet_received();
1794 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001795 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001796 absl::c_all_of(callee()->rtp_receiver_observers(),
1797 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1798 return o->first_packet_received();
1799 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001800}
1801
1802class DummyDtmfObserver : public DtmfSenderObserverInterface {
1803 public:
1804 DummyDtmfObserver() : completed_(false) {}
1805
1806 // Implements DtmfSenderObserverInterface.
1807 void OnToneChange(const std::string& tone) override {
1808 tones_.push_back(tone);
1809 if (tone.empty()) {
1810 completed_ = true;
1811 }
1812 }
1813
1814 const std::vector<std::string>& tones() const { return tones_; }
1815 bool completed() const { return completed_; }
1816
1817 private:
1818 bool completed_;
1819 std::vector<std::string> tones_;
1820};
1821
1822// Assumes |sender| already has an audio track added and the offer/answer
1823// exchange is done.
1824void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1825 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001826 // We should be able to get a DTMF sender from the local sender.
1827 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1828 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1829 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001830 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001831 dtmf_sender->RegisterObserver(&observer);
1832
1833 // Test the DtmfSender object just created.
1834 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1835 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1836
1837 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1838 std::vector<std::string> tones = {"1", "a", ""};
1839 EXPECT_EQ(tones, observer.tones());
1840 dtmf_sender->UnregisterObserver();
1841 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1842}
1843
1844// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1845// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001846TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001847 ASSERT_TRUE(CreatePeerConnectionWrappers());
1848 ConnectFakeSignaling();
1849 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001850 caller()->AddAudioTrack();
1851 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001852 caller()->CreateAndSetAndSignalOffer();
1853 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001854 // DTLS must finish before the DTMF sender can be used reliably.
1855 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001856 TestDtmfFromSenderToReceiver(caller(), callee());
1857 TestDtmfFromSenderToReceiver(callee(), caller());
1858}
1859
1860// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1861// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001862TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001863 ASSERT_TRUE(CreatePeerConnectionWrappers());
1864 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001865
deadbeef1dcb1642017-03-29 21:08:16 -07001866 // Do normal offer/answer and wait for some frames to be received in each
1867 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001868 caller()->AddAudioVideoTracks();
1869 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001870 caller()->CreateAndSetAndSignalOffer();
1871 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001872 MediaExpectations media_expectations;
1873 media_expectations.ExpectBidirectionalAudioAndVideo();
1874 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001875 EXPECT_METRIC_LE(
1876 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1877 webrtc::kEnumCounterKeyProtocolDtls));
1878 EXPECT_METRIC_EQ(
1879 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1880 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001881}
1882
1883// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001884TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001885 PeerConnectionInterface::RTCConfiguration sdes_config;
1886 sdes_config.enable_dtls_srtp.emplace(false);
1887 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1888 ConnectFakeSignaling();
1889
1890 // Do normal offer/answer and wait for some frames to be received in each
1891 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001892 caller()->AddAudioVideoTracks();
1893 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001894 caller()->CreateAndSetAndSignalOffer();
1895 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001896 MediaExpectations media_expectations;
1897 media_expectations.ExpectBidirectionalAudioAndVideo();
1898 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001899 EXPECT_METRIC_LE(
1900 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1901 webrtc::kEnumCounterKeyProtocolSdes));
1902 EXPECT_METRIC_EQ(
1903 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1904 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001905}
1906
Steve Anton9a44b2d2019-07-12 12:58:30 -07001907// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1908// option to offer encrypted versions of all header extensions alongside the
1909// unencrypted versions.
1910TEST_P(PeerConnectionIntegrationTest,
1911 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1912 CryptoOptions crypto_options;
1913 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1914 PeerConnectionInterface::RTCConfiguration config;
1915 config.crypto_options = crypto_options;
1916 // Note: This allows offering >14 RTP header extensions.
1917 config.offer_extmap_allow_mixed = true;
1918 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1919 ConnectFakeSignaling();
1920
1921 // Do normal offer/answer and wait for some frames to be received in each
1922 // direction.
1923 caller()->AddAudioVideoTracks();
1924 callee()->AddAudioVideoTracks();
1925 caller()->CreateAndSetAndSignalOffer();
1926 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1927 MediaExpectations media_expectations;
1928 media_expectations.ExpectBidirectionalAudioAndVideo();
1929 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1930}
1931
Steve Anton8c0f7a72017-10-03 10:03:10 -07001932// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1933// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001934TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001935 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1936 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1937 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1938 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1939 return pc->GetRemoteAudioSSLCertificate();
1940 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001941 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1942 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1943 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1944 return pc->GetRemoteAudioSSLCertChain();
1945 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001946
1947 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1948 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1949
1950 // Configure each side with a known certificate so they can be compared later.
1951 PeerConnectionInterface::RTCConfiguration caller_config;
1952 caller_config.enable_dtls_srtp.emplace(true);
1953 caller_config.certificates.push_back(caller_cert);
1954 PeerConnectionInterface::RTCConfiguration callee_config;
1955 callee_config.enable_dtls_srtp.emplace(true);
1956 callee_config.certificates.push_back(callee_cert);
1957 ASSERT_TRUE(
1958 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1959 ConnectFakeSignaling();
1960
1961 // When first initialized, there should not be a remote SSL certificate (and
1962 // calling this method should not crash).
1963 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1964 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001965 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1966 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001967
Steve Anton15324772018-01-16 10:26:49 -08001968 caller()->AddAudioTrack();
1969 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001970 caller()->CreateAndSetAndSignalOffer();
1971 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1972 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1973
1974 // Once DTLS has been connected, each side should return the other's SSL
1975 // certificate when calling GetRemoteAudioSSLCertificate.
1976
1977 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1978 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001979 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001980 caller_remote_cert->ToPEMString());
1981
1982 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1983 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001984 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001985 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001986
1987 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1988 ASSERT_TRUE(caller_remote_cert_chain);
1989 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1990 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001991 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001992 remote_cert->ToPEMString());
1993
1994 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1995 ASSERT_TRUE(callee_remote_cert_chain);
1996 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1997 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001998 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001999 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002000}
2001
deadbeef1dcb1642017-03-29 21:08:16 -07002002// This test sets up a call between two parties with a source resolution of
2003// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002004TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002005 Send1280By720ResolutionAndReceive16To9AspectRatio) {
2006 ASSERT_TRUE(CreatePeerConnectionWrappers());
2007 ConnectFakeSignaling();
2008
Niels Möller5c7efe72018-05-11 10:34:46 +02002009 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
2010 webrtc::FakePeriodicVideoSource::Config config;
2011 config.width = 1280;
2012 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02002013 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02002014 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
2015 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07002016
2017 // Do normal offer/answer and wait for at least one frame to be received in
2018 // each direction.
2019 caller()->CreateAndSetAndSignalOffer();
2020 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2021 callee()->min_video_frames_received_per_track() > 0,
2022 kMaxWaitForFramesMs);
2023
2024 // Check rendered aspect ratio.
2025 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
2026 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
2027 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
2028 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
2029}
2030
2031// This test sets up an one-way call, with media only from caller to
2032// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002033TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07002034 ASSERT_TRUE(CreatePeerConnectionWrappers());
2035 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002036 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002037 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002038 MediaExpectations media_expectations;
2039 media_expectations.CalleeExpectsSomeAudioAndVideo();
2040 media_expectations.CallerExpectsNoAudio();
2041 media_expectations.CallerExpectsNoVideo();
2042 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002043}
2044
2045// This test sets up a audio call initially, with the callee rejecting video
2046// initially. Then later the callee decides to upgrade to audio/video, and
2047// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002048TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07002049 ASSERT_TRUE(CreatePeerConnectionWrappers());
2050 ConnectFakeSignaling();
2051 // Initially, offer an audio/video stream from the caller, but refuse to
2052 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08002053 caller()->AddAudioVideoTracks();
2054 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002055 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2056 PeerConnectionInterface::RTCOfferAnswerOptions options;
2057 options.offer_to_receive_video = 0;
2058 callee()->SetOfferAnswerOptions(options);
2059 } else {
2060 callee()->SetRemoteOfferHandler([this] {
2061 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2062 });
2063 }
deadbeef1dcb1642017-03-29 21:08:16 -07002064 // Do offer/answer and make sure audio is still received end-to-end.
2065 caller()->CreateAndSetAndSignalOffer();
2066 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002067 {
2068 MediaExpectations media_expectations;
2069 media_expectations.ExpectBidirectionalAudio();
2070 media_expectations.ExpectNoVideo();
2071 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2072 }
deadbeef1dcb1642017-03-29 21:08:16 -07002073 // Sanity check that the callee's description has a rejected video section.
2074 ASSERT_NE(nullptr, callee()->pc()->local_description());
2075 const ContentInfo* callee_video_content =
2076 GetFirstVideoContent(callee()->pc()->local_description()->description());
2077 ASSERT_NE(nullptr, callee_video_content);
2078 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002079
deadbeef1dcb1642017-03-29 21:08:16 -07002080 // Now negotiate with video and ensure negotiation succeeds, with video
2081 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002082 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002083 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2084 PeerConnectionInterface::RTCOfferAnswerOptions options;
2085 options.offer_to_receive_video = 1;
2086 callee()->SetOfferAnswerOptions(options);
2087 } else {
2088 callee()->SetRemoteOfferHandler(nullptr);
2089 caller()->SetRemoteOfferHandler([this] {
2090 // The caller creates a new transceiver to receive video on when receiving
2091 // the offer, but by default it is send only.
2092 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002093 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002094 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
2095 transceivers[2]->receiver()->media_type());
2096 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2097 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
2098 });
2099 }
deadbeef1dcb1642017-03-29 21:08:16 -07002100 callee()->CreateAndSetAndSignalOffer();
2101 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002102 {
2103 // Expect additional audio frames to be received after the upgrade.
2104 MediaExpectations media_expectations;
2105 media_expectations.ExpectBidirectionalAudioAndVideo();
2106 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2107 }
deadbeef1dcb1642017-03-29 21:08:16 -07002108}
2109
deadbeef4389b4d2017-09-07 09:07:36 -07002110// Simpler than the above test; just add an audio track to an established
2111// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002112TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002113 ASSERT_TRUE(CreatePeerConnectionWrappers());
2114 ConnectFakeSignaling();
2115 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002116 caller()->AddVideoTrack();
2117 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002118 caller()->CreateAndSetAndSignalOffer();
2119 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2120 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002121 caller()->AddAudioTrack();
2122 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002123 caller()->CreateAndSetAndSignalOffer();
2124 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2125 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002126 MediaExpectations media_expectations;
2127 media_expectations.ExpectBidirectionalAudioAndVideo();
2128 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002129}
2130
deadbeef1dcb1642017-03-29 21:08:16 -07002131// This test sets up a call that's transferred to a new caller with a different
2132// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002133TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002134 ASSERT_TRUE(CreatePeerConnectionWrappers());
2135 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002136 caller()->AddAudioVideoTracks();
2137 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002138 caller()->CreateAndSetAndSignalOffer();
2139 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2140
2141 // Keep the original peer around which will still send packets to the
2142 // receiving client. These SRTP packets will be dropped.
2143 std::unique_ptr<PeerConnectionWrapper> original_peer(
2144 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002145 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002146 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2147 // directly above.
2148 original_peer->pc()->Close();
2149
2150 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002151 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002152 caller()->CreateAndSetAndSignalOffer();
2153 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2154 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002155 MediaExpectations media_expectations;
2156 media_expectations.ExpectBidirectionalAudioAndVideo();
2157 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002158}
2159
2160// This test sets up a call that's transferred to a new callee with a different
2161// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002162TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002163 ASSERT_TRUE(CreatePeerConnectionWrappers());
2164 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002165 caller()->AddAudioVideoTracks();
2166 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002167 caller()->CreateAndSetAndSignalOffer();
2168 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2169
2170 // Keep the original peer around which will still send packets to the
2171 // receiving client. These SRTP packets will be dropped.
2172 std::unique_ptr<PeerConnectionWrapper> original_peer(
2173 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002174 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002175 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2176 // directly above.
2177 original_peer->pc()->Close();
2178
2179 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002180 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002181 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2182 caller()->CreateAndSetAndSignalOffer();
2183 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2184 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002185 MediaExpectations media_expectations;
2186 media_expectations.ExpectBidirectionalAudioAndVideo();
2187 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002188}
2189
2190// This test sets up a non-bundled call and negotiates bundling at the same
2191// time as starting an ICE restart. When bundling is in effect in the restart,
2192// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002193TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002194 ASSERT_TRUE(CreatePeerConnectionWrappers());
2195 ConnectFakeSignaling();
2196
Steve Anton15324772018-01-16 10:26:49 -08002197 caller()->AddAudioVideoTracks();
2198 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002199 // Remove the bundle group from the SDP received by the callee.
2200 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2201 desc->RemoveGroupByName("BUNDLE");
2202 });
2203 caller()->CreateAndSetAndSignalOffer();
2204 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002205 {
2206 MediaExpectations media_expectations;
2207 media_expectations.ExpectBidirectionalAudioAndVideo();
2208 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2209 }
deadbeef1dcb1642017-03-29 21:08:16 -07002210 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2211 callee()->SetReceivedSdpMunger(nullptr);
2212 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2213 caller()->CreateAndSetAndSignalOffer();
2214 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2215
2216 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002217 {
2218 MediaExpectations media_expectations;
2219 media_expectations.ExpectBidirectionalAudioAndVideo();
2220 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2221 }
deadbeef1dcb1642017-03-29 21:08:16 -07002222}
2223
2224// Test CVO (Coordination of Video Orientation). If a video source is rotated
2225// and both peers support the CVO RTP header extension, the actual video frames
2226// don't need to be encoded in different resolutions, since the rotation is
2227// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002228TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002229 ASSERT_TRUE(CreatePeerConnectionWrappers());
2230 ConnectFakeSignaling();
2231 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002232 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002233 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002234 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002235 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2236
2237 // Wait for video frames to be received by both sides.
2238 caller()->CreateAndSetAndSignalOffer();
2239 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2240 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2241 callee()->min_video_frames_received_per_track() > 0,
2242 kMaxWaitForFramesMs);
2243
2244 // Ensure that the aspect ratio is unmodified.
2245 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2246 // not just assumed.
2247 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2248 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2249 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2250 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2251 // Ensure that the CVO bits were surfaced to the renderer.
2252 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2253 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2254}
2255
2256// Test that when the CVO extension isn't supported, video is rotated the
2257// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002258TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002259 ASSERT_TRUE(CreatePeerConnectionWrappers());
2260 ConnectFakeSignaling();
2261 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002262 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002263 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002264 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002265 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2266
2267 // Remove the CVO extension from the offered SDP.
2268 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2269 cricket::VideoContentDescription* video =
2270 GetFirstVideoContentDescription(desc);
2271 video->ClearRtpHeaderExtensions();
2272 });
2273 // Wait for video frames to be received by both sides.
2274 caller()->CreateAndSetAndSignalOffer();
2275 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2276 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2277 callee()->min_video_frames_received_per_track() > 0,
2278 kMaxWaitForFramesMs);
2279
2280 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2281 // rotation.
2282 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2283 // not just assumed.
2284 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2285 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2286 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2287 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2288 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2289 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2290 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2291}
2292
deadbeef1dcb1642017-03-29 21:08:16 -07002293// Test that if the answerer rejects the audio m= section, no audio is sent or
2294// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002295TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002296 ASSERT_TRUE(CreatePeerConnectionWrappers());
2297 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002298 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002299 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2300 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2301 // it will reject the audio m= section completely.
2302 PeerConnectionInterface::RTCOfferAnswerOptions options;
2303 options.offer_to_receive_audio = 0;
2304 callee()->SetOfferAnswerOptions(options);
2305 } else {
2306 // Stopping the audio RtpTransceiver will cause the media section to be
2307 // rejected in the answer.
2308 callee()->SetRemoteOfferHandler([this] {
2309 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2310 });
2311 }
Steve Anton15324772018-01-16 10:26:49 -08002312 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002313 // Do offer/answer and wait for successful end-to-end video frames.
2314 caller()->CreateAndSetAndSignalOffer();
2315 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002316 MediaExpectations media_expectations;
2317 media_expectations.ExpectBidirectionalVideo();
2318 media_expectations.ExpectNoAudio();
2319 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2320
deadbeef1dcb1642017-03-29 21:08:16 -07002321 // Sanity check that the callee's description has a rejected audio section.
2322 ASSERT_NE(nullptr, callee()->pc()->local_description());
2323 const ContentInfo* callee_audio_content =
2324 GetFirstAudioContent(callee()->pc()->local_description()->description());
2325 ASSERT_NE(nullptr, callee_audio_content);
2326 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002327 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2328 // The caller's transceiver should have stopped after receiving the answer.
2329 EXPECT_TRUE(caller()
2330 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2331 ->stopped());
2332 }
deadbeef1dcb1642017-03-29 21:08:16 -07002333}
2334
2335// Test that if the answerer rejects the video m= section, no video is sent or
2336// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002337TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002338 ASSERT_TRUE(CreatePeerConnectionWrappers());
2339 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002340 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002341 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2342 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2343 // it will reject the video m= section completely.
2344 PeerConnectionInterface::RTCOfferAnswerOptions options;
2345 options.offer_to_receive_video = 0;
2346 callee()->SetOfferAnswerOptions(options);
2347 } else {
2348 // Stopping the video RtpTransceiver will cause the media section to be
2349 // rejected in the answer.
2350 callee()->SetRemoteOfferHandler([this] {
2351 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2352 });
2353 }
Steve Anton15324772018-01-16 10:26:49 -08002354 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002355 // Do offer/answer and wait for successful end-to-end audio frames.
2356 caller()->CreateAndSetAndSignalOffer();
2357 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002358 MediaExpectations media_expectations;
2359 media_expectations.ExpectBidirectionalAudio();
2360 media_expectations.ExpectNoVideo();
2361 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2362
deadbeef1dcb1642017-03-29 21:08:16 -07002363 // Sanity check that the callee's description has a rejected video section.
2364 ASSERT_NE(nullptr, callee()->pc()->local_description());
2365 const ContentInfo* callee_video_content =
2366 GetFirstVideoContent(callee()->pc()->local_description()->description());
2367 ASSERT_NE(nullptr, callee_video_content);
2368 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002369 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2370 // The caller's transceiver should have stopped after receiving the answer.
2371 EXPECT_TRUE(caller()
2372 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2373 ->stopped());
2374 }
deadbeef1dcb1642017-03-29 21:08:16 -07002375}
2376
2377// Test that if the answerer rejects both audio and video m= sections, nothing
2378// bad happens.
2379// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2380// test anything but the fact that negotiation succeeds, which doesn't mean
2381// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002382TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002383 ASSERT_TRUE(CreatePeerConnectionWrappers());
2384 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002385 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002386 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2387 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2388 // will reject both audio and video m= sections.
2389 PeerConnectionInterface::RTCOfferAnswerOptions options;
2390 options.offer_to_receive_audio = 0;
2391 options.offer_to_receive_video = 0;
2392 callee()->SetOfferAnswerOptions(options);
2393 } else {
2394 callee()->SetRemoteOfferHandler([this] {
2395 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002396 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002397 transceiver->Stop();
2398 }
2399 });
2400 }
deadbeef1dcb1642017-03-29 21:08:16 -07002401 // Do offer/answer and wait for stable signaling state.
2402 caller()->CreateAndSetAndSignalOffer();
2403 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002404
deadbeef1dcb1642017-03-29 21:08:16 -07002405 // Sanity check that the callee's description has rejected m= sections.
2406 ASSERT_NE(nullptr, callee()->pc()->local_description());
2407 const ContentInfo* callee_audio_content =
2408 GetFirstAudioContent(callee()->pc()->local_description()->description());
2409 ASSERT_NE(nullptr, callee_audio_content);
2410 EXPECT_TRUE(callee_audio_content->rejected);
2411 const ContentInfo* callee_video_content =
2412 GetFirstVideoContent(callee()->pc()->local_description()->description());
2413 ASSERT_NE(nullptr, callee_video_content);
2414 EXPECT_TRUE(callee_video_content->rejected);
2415}
2416
2417// This test sets up an audio and video call between two parties. After the
2418// call runs for a while, the caller sends an updated offer with video being
2419// rejected. Once the re-negotiation is done, the video flow should stop and
2420// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002421TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002422 ASSERT_TRUE(CreatePeerConnectionWrappers());
2423 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002424 caller()->AddAudioVideoTracks();
2425 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002426 caller()->CreateAndSetAndSignalOffer();
2427 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002428 {
2429 MediaExpectations media_expectations;
2430 media_expectations.ExpectBidirectionalAudioAndVideo();
2431 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2432 }
deadbeef1dcb1642017-03-29 21:08:16 -07002433 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002434 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2435 caller()->SetGeneratedSdpMunger(
2436 [](cricket::SessionDescription* description) {
2437 for (cricket::ContentInfo& content : description->contents()) {
2438 if (cricket::IsVideoContent(&content)) {
2439 content.rejected = true;
2440 }
2441 }
2442 });
2443 } else {
2444 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2445 }
deadbeef1dcb1642017-03-29 21:08:16 -07002446 caller()->CreateAndSetAndSignalOffer();
2447 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2448
2449 // Sanity check that the caller's description has a rejected video section.
2450 ASSERT_NE(nullptr, caller()->pc()->local_description());
2451 const ContentInfo* caller_video_content =
2452 GetFirstVideoContent(caller()->pc()->local_description()->description());
2453 ASSERT_NE(nullptr, caller_video_content);
2454 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002455 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002456 {
2457 MediaExpectations media_expectations;
2458 media_expectations.ExpectBidirectionalAudio();
2459 media_expectations.ExpectNoVideo();
2460 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2461 }
deadbeef1dcb1642017-03-29 21:08:16 -07002462}
2463
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002464// Do one offer/answer with audio, another that disables it (rejecting the m=
2465// section), and another that re-enables it. Regression test for:
2466// bugs.webrtc.org/6023
2467TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2468 ASSERT_TRUE(CreatePeerConnectionWrappers());
2469 ConnectFakeSignaling();
2470
2471 // Add audio track, do normal offer/answer.
2472 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2473 caller()->CreateLocalAudioTrack();
2474 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2475 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2476 caller()->CreateAndSetAndSignalOffer();
2477 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2478
2479 // Remove audio track, and set offer_to_receive_audio to false to cause the
2480 // m= section to be completely disabled, not just "recvonly".
2481 caller()->pc()->RemoveTrack(sender);
2482 PeerConnectionInterface::RTCOfferAnswerOptions options;
2483 options.offer_to_receive_audio = 0;
2484 caller()->SetOfferAnswerOptions(options);
2485 caller()->CreateAndSetAndSignalOffer();
2486 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2487
2488 // Add the audio track again, expecting negotiation to succeed and frames to
2489 // flow.
2490 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2491 options.offer_to_receive_audio = 1;
2492 caller()->SetOfferAnswerOptions(options);
2493 caller()->CreateAndSetAndSignalOffer();
2494 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2495
2496 MediaExpectations media_expectations;
2497 media_expectations.CalleeExpectsSomeAudio();
2498 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2499}
2500
deadbeef1dcb1642017-03-29 21:08:16 -07002501// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2502// is needed to support legacy endpoints.
2503// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2504// add a test for an end-to-end test without MID signaling either (basically,
2505// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002506TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002507 ASSERT_TRUE(CreatePeerConnectionWrappers());
2508 ConnectFakeSignaling();
2509 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002510 caller()->AddAudioVideoTracks();
2511 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002512 // Remove SSRCs and MSIDs from the received offer SDP.
2513 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002514 caller()->CreateAndSetAndSignalOffer();
2515 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002516 MediaExpectations media_expectations;
2517 media_expectations.ExpectBidirectionalAudioAndVideo();
2518 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002519}
2520
Seth Hampson5897a6e2018-04-03 11:16:33 -07002521// Basic end-to-end test, without SSRC signaling. This means that the track
2522// was created properly and frames are delivered when the MSIDs are communicated
2523// with a=msid lines and no a=ssrc lines.
2524TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2525 EndToEndCallWithoutSsrcSignaling) {
2526 const char kStreamId[] = "streamId";
2527 ASSERT_TRUE(CreatePeerConnectionWrappers());
2528 ConnectFakeSignaling();
2529 // Add just audio tracks.
2530 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2531 callee()->AddAudioTrack();
2532
2533 // Remove SSRCs from the received offer SDP.
2534 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2535 caller()->CreateAndSetAndSignalOffer();
2536 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2537 MediaExpectations media_expectations;
2538 media_expectations.ExpectBidirectionalAudio();
2539 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2540}
2541
Steve Antondf527fd2018-04-27 15:52:03 -07002542// Tests that video flows between multiple video tracks when SSRCs are not
2543// signaled. This exercises the MID RTP header extension which is needed to
2544// demux the incoming video tracks.
2545TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2546 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2547 ASSERT_TRUE(CreatePeerConnectionWrappers());
2548 ConnectFakeSignaling();
2549 caller()->AddVideoTrack();
2550 caller()->AddVideoTrack();
2551 callee()->AddVideoTrack();
2552 callee()->AddVideoTrack();
2553
2554 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2555 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2556 caller()->CreateAndSetAndSignalOffer();
2557 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2558 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2559 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2560
2561 // Expect video to be received in both directions on both tracks.
2562 MediaExpectations media_expectations;
2563 media_expectations.ExpectBidirectionalVideo();
2564 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2565}
2566
Henrik Boström5b147782018-12-04 11:25:05 +01002567TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2568 ASSERT_TRUE(CreatePeerConnectionWrappers());
2569 ConnectFakeSignaling();
2570 caller()->AddAudioTrack();
2571 caller()->AddVideoTrack();
2572 caller()->CreateAndSetAndSignalOffer();
2573 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2574 auto callee_receivers = callee()->pc()->GetReceivers();
2575 ASSERT_EQ(2u, callee_receivers.size());
2576 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2577 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2578}
2579
2580TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2581 ASSERT_TRUE(CreatePeerConnectionWrappers());
2582 ConnectFakeSignaling();
2583 caller()->AddAudioTrack();
2584 caller()->AddVideoTrack();
2585 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2586 caller()->CreateAndSetAndSignalOffer();
2587 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2588 auto callee_receivers = callee()->pc()->GetReceivers();
2589 ASSERT_EQ(2u, callee_receivers.size());
2590 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2591 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2592 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2593 callee_receivers[1]->stream_ids()[0]);
2594 EXPECT_EQ(callee_receivers[0]->streams()[0],
2595 callee_receivers[1]->streams()[0]);
2596}
2597
deadbeef1dcb1642017-03-29 21:08:16 -07002598// Test that if two video tracks are sent (from caller to callee, in this test),
2599// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002600TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002601 ASSERT_TRUE(CreatePeerConnectionWrappers());
2602 ConnectFakeSignaling();
2603 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002604 caller()->AddAudioVideoTracks();
2605 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002606 caller()->CreateAndSetAndSignalOffer();
2607 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002608 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002609
2610 MediaExpectations media_expectations;
2611 media_expectations.CalleeExpectsSomeAudioAndVideo();
2612 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002613}
2614
2615static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2616 bool first = true;
2617 for (cricket::ContentInfo& content : desc->contents()) {
2618 if (first) {
2619 first = false;
2620 continue;
2621 }
2622 content.bundle_only = true;
2623 }
2624 first = true;
2625 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2626 if (first) {
2627 first = false;
2628 continue;
2629 }
2630 transport.description.ice_ufrag.clear();
2631 transport.description.ice_pwd.clear();
2632 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2633 transport.description.identity_fingerprint.reset(nullptr);
2634 }
2635}
2636
2637// Test that if applying a true "max bundle" offer, which uses ports of 0,
2638// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2639// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2640// successfully and media flows.
2641// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2642// TODO(deadbeef): Won't need this test once we start generating actual
2643// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002644TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002645 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2646 ASSERT_TRUE(CreatePeerConnectionWrappers());
2647 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002648 caller()->AddAudioVideoTracks();
2649 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002650 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2651 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2652 // but the first m= section.
2653 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2654 caller()->CreateAndSetAndSignalOffer();
2655 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002656 MediaExpectations media_expectations;
2657 media_expectations.ExpectBidirectionalAudioAndVideo();
2658 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002659}
2660
2661// Test that we can receive the audio output level from a remote audio track.
2662// TODO(deadbeef): Use a fake audio source and verify that the output level is
2663// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002664TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002665 ASSERT_TRUE(CreatePeerConnectionWrappers());
2666 ConnectFakeSignaling();
2667 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002668 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002669 caller()->CreateAndSetAndSignalOffer();
2670 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2671
2672 // Get the audio output level stats. Note that the level is not available
2673 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002674 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002675 kMaxWaitForFramesMs);
2676}
2677
2678// Test that an audio input level is reported.
2679// TODO(deadbeef): Use a fake audio source and verify that the input level is
2680// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002681TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002682 ASSERT_TRUE(CreatePeerConnectionWrappers());
2683 ConnectFakeSignaling();
2684 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002685 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002686 caller()->CreateAndSetAndSignalOffer();
2687 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2688
2689 // Get the audio input level stats. The level should be available very
2690 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002691 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002692 kMaxWaitForStatsMs);
2693}
2694
2695// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002696TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002697 ASSERT_TRUE(CreatePeerConnectionWrappers());
2698 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002699 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002700 // Do offer/answer, wait for the callee to receive some frames.
2701 caller()->CreateAndSetAndSignalOffer();
2702 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002703
2704 MediaExpectations media_expectations;
2705 media_expectations.CalleeExpectsSomeAudioAndVideo();
2706 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002707
2708 // Get a handle to the remote tracks created, so they can be used as GetStats
2709 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002710 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002711 // We received frames, so we definitely should have nonzero "received bytes"
2712 // stats at this point.
2713 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2714 0);
2715 }
deadbeef1dcb1642017-03-29 21:08:16 -07002716}
2717
2718// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002719TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002720 ASSERT_TRUE(CreatePeerConnectionWrappers());
2721 ConnectFakeSignaling();
2722 auto audio_track = caller()->CreateLocalAudioTrack();
2723 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002724 caller()->AddTrack(audio_track);
2725 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002726 // Do offer/answer, wait for the callee to receive some frames.
2727 caller()->CreateAndSetAndSignalOffer();
2728 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002729 MediaExpectations media_expectations;
2730 media_expectations.CalleeExpectsSomeAudioAndVideo();
2731 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002732
2733 // The callee received frames, so we definitely should have nonzero "sent
2734 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002735 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2736 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2737}
2738
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002739// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002740TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002741 ASSERT_TRUE(CreatePeerConnectionWrappers());
2742 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002743 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002744
Steve Anton15324772018-01-16 10:26:49 -08002745 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002746
2747 // Do offer/answer, wait for the callee to receive some frames.
2748 caller()->CreateAndSetAndSignalOffer();
2749 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2750
2751 // Get the remote audio track created on the receiver, so they can be used as
2752 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002753 auto receivers = callee()->pc()->GetReceivers();
2754 ASSERT_EQ(1u, receivers.size());
2755 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002756
2757 // Get the audio output level stats. Note that the level is not available
2758 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002759 EXPECT_TRUE_WAIT(
2760 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2761 0,
2762 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002763}
2764
Steve Antona41959e2018-11-28 11:15:33 -08002765// Test that the track ID is associated with all local and remote SSRC stats
2766// using the old GetStats() and more than 1 audio and more than 1 video track.
2767// This is a regression test for crbug.com/906988
2768TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2769 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2770 ASSERT_TRUE(CreatePeerConnectionWrappers());
2771 ConnectFakeSignaling();
2772 auto audio_sender_1 = caller()->AddAudioTrack();
2773 auto video_sender_1 = caller()->AddVideoTrack();
2774 auto audio_sender_2 = caller()->AddAudioTrack();
2775 auto video_sender_2 = caller()->AddVideoTrack();
2776 caller()->CreateAndSetAndSignalOffer();
2777 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2778
2779 MediaExpectations media_expectations;
2780 media_expectations.CalleeExpectsSomeAudioAndVideo();
2781 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2782
2783 std::vector<std::string> track_ids = {
2784 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2785 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2786
2787 auto caller_stats = caller()->OldGetStats();
2788 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2789 auto callee_stats = callee()->OldGetStats();
2790 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2791}
2792
Steve Antonffa6ce42018-11-30 09:26:08 -08002793// Test that the new GetStats() returns stats for all outgoing/incoming streams
2794// with the correct track IDs if there are more than one audio and more than one
2795// video senders/receivers.
2796TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2797 ASSERT_TRUE(CreatePeerConnectionWrappers());
2798 ConnectFakeSignaling();
2799 auto audio_sender_1 = caller()->AddAudioTrack();
2800 auto video_sender_1 = caller()->AddVideoTrack();
2801 auto audio_sender_2 = caller()->AddAudioTrack();
2802 auto video_sender_2 = caller()->AddVideoTrack();
2803 caller()->CreateAndSetAndSignalOffer();
2804 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2805
2806 MediaExpectations media_expectations;
2807 media_expectations.CalleeExpectsSomeAudioAndVideo();
2808 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2809
2810 std::vector<std::string> track_ids = {
2811 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2812 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2813
2814 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2815 caller()->NewGetStats();
2816 ASSERT_TRUE(caller_report);
2817 auto outbound_stream_stats =
2818 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2819 ASSERT_EQ(4u, outbound_stream_stats.size());
2820 std::vector<std::string> outbound_track_ids;
2821 for (const auto& stat : outbound_stream_stats) {
2822 ASSERT_TRUE(stat->bytes_sent.is_defined());
2823 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002824 if (*stat->kind == "video") {
2825 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
2826 EXPECT_GT(*stat->key_frames_encoded, 0u);
2827 ASSERT_TRUE(stat->frames_encoded.is_defined());
2828 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
2829 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002830 ASSERT_TRUE(stat->track_id.is_defined());
2831 const auto* track_stat =
2832 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2833 ASSERT_TRUE(track_stat);
2834 outbound_track_ids.push_back(*track_stat->track_identifier);
2835 }
2836 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2837
2838 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2839 callee()->NewGetStats();
2840 ASSERT_TRUE(callee_report);
2841 auto inbound_stream_stats =
2842 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2843 ASSERT_EQ(4u, inbound_stream_stats.size());
2844 std::vector<std::string> inbound_track_ids;
2845 for (const auto& stat : inbound_stream_stats) {
2846 ASSERT_TRUE(stat->bytes_received.is_defined());
2847 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002848 if (*stat->kind == "video") {
2849 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
2850 EXPECT_GT(*stat->key_frames_decoded, 0u);
2851 ASSERT_TRUE(stat->frames_decoded.is_defined());
2852 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
2853 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002854 ASSERT_TRUE(stat->track_id.is_defined());
2855 const auto* track_stat =
2856 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2857 ASSERT_TRUE(track_stat);
2858 inbound_track_ids.push_back(*track_stat->track_identifier);
2859 }
2860 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2861}
2862
2863// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002864// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2865// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002866TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002867 GetStatsForUnsignaledStreamWithNewStatsApi) {
2868 ASSERT_TRUE(CreatePeerConnectionWrappers());
2869 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002870 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002871 // Remove SSRCs and MSIDs from the received offer SDP.
2872 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2873 caller()->CreateAndSetAndSignalOffer();
2874 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002875 MediaExpectations media_expectations;
2876 media_expectations.CalleeExpectsSomeAudio(1);
2877 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002878
2879 // We received a frame, so we should have nonzero "bytes received" stats for
2880 // the unsignaled stream, if stats are working for it.
2881 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2882 callee()->NewGetStats();
2883 ASSERT_NE(nullptr, report);
2884 auto inbound_stream_stats =
2885 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2886 ASSERT_EQ(1U, inbound_stream_stats.size());
2887 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2888 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002889 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2890}
2891
Taylor Brandstettera4653442018-06-19 09:44:26 -07002892// Same as above but for the legacy stats implementation.
2893TEST_P(PeerConnectionIntegrationTest,
2894 GetStatsForUnsignaledStreamWithOldStatsApi) {
2895 ASSERT_TRUE(CreatePeerConnectionWrappers());
2896 ConnectFakeSignaling();
2897 caller()->AddAudioTrack();
2898 // Remove SSRCs and MSIDs from the received offer SDP.
2899 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2900 caller()->CreateAndSetAndSignalOffer();
2901 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2902
2903 // Note that, since the old stats implementation associates SSRCs with tracks
2904 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2905 // associated track ID. So we can't use the track "selector" argument.
2906 //
2907 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2908 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002909 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002910 kDefaultTimeout);
2911}
2912
zhihuangf8164932017-05-19 13:09:47 -07002913// Test that we can successfully get the media related stats (audio level
2914// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002915TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002916 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2917 ASSERT_TRUE(CreatePeerConnectionWrappers());
2918 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002919 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002920 // Remove SSRCs and MSIDs from the received offer SDP.
2921 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2922 caller()->CreateAndSetAndSignalOffer();
2923 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002924 MediaExpectations media_expectations;
2925 media_expectations.CalleeExpectsSomeAudio(1);
2926 media_expectations.CalleeExpectsSomeVideo(1);
2927 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002928
2929 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2930 callee()->NewGetStats();
2931 ASSERT_NE(nullptr, report);
2932
2933 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2934 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2935 ASSERT_GE(audio_index, 0);
2936 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002937}
2938
deadbeef4e2deab2017-09-20 13:56:21 -07002939// Helper for test below.
2940void ModifySsrcs(cricket::SessionDescription* desc) {
2941 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002942 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002943 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002944 for (uint32_t& ssrc : stream.ssrcs) {
2945 ssrc = rtc::CreateRandomId();
2946 }
2947 }
2948 }
2949}
2950
2951// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2952// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2953// This should result in two "RTCInboundRTPStreamStats", but only one
2954// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2955// being reset to 0 once the SSRC change occurs.
2956//
2957// Regression test for this bug:
2958// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2959//
2960// The bug causes the track stats to only represent one of the two streams:
2961// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2962// that the track stat counters would reset to 0 when the new stream is
2963// received, and a 50% chance that they'll stop updating (while
2964// "concealed_samples" continues increasing, due to silence being generated for
2965// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002966TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002967 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002968 ASSERT_TRUE(CreatePeerConnectionWrappers());
2969 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002970 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002971 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2972 // that doesn't signal SSRCs (from the callee's perspective).
2973 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2974 caller()->CreateAndSetAndSignalOffer();
2975 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2976 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002977 {
2978 MediaExpectations media_expectations;
2979 media_expectations.CalleeExpectsSomeAudio(50);
2980 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2981 }
deadbeef4e2deab2017-09-20 13:56:21 -07002982 // Some audio frames were received, so we should have nonzero "samples
2983 // received" for the track.
2984 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2985 callee()->NewGetStats();
2986 ASSERT_NE(nullptr, report);
2987 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2988 ASSERT_EQ(1U, track_stats.size());
2989 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2990 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2991 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2992
2993 // Create a new offer and munge it to cause the caller to use a new SSRC.
2994 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2995 caller()->CreateAndSetAndSignalOffer();
2996 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2997 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2998 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002999 {
3000 MediaExpectations media_expectations;
3001 media_expectations.CalleeExpectsSomeAudio(25);
3002 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3003 }
deadbeef4e2deab2017-09-20 13:56:21 -07003004
3005 report = callee()->NewGetStats();
3006 ASSERT_NE(nullptr, report);
3007 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3008 ASSERT_EQ(1U, track_stats.size());
3009 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3010 // The "total samples received" stat should only be greater than it was
3011 // before.
3012 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
3013 // Right now, the new SSRC will cause the counters to reset to 0.
3014 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
3015
3016 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08003017 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07003018 // good sign that we're seeing stats from the old stream that's no longer
3019 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08003020 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07003021 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
3022 EXPECT_LT(*track_stats[0]->concealed_samples,
3023 *track_stats[0]->total_samples_received *
3024 kAcceptableConcealedSamplesPercentage);
3025
3026 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
3027 // sanity check that the SSRC really changed.
3028 // TODO(deadbeef): This isn't working right now, because we're not returning
3029 // *any* stats for the inactive stream. Uncomment when the bug is completely
3030 // fixed.
3031 // auto inbound_stream_stats =
3032 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3033 // ASSERT_EQ(2U, inbound_stream_stats.size());
3034}
3035
deadbeef1dcb1642017-03-29 21:08:16 -07003036// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003037TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003038 PeerConnectionFactory::Options dtls_10_options;
3039 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3040 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3041 dtls_10_options));
3042 ConnectFakeSignaling();
3043 // Do normal offer/answer and wait for some frames to be received in each
3044 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003045 caller()->AddAudioVideoTracks();
3046 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003047 caller()->CreateAndSetAndSignalOffer();
3048 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003049 MediaExpectations media_expectations;
3050 media_expectations.ExpectBidirectionalAudioAndVideo();
3051 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003052}
3053
3054// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003055TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003056 PeerConnectionFactory::Options dtls_10_options;
3057 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3058 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3059 dtls_10_options));
3060 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003061 caller()->AddAudioVideoTracks();
3062 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003063 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003064 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003065 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003066 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003067 kDefaultTimeout);
3068 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003069 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003070 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003071 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3072 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3073 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003074}
3075
3076// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003077TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003078 PeerConnectionFactory::Options dtls_12_options;
3079 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3080 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3081 dtls_12_options));
3082 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003083 caller()->AddAudioVideoTracks();
3084 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003085 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003086 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003087 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003088 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003089 kDefaultTimeout);
3090 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003091 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003092 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003093 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3094 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3095 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003096}
3097
3098// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3099// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003100TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003101 PeerConnectionFactory::Options caller_options;
3102 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3103 PeerConnectionFactory::Options callee_options;
3104 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3105 ASSERT_TRUE(
3106 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3107 ConnectFakeSignaling();
3108 // Do normal offer/answer and wait for some frames to be received in each
3109 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003110 caller()->AddAudioVideoTracks();
3111 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003112 caller()->CreateAndSetAndSignalOffer();
3113 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003114 MediaExpectations media_expectations;
3115 media_expectations.ExpectBidirectionalAudioAndVideo();
3116 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003117}
3118
3119// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3120// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003121TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003122 PeerConnectionFactory::Options caller_options;
3123 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3124 PeerConnectionFactory::Options callee_options;
3125 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3126 ASSERT_TRUE(
3127 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3128 ConnectFakeSignaling();
3129 // Do normal offer/answer and wait for some frames to be received in each
3130 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003131 caller()->AddAudioVideoTracks();
3132 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003133 caller()->CreateAndSetAndSignalOffer();
3134 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003135 MediaExpectations media_expectations;
3136 media_expectations.ExpectBidirectionalAudioAndVideo();
3137 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003138}
3139
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003140// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3141// works as expected; the cipher should only be used if enabled by both sides.
3142TEST_P(PeerConnectionIntegrationTest,
3143 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3144 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003145 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003146 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003147 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3148 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003149 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3150 TestNegotiatedCipherSuite(caller_options, callee_options,
3151 expected_cipher_suite);
3152}
3153
3154TEST_P(PeerConnectionIntegrationTest,
3155 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3156 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003157 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3158 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003159 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003160 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003161 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3162 TestNegotiatedCipherSuite(caller_options, callee_options,
3163 expected_cipher_suite);
3164}
3165
3166TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3167 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003168 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003169 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003170 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003171 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3172 TestNegotiatedCipherSuite(caller_options, callee_options,
3173 expected_cipher_suite);
3174}
3175
deadbeef1dcb1642017-03-29 21:08:16 -07003176// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003177TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003178 bool local_gcm_enabled = false;
3179 bool remote_gcm_enabled = false;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003180 bool aes_ctr_enabled = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003181 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3182 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003183 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003184}
3185
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003186// Test that a GCM cipher is used if both ends support it and non-GCM is
3187// disabled.
3188TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenOnlyGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003189 bool local_gcm_enabled = true;
3190 bool remote_gcm_enabled = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003191 bool aes_ctr_enabled = false;
deadbeef1dcb1642017-03-29 21:08:16 -07003192 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3193 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003194 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003195}
3196
deadbeef7914b8c2017-04-21 03:23:33 -07003197// Verify that media can be transmitted end-to-end when GCM crypto suites are
3198// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3199// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3200// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003201TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003202 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003203 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003204 gcm_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher = false;
deadbeef7914b8c2017-04-21 03:23:33 -07003205 ASSERT_TRUE(
3206 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3207 ConnectFakeSignaling();
3208 // Do normal offer/answer and wait for some frames to be received in each
3209 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003210 caller()->AddAudioVideoTracks();
3211 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003212 caller()->CreateAndSetAndSignalOffer();
3213 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003214 MediaExpectations media_expectations;
3215 media_expectations.ExpectBidirectionalAudioAndVideo();
3216 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003217}
3218
deadbeef1dcb1642017-03-29 21:08:16 -07003219// This test sets up a call between two parties with audio, video and an RTP
3220// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003221TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003222 PeerConnectionInterface::RTCConfiguration rtc_config;
3223 rtc_config.enable_rtp_data_channel = true;
3224 rtc_config.enable_dtls_srtp = false;
3225 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003226 ConnectFakeSignaling();
3227 // Expect that data channel created on caller side will show up for callee as
3228 // well.
3229 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003230 caller()->AddAudioVideoTracks();
3231 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003232 caller()->CreateAndSetAndSignalOffer();
3233 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3234 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003235 MediaExpectations media_expectations;
3236 media_expectations.ExpectBidirectionalAudioAndVideo();
3237 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003238 ASSERT_NE(nullptr, caller()->data_channel());
3239 ASSERT_NE(nullptr, callee()->data_channel());
3240 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3241 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3242
3243 // Ensure data can be sent in both directions.
3244 std::string data = "hello world";
3245 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3246 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3247 kDefaultTimeout);
3248 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3249 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3250 kDefaultTimeout);
3251}
3252
Eldar Rellod9ebe012020-03-18 20:41:45 +02003253TEST_P(PeerConnectionIntegrationTest, RtpDataChannelWorksAfterRollback) {
3254 PeerConnectionInterface::RTCConfiguration rtc_config;
3255 rtc_config.enable_rtp_data_channel = true;
3256 rtc_config.enable_dtls_srtp = false;
3257 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
3258 ConnectFakeSignaling();
3259 auto data_channel = caller()->pc()->CreateDataChannel("label_1", nullptr);
3260 ASSERT_TRUE(data_channel.get() != nullptr);
3261 caller()->CreateAndSetAndSignalOffer();
3262 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3263
3264 caller()->CreateDataChannel("label_2", nullptr);
3265 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
3266 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
3267 caller()->pc()->SetLocalDescription(observer,
3268 caller()->CreateOfferAndWait().release());
3269 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
3270 caller()->Rollback();
3271
3272 std::string data = "hello world";
3273 SendRtpDataWithRetries(data_channel, data, 5);
3274 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3275 kDefaultTimeout);
3276}
3277
deadbeef1dcb1642017-03-29 21:08:16 -07003278// Ensure that an RTP data channel is signaled as closed for the caller when
3279// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003280TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003281 RtpDataChannelSignaledClosedInCalleeOffer) {
3282 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003283 PeerConnectionInterface::RTCConfiguration rtc_config;
3284 rtc_config.enable_rtp_data_channel = true;
3285 rtc_config.enable_dtls_srtp = false;
3286 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003287 ConnectFakeSignaling();
3288 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003289 caller()->AddAudioVideoTracks();
3290 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003291 caller()->CreateAndSetAndSignalOffer();
3292 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3293 ASSERT_NE(nullptr, caller()->data_channel());
3294 ASSERT_NE(nullptr, callee()->data_channel());
3295 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3296 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3297
3298 // Close the data channel on the callee, and do an updated offer/answer.
3299 callee()->data_channel()->Close();
3300 callee()->CreateAndSetAndSignalOffer();
3301 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3302 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3303 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3304}
3305
3306// Tests that data is buffered in an RTP data channel until an observer is
3307// registered for it.
3308//
3309// NOTE: RTP data channels can receive data before the underlying
3310// transport has detected that a channel is writable and thus data can be
3311// received before the data channel state changes to open. That is hard to test
3312// but the same buffering is expected to be used in that case.
Yves Gerey100fe632020-01-17 19:15:53 +01003313//
3314// Use fake clock and simulated network delay so that we predictably can wait
3315// until an SCTP message has been delivered without "sleep()"ing.
3316TEST_P(PeerConnectionIntegrationTestWithFakeClock,
deadbeef1dcb1642017-03-29 21:08:16 -07003317 DataBufferedUntilRtpDataChannelObserverRegistered) {
deadbeef1dcb1642017-03-29 21:08:16 -07003318 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3319 virtual_socket_server()->UpdateDelayDistribution();
3320
Niels Möllerf06f9232018-08-07 12:32:18 +02003321 PeerConnectionInterface::RTCConfiguration rtc_config;
3322 rtc_config.enable_rtp_data_channel = true;
3323 rtc_config.enable_dtls_srtp = false;
3324 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003325 ConnectFakeSignaling();
3326 caller()->CreateDataChannel();
3327 caller()->CreateAndSetAndSignalOffer();
3328 ASSERT_TRUE(caller()->data_channel() != nullptr);
3329 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
Yves Gerey100fe632020-01-17 19:15:53 +01003330 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003331 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
Yves Gerey100fe632020-01-17 19:15:53 +01003332 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003333 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3334 callee()->data_channel()->state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003335 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003336
3337 // Unregister the observer which is normally automatically registered.
3338 callee()->data_channel()->UnregisterObserver();
3339 // Send data and advance fake clock until it should have been received.
3340 std::string data = "hello world";
3341 caller()->data_channel()->Send(DataBuffer(data));
Yves Gerey100fe632020-01-17 19:15:53 +01003342 SIMULATED_WAIT(false, 50, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003343
3344 // Attach data channel and expect data to be received immediately. Note that
3345 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3346 // further, but data can be received even if the callback is asynchronous.
3347 MockDataChannelObserver new_observer(callee()->data_channel());
3348 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003349 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003350}
3351
3352// This test sets up a call between two parties with audio, video and but only
3353// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003354TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003355 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3356 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003357 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003358 rtc_config_1.enable_dtls_srtp = false;
3359 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3360 rtc_config_2.enable_dtls_srtp = false;
3361 rtc_config_2.enable_dtls_srtp = false;
3362 ASSERT_TRUE(
3363 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003364 ConnectFakeSignaling();
3365 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003366 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003367 caller()->AddAudioVideoTracks();
3368 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003369 caller()->CreateAndSetAndSignalOffer();
3370 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3371 // The caller should still have a data channel, but it should be closed, and
3372 // one should ever have been created for the callee.
3373 EXPECT_TRUE(caller()->data_channel() != nullptr);
3374 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3375 EXPECT_EQ(nullptr, callee()->data_channel());
3376}
3377
3378// This test sets up a call between two parties with audio, and video. When
3379// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003380TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003381 PeerConnectionInterface::RTCConfiguration rtc_config;
3382 rtc_config.enable_rtp_data_channel = true;
3383 rtc_config.enable_dtls_srtp = false;
3384 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003385 ConnectFakeSignaling();
3386 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003387 caller()->AddAudioVideoTracks();
3388 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003389 caller()->CreateAndSetAndSignalOffer();
3390 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3391 // Create data channel and do new offer and answer.
3392 caller()->CreateDataChannel();
3393 caller()->CreateAndSetAndSignalOffer();
3394 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3395 ASSERT_NE(nullptr, caller()->data_channel());
3396 ASSERT_NE(nullptr, callee()->data_channel());
3397 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3398 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3399 // Ensure data can be sent in both directions.
3400 std::string data = "hello world";
3401 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3402 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3403 kDefaultTimeout);
3404 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3405 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3406 kDefaultTimeout);
3407}
3408
3409#ifdef HAVE_SCTP
3410
3411// This test sets up a call between two parties with audio, video and an SCTP
3412// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003413TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003414 ASSERT_TRUE(CreatePeerConnectionWrappers());
3415 ConnectFakeSignaling();
3416 // Expect that data channel created on caller side will show up for callee as
3417 // well.
3418 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003419 caller()->AddAudioVideoTracks();
3420 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003421 caller()->CreateAndSetAndSignalOffer();
3422 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3423 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003424 MediaExpectations media_expectations;
3425 media_expectations.ExpectBidirectionalAudioAndVideo();
3426 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003427 // Caller data channel should already exist (it created one). Callee data
3428 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3429 ASSERT_NE(nullptr, caller()->data_channel());
3430 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3431 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3432 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3433
3434 // Ensure data can be sent in both directions.
3435 std::string data = "hello world";
3436 caller()->data_channel()->Send(DataBuffer(data));
3437 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3438 kDefaultTimeout);
3439 callee()->data_channel()->Send(DataBuffer(data));
3440 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3441 kDefaultTimeout);
3442}
3443
3444// Ensure that when the callee closes an SCTP data channel, the closing
3445// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003446TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003447 // Same procedure as above test.
3448 ASSERT_TRUE(CreatePeerConnectionWrappers());
3449 ConnectFakeSignaling();
3450 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003451 caller()->AddAudioVideoTracks();
3452 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003453 caller()->CreateAndSetAndSignalOffer();
3454 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3455 ASSERT_NE(nullptr, caller()->data_channel());
3456 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3457 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3458 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3459
3460 // Close the data channel on the callee side, and wait for it to reach the
3461 // "closed" state on both sides.
3462 callee()->data_channel()->Close();
3463 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3464 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3465}
3466
Seth Hampson2f0d7022018-02-20 11:54:42 -08003467TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003468 ASSERT_TRUE(CreatePeerConnectionWrappers());
3469 ConnectFakeSignaling();
3470 webrtc::DataChannelInit init;
3471 init.id = 53;
3472 init.maxRetransmits = 52;
3473 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003474 caller()->AddAudioVideoTracks();
3475 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003476 caller()->CreateAndSetAndSignalOffer();
3477 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003478 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3479 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003480 // Since "negotiated" is false, the "id" parameter should be ignored.
3481 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003482 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3483 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3484 EXPECT_FALSE(callee()->data_channel()->negotiated());
3485}
3486
deadbeef1dcb1642017-03-29 21:08:16 -07003487// Test usrsctp's ability to process unordered data stream, where data actually
3488// arrives out of order using simulated delays. Previously there have been some
3489// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003490TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003491 // Introduce random network delays.
3492 // Otherwise it's not a true "unordered" test.
3493 virtual_socket_server()->set_delay_mean(20);
3494 virtual_socket_server()->set_delay_stddev(5);
3495 virtual_socket_server()->UpdateDelayDistribution();
3496 // Normal procedure, but with unordered data channel config.
3497 ASSERT_TRUE(CreatePeerConnectionWrappers());
3498 ConnectFakeSignaling();
3499 webrtc::DataChannelInit init;
3500 init.ordered = false;
3501 caller()->CreateDataChannel(&init);
3502 caller()->CreateAndSetAndSignalOffer();
3503 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3504 ASSERT_NE(nullptr, caller()->data_channel());
3505 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3506 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3507 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3508
3509 static constexpr int kNumMessages = 100;
3510 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3511 static constexpr size_t kMaxMessageSize = 4096;
3512 // Create and send random messages.
3513 std::vector<std::string> sent_messages;
3514 for (int i = 0; i < kNumMessages; ++i) {
3515 size_t length =
3516 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3517 std::string message;
3518 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3519 caller()->data_channel()->Send(DataBuffer(message));
3520 callee()->data_channel()->Send(DataBuffer(message));
3521 sent_messages.push_back(message);
3522 }
3523
3524 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003525 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003526 caller()->data_observer()->received_message_count(),
3527 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003528 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003529 callee()->data_observer()->received_message_count(),
3530 kDefaultTimeout);
3531
3532 // Sort and compare to make sure none of the messages were corrupted.
3533 std::vector<std::string> caller_received_messages =
3534 caller()->data_observer()->messages();
3535 std::vector<std::string> callee_received_messages =
3536 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003537 absl::c_sort(sent_messages);
3538 absl::c_sort(caller_received_messages);
3539 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003540 EXPECT_EQ(sent_messages, caller_received_messages);
3541 EXPECT_EQ(sent_messages, callee_received_messages);
3542}
3543
3544// This test sets up a call between two parties with audio, and video. When
3545// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003546TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003547 ASSERT_TRUE(CreatePeerConnectionWrappers());
3548 ConnectFakeSignaling();
3549 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003550 caller()->AddAudioVideoTracks();
3551 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003552 caller()->CreateAndSetAndSignalOffer();
3553 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3554 // Create data channel and do new offer and answer.
3555 caller()->CreateDataChannel();
3556 caller()->CreateAndSetAndSignalOffer();
3557 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3558 // Caller data channel should already exist (it created one). Callee data
3559 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3560 ASSERT_NE(nullptr, caller()->data_channel());
3561 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3562 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3563 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3564 // Ensure data can be sent in both directions.
3565 std::string data = "hello world";
3566 caller()->data_channel()->Send(DataBuffer(data));
3567 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3568 kDefaultTimeout);
3569 callee()->data_channel()->Send(DataBuffer(data));
3570 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3571 kDefaultTimeout);
3572}
3573
deadbeef7914b8c2017-04-21 03:23:33 -07003574// Set up a connection initially just using SCTP data channels, later upgrading
3575// to audio/video, ensuring frames are received end-to-end. Effectively the
3576// inverse of the test above.
3577// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003578TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003579 ASSERT_TRUE(CreatePeerConnectionWrappers());
3580 ConnectFakeSignaling();
3581 // Do initial offer/answer with just data channel.
3582 caller()->CreateDataChannel();
3583 caller()->CreateAndSetAndSignalOffer();
3584 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3585 // Wait until data can be sent over the data channel.
3586 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3587 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3588 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3589
3590 // Do subsequent offer/answer with two-way audio and video. Audio and video
3591 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003592 caller()->AddAudioVideoTracks();
3593 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003594 caller()->CreateAndSetAndSignalOffer();
3595 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003596 MediaExpectations media_expectations;
3597 media_expectations.ExpectBidirectionalAudioAndVideo();
3598 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003599}
3600
deadbeef8b7e9ad2017-05-25 09:38:55 -07003601static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003602 cricket::SctpDataContentDescription* dcd_offer =
3603 GetFirstSctpDataContentDescription(desc);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01003604 // See https://crbug.com/webrtc/11211 - this function is a no-op
Steve Antonb1c1de12017-12-21 15:14:30 -08003605 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003606 dcd_offer->set_use_sctpmap(false);
3607 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3608}
3609
3610// Test that the data channel works when a spec-compliant SCTP m= section is
3611// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3612// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003613TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003614 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3615 ASSERT_TRUE(CreatePeerConnectionWrappers());
3616 ConnectFakeSignaling();
3617 caller()->CreateDataChannel();
3618 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3619 caller()->CreateAndSetAndSignalOffer();
3620 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3621 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3622 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3623 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3624
3625 // Ensure data can be sent in both directions.
3626 std::string data = "hello world";
3627 caller()->data_channel()->Send(DataBuffer(data));
3628 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3629 kDefaultTimeout);
3630 callee()->data_channel()->Send(DataBuffer(data));
3631 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3632 kDefaultTimeout);
3633}
3634
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003635// Tests that the datagram transport to SCTP fallback works correctly when
3636// datagram transport negotiation fails.
3637TEST_P(PeerConnectionIntegrationTest,
3638 DatagramTransportDataChannelFallbackToSctp) {
3639 PeerConnectionInterface::RTCConfiguration rtc_config;
3640 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3641 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3642 rtc_config.use_datagram_transport_for_data_channels = true;
3643
3644 // Configure one endpoint to use datagram transport for data channels while
3645 // the other does not.
3646 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3647 rtc_config, RTCConfiguration(),
3648 loopback_media_transports()->first_factory(), nullptr));
3649 ConnectFakeSignaling();
3650
3651 // The caller offers a data channel using either datagram transport or SCTP.
3652 caller()->CreateDataChannel();
3653 caller()->AddAudioVideoTracks();
3654 callee()->AddAudioVideoTracks();
3655 caller()->CreateAndSetAndSignalOffer();
3656 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3657
3658 // Negotiation should fallback to SCTP, allowing the data channel to be
3659 // established.
3660 ASSERT_NE(nullptr, caller()->data_channel());
3661 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3662 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3663 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3664
3665 // Ensure data can be sent in both directions.
3666 std::string data = "hello world";
3667 caller()->data_channel()->Send(DataBuffer(data));
3668 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3669 kDefaultTimeout);
3670 callee()->data_channel()->Send(DataBuffer(data));
3671 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3672 kDefaultTimeout);
3673
3674 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3675 MediaExpectations media_expectations;
3676 media_expectations.ExpectBidirectionalAudioAndVideo();
3677 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3678}
3679
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07003680// Tests that the data channel transport works correctly when datagram transport
3681// negotiation succeeds and does not fall back to SCTP.
3682TEST_P(PeerConnectionIntegrationTest,
3683 DatagramTransportDataChannelDoesNotFallbackToSctp) {
3684 PeerConnectionInterface::RTCConfiguration rtc_config;
3685 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3686 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3687 rtc_config.use_datagram_transport_for_data_channels = true;
3688
3689 // Configure one endpoint to use datagram transport for data channels while
3690 // the other does not.
3691 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3692 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3693 loopback_media_transports()->second_factory()));
3694 ConnectFakeSignaling();
3695
3696 // The caller offers a data channel using either datagram transport or SCTP.
3697 caller()->CreateDataChannel();
3698 caller()->AddAudioVideoTracks();
3699 callee()->AddAudioVideoTracks();
3700 caller()->CreateAndSetAndSignalOffer();
3701 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3702
3703 // Ensure that the data channel transport is ready.
3704 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3705 loopback_media_transports()->FlushAsyncInvokes();
3706
3707 // Negotiation should succeed, allowing the data channel to be established.
3708 ASSERT_NE(nullptr, caller()->data_channel());
3709 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3710 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3711 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3712
3713 // Ensure data can be sent in both directions.
3714 std::string data = "hello world";
3715 caller()->data_channel()->Send(DataBuffer(data));
3716 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3717 kDefaultTimeout);
3718 callee()->data_channel()->Send(DataBuffer(data));
3719 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3720 kDefaultTimeout);
3721
3722 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3723 MediaExpectations media_expectations;
3724 media_expectations.ExpectBidirectionalAudioAndVideo();
3725 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3726}
3727
Bjorn A Mellem0cda7b82020-01-28 17:06:55 -08003728// Tests that the datagram transport to SCTP fallback works correctly when
3729// datagram transports do not advertise compatible transport parameters.
3730TEST_P(PeerConnectionIntegrationTest,
3731 DatagramTransportIncompatibleParametersFallsBackToSctp) {
3732 PeerConnectionInterface::RTCConfiguration rtc_config;
3733 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3734 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3735 rtc_config.use_datagram_transport_for_data_channels = true;
3736
3737 // By default, only equal parameters are compatible.
3738 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
3739 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
3740
3741 // Configure one endpoint to use datagram transport for data channels while
3742 // the other does not.
3743 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3744 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3745 loopback_media_transports()->second_factory()));
3746 ConnectFakeSignaling();
3747
3748 // The caller offers a data channel using either datagram transport or SCTP.
3749 caller()->CreateDataChannel();
3750 caller()->AddAudioVideoTracks();
3751 callee()->AddAudioVideoTracks();
3752 caller()->CreateAndSetAndSignalOffer();
3753 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3754
3755 // Negotiation should fallback to SCTP, allowing the data channel to be
3756 // established.
3757 ASSERT_NE(nullptr, caller()->data_channel());
3758 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3759 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3760 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3761
3762 // Both endpoints should agree to use SCTP for data channels.
3763 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
3764 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
3765
3766 // Ensure data can be sent in both directions.
3767 std::string data = "hello world";
3768 caller()->data_channel()->Send(DataBuffer(data));
3769 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3770 kDefaultTimeout);
3771 callee()->data_channel()->Send(DataBuffer(data));
3772 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3773 kDefaultTimeout);
3774
3775 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3776 MediaExpectations media_expectations;
3777 media_expectations.ExpectBidirectionalAudioAndVideo();
3778 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3779}
3780
3781// Tests that the datagram transport to SCTP fallback works correctly when
3782// only the answerer believes datagram transport parameters are incompatible.
3783TEST_P(PeerConnectionIntegrationTest,
3784 DatagramTransportIncompatibleParametersOnAnswererFallsBackToSctp) {
3785 PeerConnectionInterface::RTCConfiguration rtc_config;
3786 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3787 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3788 rtc_config.use_datagram_transport_for_data_channels = true;
3789
3790 // By default, only equal parameters are compatible.
3791 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
3792 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
3793
3794 // Set the offerer to accept different parameters, while the answerer rejects
3795 // them.
3796 loopback_media_transports()->SetFirstDatagramTransportParametersComparison(
3797 [](absl::string_view a, absl::string_view b) { return true; });
3798 loopback_media_transports()->SetSecondDatagramTransportParametersComparison(
3799 [](absl::string_view a, absl::string_view b) { return false; });
3800
3801 // Configure one endpoint to use datagram transport for data channels while
3802 // the other does not.
3803 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3804 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3805 loopback_media_transports()->second_factory()));
3806 ConnectFakeSignaling();
3807
3808 // The caller offers a data channel using either datagram transport or SCTP.
3809 caller()->CreateDataChannel();
3810 caller()->AddAudioVideoTracks();
3811 callee()->AddAudioVideoTracks();
3812 caller()->CreateAndSetAndSignalOffer();
3813 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3814
3815 // Negotiation should fallback to SCTP, allowing the data channel to be
3816 // established.
3817 ASSERT_NE(nullptr, caller()->data_channel());
3818 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3819 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3820 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3821
3822 // Both endpoints should agree to use SCTP for data channels.
3823 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
3824 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
3825
3826 // Ensure data can be sent in both directions.
3827 std::string data = "hello world";
3828 caller()->data_channel()->Send(DataBuffer(data));
3829 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3830 kDefaultTimeout);
3831 callee()->data_channel()->Send(DataBuffer(data));
3832 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3833 kDefaultTimeout);
3834
3835 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3836 MediaExpectations media_expectations;
3837 media_expectations.ExpectBidirectionalAudioAndVideo();
3838 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3839}
3840
3841// Tests that the data channel transport works correctly when datagram
3842// transports provide different, but compatible, transport parameters.
3843TEST_P(PeerConnectionIntegrationTest,
3844 DatagramTransportCompatibleParametersDoNotFallbackToSctp) {
3845 PeerConnectionInterface::RTCConfiguration rtc_config;
3846 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3847 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3848 rtc_config.use_datagram_transport_for_data_channels = true;
3849
3850 // By default, only equal parameters are compatible.
3851 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
3852 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
3853
3854 // Change the comparison used to treat these transport parameters are
3855 // compatible (on both sides).
3856 loopback_media_transports()->SetFirstDatagramTransportParametersComparison(
3857 [](absl::string_view a, absl::string_view b) { return true; });
3858 loopback_media_transports()->SetSecondDatagramTransportParametersComparison(
3859 [](absl::string_view a, absl::string_view b) { return true; });
3860
3861 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3862 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3863 loopback_media_transports()->second_factory()));
3864 ConnectFakeSignaling();
3865
3866 // The caller offers a data channel using either datagram transport or SCTP.
3867 caller()->CreateDataChannel();
3868 caller()->AddAudioVideoTracks();
3869 callee()->AddAudioVideoTracks();
3870 caller()->CreateAndSetAndSignalOffer();
3871 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3872
3873 // Ensure that the data channel transport is ready.
3874 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3875 loopback_media_transports()->FlushAsyncInvokes();
3876
3877 // Negotiation should succeed, allowing the data channel to be established.
3878 ASSERT_NE(nullptr, caller()->data_channel());
3879 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3880 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3881 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3882
3883 // Both endpoints should agree to use datagram transport for data channels.
3884 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
3885 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
3886
3887 // Ensure data can be sent in both directions.
3888 std::string data = "hello world";
3889 caller()->data_channel()->Send(DataBuffer(data));
3890 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3891 kDefaultTimeout);
3892 callee()->data_channel()->Send(DataBuffer(data));
3893 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3894 kDefaultTimeout);
3895
3896 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3897 MediaExpectations media_expectations;
3898 media_expectations.ExpectBidirectionalAudioAndVideo();
3899 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3900}
3901
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07003902TEST_P(PeerConnectionIntegrationTest,
3903 DatagramTransportDataChannelWithMediaOnCaller) {
3904 // Configure the caller to attempt use of datagram transport for media and
3905 // data channels.
3906 PeerConnectionInterface::RTCConfiguration offerer_config;
3907 offerer_config.rtcp_mux_policy =
3908 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3909 offerer_config.bundle_policy =
3910 PeerConnectionInterface::kBundlePolicyMaxBundle;
3911 offerer_config.use_datagram_transport_for_data_channels = true;
3912 offerer_config.use_datagram_transport = true;
3913
3914 // Configure the callee to only use datagram transport for data channels.
3915 PeerConnectionInterface::RTCConfiguration answerer_config;
3916 answerer_config.rtcp_mux_policy =
3917 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3918 answerer_config.bundle_policy =
3919 PeerConnectionInterface::kBundlePolicyMaxBundle;
3920 answerer_config.use_datagram_transport_for_data_channels = true;
3921
3922 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3923 offerer_config, answerer_config,
3924 loopback_media_transports()->first_factory(),
3925 loopback_media_transports()->second_factory()));
3926 ConnectFakeSignaling();
3927
3928 // Offer both media and data.
3929 caller()->AddAudioVideoTracks();
3930 callee()->AddAudioVideoTracks();
3931 caller()->CreateDataChannel();
3932 caller()->CreateAndSetAndSignalOffer();
3933 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3934
3935 // Ensure that the data channel transport is ready.
3936 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3937 loopback_media_transports()->FlushAsyncInvokes();
3938
3939 ASSERT_NE(nullptr, caller()->data_channel());
3940 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3941 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3942 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3943
3944 // Both endpoints should agree to use datagram transport for data channels.
3945 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
3946 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
3947
3948 // Ensure data can be sent in both directions.
3949 std::string data = "hello world";
3950 caller()->data_channel()->Send(DataBuffer(data));
3951 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3952 kDefaultTimeout);
3953 callee()->data_channel()->Send(DataBuffer(data));
3954 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3955 kDefaultTimeout);
3956
3957 // Media flow should not be impacted.
3958 MediaExpectations media_expectations;
3959 media_expectations.ExpectBidirectionalAudioAndVideo();
3960 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3961}
3962
3963TEST_P(PeerConnectionIntegrationTest,
3964 DatagramTransportMediaWithDataChannelOnCaller) {
3965 // Configure the caller to attempt use of datagram transport for media and
3966 // data channels.
3967 PeerConnectionInterface::RTCConfiguration offerer_config;
3968 offerer_config.rtcp_mux_policy =
3969 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3970 offerer_config.bundle_policy =
3971 PeerConnectionInterface::kBundlePolicyMaxBundle;
3972 offerer_config.use_datagram_transport_for_data_channels = true;
3973 offerer_config.use_datagram_transport = true;
3974
3975 // Configure the callee to only use datagram transport for media.
3976 PeerConnectionInterface::RTCConfiguration answerer_config;
3977 answerer_config.rtcp_mux_policy =
3978 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3979 answerer_config.bundle_policy =
3980 PeerConnectionInterface::kBundlePolicyMaxBundle;
3981 answerer_config.use_datagram_transport = true;
3982
3983 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3984 offerer_config, answerer_config,
3985 loopback_media_transports()->first_factory(),
3986 loopback_media_transports()->second_factory()));
3987 ConnectFakeSignaling();
3988
3989 // Offer both media and data.
3990 caller()->AddAudioVideoTracks();
3991 callee()->AddAudioVideoTracks();
3992 caller()->CreateDataChannel();
3993 caller()->CreateAndSetAndSignalOffer();
3994 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3995
3996 // Ensure that the data channel transport is ready.
3997 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3998 loopback_media_transports()->FlushAsyncInvokes();
3999
4000 ASSERT_NE(nullptr, caller()->data_channel());
4001 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4002 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4003 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4004
4005 // Both endpoints should agree to use SCTP for data channels.
4006 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4007 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4008
4009 // Ensure data can be sent in both directions.
4010 std::string data = "hello world";
4011 caller()->data_channel()->Send(DataBuffer(data));
4012 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4013 kDefaultTimeout);
4014 callee()->data_channel()->Send(DataBuffer(data));
4015 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4016 kDefaultTimeout);
4017
4018 // Media flow should not be impacted.
4019 MediaExpectations media_expectations;
4020 media_expectations.ExpectBidirectionalAudioAndVideo();
4021 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4022}
4023
4024TEST_P(PeerConnectionIntegrationTest,
4025 DatagramTransportDataChannelWithMediaOnCallee) {
4026 // Configure the caller to attempt use of datagram transport for data
4027 // channels.
4028 PeerConnectionInterface::RTCConfiguration offerer_config;
4029 offerer_config.rtcp_mux_policy =
4030 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4031 offerer_config.bundle_policy =
4032 PeerConnectionInterface::kBundlePolicyMaxBundle;
4033 offerer_config.use_datagram_transport_for_data_channels = true;
4034
4035 // Configure the callee to use datagram transport for data channels and media.
4036 PeerConnectionInterface::RTCConfiguration answerer_config;
4037 answerer_config.rtcp_mux_policy =
4038 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4039 answerer_config.bundle_policy =
4040 PeerConnectionInterface::kBundlePolicyMaxBundle;
4041 answerer_config.use_datagram_transport_for_data_channels = true;
4042 answerer_config.use_datagram_transport = true;
4043
4044 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4045 offerer_config, answerer_config,
4046 loopback_media_transports()->first_factory(),
4047 loopback_media_transports()->second_factory()));
4048 ConnectFakeSignaling();
4049
4050 // Offer both media and data.
4051 caller()->AddAudioVideoTracks();
4052 callee()->AddAudioVideoTracks();
4053 caller()->CreateDataChannel();
4054 caller()->CreateAndSetAndSignalOffer();
4055 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4056
4057 // Ensure that the data channel transport is ready.
4058 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4059 loopback_media_transports()->FlushAsyncInvokes();
4060
4061 ASSERT_NE(nullptr, caller()->data_channel());
4062 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4063 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4064 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4065
4066 // Both endpoints should agree to use datagram transport for data channels.
4067 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4068 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4069
4070 // Ensure data can be sent in both directions.
4071 std::string data = "hello world";
4072 caller()->data_channel()->Send(DataBuffer(data));
4073 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4074 kDefaultTimeout);
4075 callee()->data_channel()->Send(DataBuffer(data));
4076 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4077 kDefaultTimeout);
4078
4079 // Media flow should not be impacted.
4080 MediaExpectations media_expectations;
4081 media_expectations.ExpectBidirectionalAudioAndVideo();
4082 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4083}
4084
4085TEST_P(PeerConnectionIntegrationTest,
4086 DatagramTransportMediaWithDataChannelOnCallee) {
4087 // Configure the caller to attempt use of datagram transport for media.
4088 PeerConnectionInterface::RTCConfiguration offerer_config;
4089 offerer_config.rtcp_mux_policy =
4090 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4091 offerer_config.bundle_policy =
4092 PeerConnectionInterface::kBundlePolicyMaxBundle;
4093 offerer_config.use_datagram_transport = true;
4094
4095 // Configure the callee to only use datagram transport for media and data
4096 // channels.
4097 PeerConnectionInterface::RTCConfiguration answerer_config;
4098 answerer_config.rtcp_mux_policy =
4099 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4100 answerer_config.bundle_policy =
4101 PeerConnectionInterface::kBundlePolicyMaxBundle;
4102 answerer_config.use_datagram_transport = true;
4103 answerer_config.use_datagram_transport_for_data_channels = true;
4104
4105 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4106 offerer_config, answerer_config,
4107 loopback_media_transports()->first_factory(),
4108 loopback_media_transports()->second_factory()));
4109 ConnectFakeSignaling();
4110
4111 // Offer both media and data.
4112 caller()->AddAudioVideoTracks();
4113 callee()->AddAudioVideoTracks();
4114 caller()->CreateDataChannel();
4115 caller()->CreateAndSetAndSignalOffer();
4116 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4117
4118 // Ensure that the data channel transport is ready.
4119 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4120 loopback_media_transports()->FlushAsyncInvokes();
4121
4122 ASSERT_NE(nullptr, caller()->data_channel());
4123 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4124 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4125 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4126
4127 // Both endpoints should agree to use SCTP for data channels.
4128 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4129 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4130
4131 // Ensure data can be sent in both directions.
4132 std::string data = "hello world";
4133 caller()->data_channel()->Send(DataBuffer(data));
4134 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4135 kDefaultTimeout);
4136 callee()->data_channel()->Send(DataBuffer(data));
4137 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4138 kDefaultTimeout);
4139
4140 // Media flow should not be impacted.
4141 MediaExpectations media_expectations;
4142 media_expectations.ExpectBidirectionalAudioAndVideo();
4143 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4144}
4145
4146TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelAndMedia) {
4147 // Configure the caller to use datagram transport for data channels and media.
4148 PeerConnectionInterface::RTCConfiguration offerer_config;
4149 offerer_config.rtcp_mux_policy =
4150 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4151 offerer_config.bundle_policy =
4152 PeerConnectionInterface::kBundlePolicyMaxBundle;
4153 offerer_config.use_datagram_transport_for_data_channels = true;
4154 offerer_config.use_datagram_transport = true;
4155
4156 // Configure the callee to use datagram transport for data channels and media.
4157 PeerConnectionInterface::RTCConfiguration answerer_config;
4158 answerer_config.rtcp_mux_policy =
4159 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4160 answerer_config.bundle_policy =
4161 PeerConnectionInterface::kBundlePolicyMaxBundle;
4162 answerer_config.use_datagram_transport_for_data_channels = true;
4163 answerer_config.use_datagram_transport = true;
4164
4165 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4166 offerer_config, answerer_config,
4167 loopback_media_transports()->first_factory(),
4168 loopback_media_transports()->second_factory()));
4169 ConnectFakeSignaling();
4170
4171 // Offer both media and data.
4172 caller()->AddAudioVideoTracks();
4173 callee()->AddAudioVideoTracks();
4174 caller()->CreateDataChannel();
4175 caller()->CreateAndSetAndSignalOffer();
4176 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4177
4178 // Ensure that the data channel transport is ready.
4179 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4180 loopback_media_transports()->FlushAsyncInvokes();
4181
4182 ASSERT_NE(nullptr, caller()->data_channel());
4183 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4184 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4185 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4186
4187 // Both endpoints should agree to use datagram transport for data channels.
4188 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4189 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4190
4191 // Ensure data can be sent in both directions.
4192 std::string data = "hello world";
4193 caller()->data_channel()->Send(DataBuffer(data));
4194 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4195 kDefaultTimeout);
4196 callee()->data_channel()->Send(DataBuffer(data));
4197 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4198 kDefaultTimeout);
4199
4200 // Media flow should not be impacted.
4201 MediaExpectations media_expectations;
4202 media_expectations.ExpectBidirectionalAudioAndVideo();
4203 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4204}
4205
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004206// Tests that data channels use SCTP instead of datagram transport if datagram
4207// transport is configured in receive-only mode on the caller.
4208TEST_P(PeerConnectionIntegrationTest,
4209 DatagramTransportDataChannelReceiveOnlyOnCallerUsesSctp) {
4210 PeerConnectionInterface::RTCConfiguration rtc_config;
4211 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4212 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4213 rtc_config.use_datagram_transport_for_data_channels = true;
4214 rtc_config.use_datagram_transport_for_data_channels_receive_only = true;
4215
4216 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4217 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4218 loopback_media_transports()->second_factory()));
4219 ConnectFakeSignaling();
4220
4221 // The caller should offer a data channel using SCTP.
4222 caller()->CreateDataChannel();
4223 caller()->AddAudioVideoTracks();
4224 callee()->AddAudioVideoTracks();
4225 caller()->CreateAndSetAndSignalOffer();
4226 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4227
4228 ASSERT_NE(nullptr, caller()->data_channel());
4229 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4230 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4231 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4232
4233 // SCTP transports should be present, since they are in use.
4234 EXPECT_NE(caller()->pc()->GetSctpTransport(), nullptr);
4235 EXPECT_NE(callee()->pc()->GetSctpTransport(), nullptr);
4236
4237 // Ensure data can be sent in both directions.
4238 std::string data = "hello world";
4239 caller()->data_channel()->Send(DataBuffer(data));
4240 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4241 kDefaultTimeout);
4242 callee()->data_channel()->Send(DataBuffer(data));
4243 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4244 kDefaultTimeout);
4245}
4246
deadbeef1dcb1642017-03-29 21:08:16 -07004247#endif // HAVE_SCTP
4248
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004249// Tests that a callee configured for receive-only use of datagram transport
4250// data channels accepts them on incoming calls.
4251TEST_P(PeerConnectionIntegrationTest,
4252 DatagramTransportDataChannelReceiveOnlyOnCallee) {
4253 PeerConnectionInterface::RTCConfiguration offerer_config;
4254 offerer_config.rtcp_mux_policy =
4255 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4256 offerer_config.bundle_policy =
4257 PeerConnectionInterface::kBundlePolicyMaxBundle;
4258 offerer_config.use_datagram_transport_for_data_channels = true;
4259
4260 PeerConnectionInterface::RTCConfiguration answerer_config;
4261 answerer_config.rtcp_mux_policy =
4262 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4263 answerer_config.bundle_policy =
4264 PeerConnectionInterface::kBundlePolicyMaxBundle;
4265 answerer_config.use_datagram_transport_for_data_channels = true;
4266 answerer_config.use_datagram_transport_for_data_channels_receive_only = true;
4267
4268 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4269 offerer_config, answerer_config,
4270 loopback_media_transports()->first_factory(),
4271 loopback_media_transports()->second_factory()));
4272 ConnectFakeSignaling();
4273
4274 caller()->CreateDataChannel();
4275 caller()->CreateAndSetAndSignalOffer();
4276 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4277
4278 // Ensure that the data channel transport is ready.
4279 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4280 loopback_media_transports()->FlushAsyncInvokes();
4281
4282 ASSERT_NE(nullptr, caller()->data_channel());
4283 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4284 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4285 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4286
4287 // SCTP transports should not be present, since datagram transport is used.
4288 EXPECT_EQ(caller()->pc()->GetSctpTransport(), nullptr);
4289 EXPECT_EQ(callee()->pc()->GetSctpTransport(), nullptr);
4290
4291 // Ensure data can be sent in both directions.
4292 std::string data = "hello world";
4293 caller()->data_channel()->Send(DataBuffer(data));
4294 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4295 kDefaultTimeout);
4296 callee()->data_channel()->Send(DataBuffer(data));
4297 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4298 kDefaultTimeout);
4299}
4300
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004301// This test sets up a call between two parties with a datagram transport data
4302// channel.
4303TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelEndToEnd) {
4304 PeerConnectionInterface::RTCConfiguration rtc_config;
4305 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4306 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4307 rtc_config.use_datagram_transport_for_data_channels = true;
4308 rtc_config.enable_dtls_srtp = false;
4309 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4310 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4311 loopback_media_transports()->second_factory()));
4312 ConnectFakeSignaling();
4313
4314 // Expect that data channel created on caller side will show up for callee as
4315 // well.
4316 caller()->CreateDataChannel();
4317 caller()->CreateAndSetAndSignalOffer();
4318 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4319
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004320 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004321 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4322 loopback_media_transports()->FlushAsyncInvokes();
4323
4324 // Caller data channel should already exist (it created one). Callee data
4325 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4326 ASSERT_NE(nullptr, caller()->data_channel());
4327 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4328 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4329 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4330
4331 // Ensure data can be sent in both directions.
4332 std::string data = "hello world";
4333 caller()->data_channel()->Send(DataBuffer(data));
4334 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4335 kDefaultTimeout);
4336 callee()->data_channel()->Send(DataBuffer(data));
4337 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4338 kDefaultTimeout);
4339}
4340
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004341// Tests that 'zero-rtt' data channel transports (which are ready-to-send as
4342// soon as they're created) work correctly.
4343TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelZeroRtt) {
4344 PeerConnectionInterface::RTCConfiguration rtc_config;
4345 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4346 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4347 rtc_config.use_datagram_transport_for_data_channels = true;
4348 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
4349 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4350 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4351 loopback_media_transports()->second_factory()));
4352 ConnectFakeSignaling();
4353
4354 // Ensure that the callee's media transport is ready-to-send immediately.
4355 // Note that only the callee can become writable in zero RTTs. The caller
4356 // must wait for the callee's answer.
4357 loopback_media_transports()->SetSecondStateAfterConnect(
4358 webrtc::MediaTransportState::kWritable);
4359 loopback_media_transports()->FlushAsyncInvokes();
4360
4361 // Expect that data channel created on caller side will show up for callee as
4362 // well.
4363 caller()->CreateDataChannel();
4364 caller()->CreateAndSetAndSignalOffer();
4365 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4366
4367 loopback_media_transports()->SetFirstState(
4368 webrtc::MediaTransportState::kWritable);
4369 loopback_media_transports()->FlushAsyncInvokes();
4370
4371 // Caller data channel should already exist (it created one). Callee data
4372 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4373 ASSERT_NE(nullptr, caller()->data_channel());
4374 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4375 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4376 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4377
4378 // Ensure data can be sent in both directions.
4379 std::string data = "hello world";
4380 caller()->data_channel()->Send(DataBuffer(data));
4381 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4382 kDefaultTimeout);
4383 callee()->data_channel()->Send(DataBuffer(data));
4384 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4385 kDefaultTimeout);
4386}
4387
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004388// Ensures that when the callee closes a datagram transport data channel, the
4389// closing procedure results in the data channel being closed for the caller
4390// as well.
4391TEST_P(PeerConnectionIntegrationTest,
4392 DatagramTransportDataChannelCalleeCloses) {
4393 PeerConnectionInterface::RTCConfiguration rtc_config;
4394 rtc_config.use_datagram_transport_for_data_channels = true;
4395 rtc_config.enable_dtls_srtp = false;
4396 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4397 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4398 loopback_media_transports()->second_factory()));
4399 ConnectFakeSignaling();
4400
4401 // Create a data channel on the caller and signal it to the callee.
4402 caller()->CreateDataChannel();
4403 caller()->CreateAndSetAndSignalOffer();
4404 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4405
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004406 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004407 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4408 loopback_media_transports()->FlushAsyncInvokes();
4409
4410 // Data channels exist and open on both ends of the connection.
4411 ASSERT_NE(nullptr, caller()->data_channel());
4412 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4413 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4414 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4415
4416 // Close the data channel on the callee side, and wait for it to reach the
4417 // "closed" state on both sides.
4418 callee()->data_channel()->Close();
4419 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
4420 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
4421}
4422
4423// Tests that datagram transport data channels can do in-band negotiation.
4424TEST_P(PeerConnectionIntegrationTest,
4425 DatagramTransportDataChannelConfigSentToOtherSide) {
4426 PeerConnectionInterface::RTCConfiguration rtc_config;
4427 rtc_config.use_datagram_transport_for_data_channels = true;
4428 rtc_config.enable_dtls_srtp = false;
4429 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4430 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4431 loopback_media_transports()->second_factory()));
4432 ConnectFakeSignaling();
4433
4434 // Create a data channel with a non-default configuration and signal it to the
4435 // callee.
4436 webrtc::DataChannelInit init;
4437 init.id = 53;
4438 init.maxRetransmits = 52;
4439 caller()->CreateDataChannel("data-channel", &init);
4440 caller()->CreateAndSetAndSignalOffer();
4441 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4442
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004443 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004444 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4445 loopback_media_transports()->FlushAsyncInvokes();
4446
4447 // Ensure that the data channel exists on the callee with the correct
4448 // configuration.
4449 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4450 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4451 // Since "negotiate" is false, the "id" parameter is ignored.
4452 EXPECT_NE(init.id, callee()->data_channel()->id());
4453 EXPECT_EQ("data-channel", callee()->data_channel()->label());
4454 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
4455 EXPECT_FALSE(callee()->data_channel()->negotiated());
4456}
4457
4458TEST_P(PeerConnectionIntegrationTest,
4459 DatagramTransportDataChannelRejectedWithNoFallback) {
4460 PeerConnectionInterface::RTCConfiguration offerer_config;
4461 offerer_config.rtcp_mux_policy =
4462 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4463 offerer_config.bundle_policy =
4464 PeerConnectionInterface::kBundlePolicyMaxBundle;
4465 offerer_config.use_datagram_transport_for_data_channels = true;
4466 // Disabling DTLS precludes a fallback to SCTP.
4467 offerer_config.enable_dtls_srtp = false;
4468
4469 PeerConnectionInterface::RTCConfiguration answerer_config;
4470 answerer_config.rtcp_mux_policy =
4471 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4472 answerer_config.bundle_policy =
4473 PeerConnectionInterface::kBundlePolicyMaxBundle;
4474 // Both endpoints must disable DTLS or SetRemoteDescription will fail.
4475 answerer_config.enable_dtls_srtp = false;
4476
4477 // Configure one endpoint to use datagram transport for data channels while
4478 // the other does not.
4479 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4480 offerer_config, answerer_config,
4481 loopback_media_transports()->first_factory(), nullptr));
4482 ConnectFakeSignaling();
4483
4484 // The caller offers a data channel using either datagram transport or SCTP.
4485 caller()->CreateDataChannel();
4486 caller()->AddAudioVideoTracks();
4487 callee()->AddAudioVideoTracks();
4488 caller()->CreateAndSetAndSignalOffer();
4489 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4490
4491 // Caller data channel should already exist (it created one). Callee data
4492 // channel should not exist, since negotiation happens in-band, not in SDP.
4493 EXPECT_NE(nullptr, caller()->data_channel());
4494 EXPECT_EQ(nullptr, callee()->data_channel());
4495
4496 // The caller's data channel should close when the datagram transport is
4497 // rejected.
4498 EXPECT_FALSE(caller()->data_observer()->IsOpen());
4499
4500 // Media flow should not be impacted by the failed data channel.
4501 MediaExpectations media_expectations;
4502 media_expectations.ExpectBidirectionalAudioAndVideo();
4503 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4504}
4505
deadbeef1dcb1642017-03-29 21:08:16 -07004506// Test that the ICE connection and gathering states eventually reach
4507// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08004508TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07004509 ASSERT_TRUE(CreatePeerConnectionWrappers());
4510 ConnectFakeSignaling();
4511 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08004512 caller()->AddAudioVideoTracks();
4513 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004514 caller()->CreateAndSetAndSignalOffer();
4515 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4516 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4517 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
4518 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4519 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
4520 // After the best candidate pair is selected and all candidates are signaled,
4521 // the ICE connection state should reach "complete".
4522 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
4523 // answerer/"callee" by default) only reaches "connected". When this is
4524 // fixed, this test should be updated.
4525 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4526 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00004527 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4528 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07004529}
4530
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004531constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
4532 cricket::PORTALLOCATOR_DISABLE_RELAY |
4533 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004534
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004535// Use a mock resolver to resolve the hostname back to the original IP on both
4536// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004537TEST_P(PeerConnectionIntegrationTest,
4538 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004539 auto caller_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004540 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004541 auto callee_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004542 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004543 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
4544 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004545
4546 // This also verifies that the injected AsyncResolverFactory is used by
4547 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004548 EXPECT_CALL(*caller_resolver_factory, Create())
4549 .WillOnce(Return(&caller_async_resolver));
4550 webrtc::PeerConnectionDependencies caller_deps(nullptr);
4551 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
4552
4553 EXPECT_CALL(*callee_resolver_factory, Create())
4554 .WillOnce(Return(&callee_async_resolver));
4555 webrtc::PeerConnectionDependencies callee_deps(nullptr);
4556 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
4557
4558 PeerConnectionInterface::RTCConfiguration config;
4559 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4560 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4561
4562 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4563 config, std::move(caller_deps), config, std::move(callee_deps)));
4564
4565 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
4566 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
4567
4568 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07004569 caller()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004570 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wangecd30542019-05-22 14:34:56 -07004571 callee()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004572 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004573
4574 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004575
4576 ConnectFakeSignaling();
4577 caller()->AddAudioVideoTracks();
4578 callee()->AddAudioVideoTracks();
4579 caller()->CreateAndSetAndSignalOffer();
4580 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4581 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4582 caller()->ice_connection_state(), kDefaultTimeout);
4583 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4584 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08004585
Ying Wangef3998f2019-12-09 13:06:53 +01004586 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
4587 "WebRTC.PeerConnection.CandidatePairType_UDP",
4588 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004589}
4590
Steve Antonede9ca52017-10-16 13:04:27 -07004591// Test that firewalling the ICE connection causes the clients to identify the
4592// disconnected state and then removing the firewall causes them to reconnect.
4593class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004594 : public PeerConnectionIntegrationBaseTest,
4595 public ::testing::WithParamInterface<
4596 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07004597 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004598 PeerConnectionIntegrationIceStatesTest()
4599 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
4600 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07004601 }
4602
4603 void StartStunServer(const SocketAddress& server_address) {
4604 stun_server_.reset(
4605 cricket::TestStunServer::Create(network_thread(), server_address));
4606 }
4607
4608 bool TestIPv6() {
4609 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
4610 }
4611
4612 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004613 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
4614 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07004615 }
4616
4617 std::vector<SocketAddress> CallerAddresses() {
4618 std::vector<SocketAddress> addresses;
4619 addresses.push_back(SocketAddress("1.1.1.1", 0));
4620 if (TestIPv6()) {
4621 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
4622 }
4623 return addresses;
4624 }
4625
4626 std::vector<SocketAddress> CalleeAddresses() {
4627 std::vector<SocketAddress> addresses;
4628 addresses.push_back(SocketAddress("2.2.2.2", 0));
4629 if (TestIPv6()) {
4630 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
4631 }
4632 return addresses;
4633 }
4634
4635 void SetUpNetworkInterfaces() {
4636 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07004637 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
4638 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07004639
4640 // Add network addresses for test.
4641 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004642 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004643 }
4644 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004645 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004646 }
4647 }
4648
4649 private:
4650 uint32_t port_allocator_flags_;
4651 std::unique_ptr<cricket::TestStunServer> stun_server_;
4652};
4653
Yves Gerey100fe632020-01-17 19:15:53 +01004654// Ensure FakeClockForTest is constructed first (see class for rationale).
4655class PeerConnectionIntegrationIceStatesTestWithFakeClock
4656 : public FakeClockForTest,
4657 public PeerConnectionIntegrationIceStatesTest {};
4658
Steve Antonede9ca52017-10-16 13:04:27 -07004659// Tests that the PeerConnection goes through all the ICE gathering/connection
4660// states over the duration of the call. This includes Disconnected and Failed
4661// states, induced by putting a firewall between the peers and waiting for them
4662// to time out.
Yves Gerey100fe632020-01-17 19:15:53 +01004663TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock, VerifyIceStates) {
Steve Antonede9ca52017-10-16 13:04:27 -07004664 const SocketAddress kStunServerAddress =
4665 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
4666 StartStunServer(kStunServerAddress);
4667
4668 PeerConnectionInterface::RTCConfiguration config;
4669 PeerConnectionInterface::IceServer ice_stun_server;
4670 ice_stun_server.urls.push_back(
4671 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4672 kStunServerAddress.PortAsString());
4673 config.servers.push_back(ice_stun_server);
4674
4675 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4676 ConnectFakeSignaling();
4677 SetPortAllocatorFlags();
4678 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004679 caller()->AddAudioVideoTracks();
4680 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004681
4682 // Initial state before anything happens.
4683 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4684 caller()->ice_gathering_state());
4685 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4686 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004687 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4688 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004689
4690 // Start the call by creating the offer, setting it as the local description,
4691 // then sending it to the peer who will respond with an answer. This happens
4692 // asynchronously so that we can watch the states as it runs in the
4693 // background.
4694 caller()->CreateAndSetAndSignalOffer();
4695
Steve Antona9b67ce2020-01-16 14:00:44 -08004696 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4697 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004698 FakeClock());
Steve Antona9b67ce2020-01-16 14:00:44 -08004699 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4700 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004701 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004702
4703 // Verify that the observer was notified of the intermediate transitions.
4704 EXPECT_THAT(caller()->ice_connection_state_history(),
4705 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4706 PeerConnectionInterface::kIceConnectionConnected,
4707 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004708 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4709 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4710 PeerConnectionInterface::kIceConnectionConnected,
4711 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004712 EXPECT_THAT(
4713 caller()->peer_connection_state_history(),
4714 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004715 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004716 EXPECT_THAT(caller()->ice_gathering_state_history(),
4717 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4718 PeerConnectionInterface::kIceGatheringComplete));
4719
4720 // Block connections to/from the caller and wait for ICE to become
4721 // disconnected.
4722 for (const auto& caller_address : CallerAddresses()) {
4723 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4724 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004725 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004726 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4727 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004728 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004729 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4730 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004731 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004732
4733 // Let ICE re-establish by removing the firewall rules.
4734 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004735 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004736 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4737 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004738 FakeClock());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004739 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004740 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004741 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004742
4743 // According to RFC7675, if there is no response within 30 seconds then the
4744 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004745 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004746 constexpr int kConsentTimeout = 30000;
4747 for (const auto& caller_address : CallerAddresses()) {
4748 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4749 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004750 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004751 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4752 caller()->ice_connection_state(), kConsentTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004753 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004754 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4755 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004756 kConsentTimeout, FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004757}
4758
4759// Tests that if the connection doesn't get set up properly we eventually reach
4760// the "failed" iceConnectionState.
Yves Gerey100fe632020-01-17 19:15:53 +01004761TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock,
4762 IceStateSetupFailure) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004763 // Block connections to/from the caller and wait for ICE to become
4764 // disconnected.
4765 for (const auto& caller_address : CallerAddresses()) {
4766 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4767 }
4768
4769 ASSERT_TRUE(CreatePeerConnectionWrappers());
4770 ConnectFakeSignaling();
4771 SetPortAllocatorFlags();
4772 SetUpNetworkInterfaces();
4773 caller()->AddAudioVideoTracks();
4774 caller()->CreateAndSetAndSignalOffer();
4775
4776 // According to RFC7675, if there is no response within 30 seconds then the
4777 // peer should consider the other side to have rejected the connection. This
4778 // is signaled by the state transitioning to "failed".
4779 constexpr int kConsentTimeout = 30000;
4780 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4781 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004782 kConsentTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004783}
4784
4785// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4786// and that the statistics in the metric observers are updated correctly.
4787TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4788 ASSERT_TRUE(CreatePeerConnectionWrappers());
4789 ConnectFakeSignaling();
4790 SetPortAllocatorFlags();
4791 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004792 caller()->AddAudioVideoTracks();
4793 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004794 caller()->CreateAndSetAndSignalOffer();
4795
4796 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton692f3c72020-01-16 14:12:31 -08004797 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4798 caller()->ice_connection_state(), kDefaultTimeout);
4799 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4800 callee()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07004801
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004802 // TODO(bugs.webrtc.org/9456): Fix it.
4803 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4804 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4805 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4806 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004807 if (TestIPv6()) {
4808 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4809 // connection.
Ying Wangef3998f2019-12-09 13:06:53 +01004810 EXPECT_METRIC_EQ(0, num_best_ipv4);
4811 EXPECT_METRIC_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004812 } else {
Ying Wangef3998f2019-12-09 13:06:53 +01004813 EXPECT_METRIC_EQ(1, num_best_ipv4);
4814 EXPECT_METRIC_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004815 }
4816
Ying Wangef3998f2019-12-09 13:06:53 +01004817 EXPECT_METRIC_EQ(0, webrtc::metrics::NumEvents(
4818 "WebRTC.PeerConnection.CandidatePairType_UDP",
4819 webrtc::kIceCandidatePairHostHost));
4820 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
4821 "WebRTC.PeerConnection.CandidatePairType_UDP",
4822 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004823}
4824
4825constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4826 cricket::PORTALLOCATOR_DISABLE_STUN |
4827 cricket::PORTALLOCATOR_DISABLE_RELAY;
4828constexpr uint32_t kFlagsIPv6NoStun =
4829 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4830 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4831constexpr uint32_t kFlagsIPv4Stun =
4832 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4833
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004834INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004835 PeerConnectionIntegrationTest,
4836 PeerConnectionIntegrationIceStatesTest,
4837 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4838 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4839 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4840 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004841
Yves Gerey100fe632020-01-17 19:15:53 +01004842INSTANTIATE_TEST_SUITE_P(
4843 PeerConnectionIntegrationTest,
4844 PeerConnectionIntegrationIceStatesTestWithFakeClock,
4845 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4846 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4847 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4848 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
4849
deadbeef1dcb1642017-03-29 21:08:16 -07004850// This test sets up a call between two parties with audio and video.
4851// During the call, the caller restarts ICE and the test verifies that
4852// new ICE candidates are generated and audio and video still can flow, and the
4853// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004854TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004855 ASSERT_TRUE(CreatePeerConnectionWrappers());
4856 ConnectFakeSignaling();
4857 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004858 caller()->AddAudioVideoTracks();
4859 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004860 caller()->CreateAndSetAndSignalOffer();
4861 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4862 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4863 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004864 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4865 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004866
4867 // To verify that the ICE restart actually occurs, get
4868 // ufrag/password/candidates before and after restart.
4869 // Create an SDP string of the first audio candidate for both clients.
4870 const webrtc::IceCandidateCollection* audio_candidates_caller =
4871 caller()->pc()->local_description()->candidates(0);
4872 const webrtc::IceCandidateCollection* audio_candidates_callee =
4873 callee()->pc()->local_description()->candidates(0);
4874 ASSERT_GT(audio_candidates_caller->count(), 0u);
4875 ASSERT_GT(audio_candidates_callee->count(), 0u);
4876 std::string caller_candidate_pre_restart;
4877 ASSERT_TRUE(
4878 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4879 std::string callee_candidate_pre_restart;
4880 ASSERT_TRUE(
4881 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4882 const cricket::SessionDescription* desc =
4883 caller()->pc()->local_description()->description();
4884 std::string caller_ufrag_pre_restart =
4885 desc->transport_infos()[0].description.ice_ufrag;
4886 desc = callee()->pc()->local_description()->description();
4887 std::string callee_ufrag_pre_restart =
4888 desc->transport_infos()[0].description.ice_ufrag;
4889
Alex Drake00c7ecf2019-08-06 10:54:47 -07004890 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004891 // Have the caller initiate an ICE restart.
4892 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4893 caller()->CreateAndSetAndSignalOffer();
4894 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4895 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4896 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004897 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004898 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4899
4900 // Grab the ufrags/candidates again.
4901 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4902 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4903 ASSERT_GT(audio_candidates_caller->count(), 0u);
4904 ASSERT_GT(audio_candidates_callee->count(), 0u);
4905 std::string caller_candidate_post_restart;
4906 ASSERT_TRUE(
4907 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4908 std::string callee_candidate_post_restart;
4909 ASSERT_TRUE(
4910 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4911 desc = caller()->pc()->local_description()->description();
4912 std::string caller_ufrag_post_restart =
4913 desc->transport_infos()[0].description.ice_ufrag;
4914 desc = callee()->pc()->local_description()->description();
4915 std::string callee_ufrag_post_restart =
4916 desc->transport_infos()[0].description.ice_ufrag;
4917 // Sanity check that an ICE restart was actually negotiated in SDP.
4918 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4919 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4920 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4921 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07004922 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004923
4924 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004925 MediaExpectations media_expectations;
4926 media_expectations.ExpectBidirectionalAudioAndVideo();
4927 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004928}
4929
4930// Verify that audio/video can be received end-to-end when ICE renomination is
4931// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004932TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004933 PeerConnectionInterface::RTCConfiguration config;
4934 config.enable_ice_renomination = true;
4935 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4936 ConnectFakeSignaling();
4937 // Do normal offer/answer and wait for some frames to be received in each
4938 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004939 caller()->AddAudioVideoTracks();
4940 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004941 caller()->CreateAndSetAndSignalOffer();
4942 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4943 // Sanity check that ICE renomination was actually negotiated.
4944 const cricket::SessionDescription* desc =
4945 caller()->pc()->local_description()->description();
4946 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004947 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004948 }
4949 desc = callee()->pc()->local_description()->description();
4950 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004951 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004952 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004953 MediaExpectations media_expectations;
4954 media_expectations.ExpectBidirectionalAudioAndVideo();
4955 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004956}
4957
Steve Anton6f25b092017-10-23 09:39:20 -07004958// With a max bundle policy and RTCP muxing, adding a new media description to
4959// the connection should not affect ICE at all because the new media will use
4960// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004961TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004962 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004963 PeerConnectionInterface::RTCConfiguration config;
4964 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4965 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4966 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4967 config, PeerConnectionInterface::RTCConfiguration()));
4968 ConnectFakeSignaling();
4969
Steve Anton15324772018-01-16 10:26:49 -08004970 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004971 caller()->CreateAndSetAndSignalOffer();
4972 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004973 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4974 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004975
4976 caller()->clear_ice_connection_state_history();
4977
Steve Anton15324772018-01-16 10:26:49 -08004978 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004979 caller()->CreateAndSetAndSignalOffer();
4980 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4981
4982 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4983}
4984
deadbeef1dcb1642017-03-29 21:08:16 -07004985// This test sets up a call between two parties with audio and video. It then
4986// renegotiates setting the video m-line to "port 0", then later renegotiates
4987// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004988TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004989 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4990 ASSERT_TRUE(CreatePeerConnectionWrappers());
4991 ConnectFakeSignaling();
4992
4993 // Do initial negotiation, only sending media from the caller. Will result in
4994 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004995 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004996 caller()->CreateAndSetAndSignalOffer();
4997 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4998
4999 // Negotiate again, disabling the video "m=" section (the callee will set the
5000 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005001 if (sdp_semantics_ == SdpSemantics::kPlanB) {
5002 PeerConnectionInterface::RTCOfferAnswerOptions options;
5003 options.offer_to_receive_video = 0;
5004 callee()->SetOfferAnswerOptions(options);
5005 } else {
5006 callee()->SetRemoteOfferHandler([this] {
5007 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
5008 });
5009 }
deadbeef1dcb1642017-03-29 21:08:16 -07005010 caller()->CreateAndSetAndSignalOffer();
5011 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5012 // Sanity check that video "m=" section was actually rejected.
5013 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
5014 callee()->pc()->local_description()->description());
5015 ASSERT_NE(nullptr, answer_video_content);
5016 ASSERT_TRUE(answer_video_content->rejected);
5017
5018 // Enable video and do negotiation again, making sure video is received
5019 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005020 if (sdp_semantics_ == SdpSemantics::kPlanB) {
5021 PeerConnectionInterface::RTCOfferAnswerOptions options;
5022 options.offer_to_receive_video = 1;
5023 callee()->SetOfferAnswerOptions(options);
5024 } else {
5025 // The caller's transceiver is stopped, so we need to add another track.
5026 auto caller_transceiver =
5027 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
5028 EXPECT_TRUE(caller_transceiver->stopped());
5029 caller()->AddVideoTrack();
5030 }
5031 callee()->AddVideoTrack();
5032 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07005033 caller()->CreateAndSetAndSignalOffer();
5034 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005035
deadbeef1dcb1642017-03-29 21:08:16 -07005036 // Verify the caller receives frames from the newly added stream, and the
5037 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005038 MediaExpectations media_expectations;
5039 media_expectations.CalleeExpectsSomeAudio();
5040 media_expectations.ExpectBidirectionalVideo();
5041 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005042}
5043
deadbeef1dcb1642017-03-29 21:08:16 -07005044// This tests that if we negotiate after calling CreateSender but before we
5045// have a track, then set a track later, frames from the newly-set track are
5046// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005047TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07005048 MediaFlowsAfterEarlyWarmupWithCreateSender) {
5049 ASSERT_TRUE(CreatePeerConnectionWrappers());
5050 ConnectFakeSignaling();
5051 auto caller_audio_sender =
5052 caller()->pc()->CreateSender("audio", "caller_stream");
5053 auto caller_video_sender =
5054 caller()->pc()->CreateSender("video", "caller_stream");
5055 auto callee_audio_sender =
5056 callee()->pc()->CreateSender("audio", "callee_stream");
5057 auto callee_video_sender =
5058 callee()->pc()->CreateSender("video", "callee_stream");
5059 caller()->CreateAndSetAndSignalOffer();
5060 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5061 // Wait for ICE to complete, without any tracks being set.
5062 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5063 caller()->ice_connection_state(), kMaxWaitForFramesMs);
5064 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5065 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5066 // Now set the tracks, and expect frames to immediately start flowing.
5067 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
5068 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
5069 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
5070 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08005071 MediaExpectations media_expectations;
5072 media_expectations.ExpectBidirectionalAudioAndVideo();
5073 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5074}
5075
5076// This tests that if we negotiate after calling AddTransceiver but before we
5077// have a track, then set a track later, frames from the newly-set tracks are
5078// received end-to-end.
5079TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5080 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
5081 ASSERT_TRUE(CreatePeerConnectionWrappers());
5082 ConnectFakeSignaling();
5083 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
5084 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
5085 auto caller_audio_sender = audio_result.MoveValue()->sender();
5086 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
5087 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
5088 auto caller_video_sender = video_result.MoveValue()->sender();
5089 callee()->SetRemoteOfferHandler([this] {
5090 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
5091 callee()->pc()->GetTransceivers()[0]->SetDirection(
5092 RtpTransceiverDirection::kSendRecv);
5093 callee()->pc()->GetTransceivers()[1]->SetDirection(
5094 RtpTransceiverDirection::kSendRecv);
5095 });
5096 caller()->CreateAndSetAndSignalOffer();
5097 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5098 // Wait for ICE to complete, without any tracks being set.
5099 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5100 caller()->ice_connection_state(), kMaxWaitForFramesMs);
5101 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5102 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5103 // Now set the tracks, and expect frames to immediately start flowing.
5104 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
5105 auto callee_video_sender = callee()->pc()->GetSenders()[1];
5106 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
5107 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
5108 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
5109 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
5110 MediaExpectations media_expectations;
5111 media_expectations.ExpectBidirectionalAudioAndVideo();
5112 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005113}
5114
5115// This test verifies that a remote video track can be added via AddStream,
5116// and sent end-to-end. For this particular test, it's simply echoed back
5117// from the caller to the callee, rather than being forwarded to a third
5118// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005119TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07005120 ASSERT_TRUE(CreatePeerConnectionWrappers());
5121 ConnectFakeSignaling();
5122 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08005123 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07005124 caller()->CreateAndSetAndSignalOffer();
5125 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02005126 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07005127
5128 // Echo the stream back, and do a new offer/anwer (initiated by callee this
5129 // time).
5130 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
5131 callee()->CreateAndSetAndSignalOffer();
5132 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5133
Seth Hampson2f0d7022018-02-20 11:54:42 -08005134 MediaExpectations media_expectations;
5135 media_expectations.ExpectBidirectionalVideo();
5136 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005137}
5138
5139// Test that we achieve the expected end-to-end connection time, using a
5140// fake clock and simulated latency on the media and signaling paths.
5141// We use a TURN<->TURN connection because this is usually the quickest to
5142// set up initially, especially when we're confident the connection will work
5143// and can start sending media before we get a STUN response.
5144//
5145// With various optimizations enabled, here are the network delays we expect to
5146// be on the critical path:
5147// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
5148// signaling answer (with DTLS fingerprint).
5149// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
5150// using TURN<->TURN pair, and DTLS exchange is 4 packets,
5151// the first of which should have arrived before the answer.
Yves Gerey100fe632020-01-17 19:15:53 +01005152TEST_P(PeerConnectionIntegrationTestWithFakeClock,
5153 EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07005154 static constexpr int media_hop_delay_ms = 50;
5155 static constexpr int signaling_trip_delay_ms = 500;
5156 // For explanation of these values, see comment above.
5157 static constexpr int required_media_hops = 9;
5158 static constexpr int required_signaling_trips = 2;
5159 // For internal delays (such as posting an event asychronously).
5160 static constexpr int allowed_internal_delay_ms = 20;
5161 static constexpr int total_connection_time_ms =
5162 media_hop_delay_ms * required_media_hops +
5163 signaling_trip_delay_ms * required_signaling_trips +
5164 allowed_internal_delay_ms;
5165
5166 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
5167 3478};
5168 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
5169 0};
5170 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
5171 3478};
5172 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
5173 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07005174 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
5175 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005176
Seth Hampsonaed71642018-06-11 07:41:32 -07005177 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
5178 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07005179 // Bypass permission check on received packets so media can be sent before
5180 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07005181 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
5182 turn_server_1->set_enable_permission_checks(false);
5183 });
5184 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
5185 turn_server_2->set_enable_permission_checks(false);
5186 });
deadbeef1dcb1642017-03-29 21:08:16 -07005187
5188 PeerConnectionInterface::RTCConfiguration client_1_config;
5189 webrtc::PeerConnectionInterface::IceServer ice_server_1;
5190 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
5191 ice_server_1.username = "test";
5192 ice_server_1.password = "test";
5193 client_1_config.servers.push_back(ice_server_1);
5194 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5195 client_1_config.presume_writable_when_fully_relayed = true;
5196
5197 PeerConnectionInterface::RTCConfiguration client_2_config;
5198 webrtc::PeerConnectionInterface::IceServer ice_server_2;
5199 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
5200 ice_server_2.username = "test";
5201 ice_server_2.password = "test";
5202 client_2_config.servers.push_back(ice_server_2);
5203 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5204 client_2_config.presume_writable_when_fully_relayed = true;
5205
5206 ASSERT_TRUE(
5207 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5208 // Set up the simulated delays.
5209 SetSignalingDelayMs(signaling_trip_delay_ms);
5210 ConnectFakeSignaling();
5211 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
5212 virtual_socket_server()->UpdateDelayDistribution();
5213
5214 // Set "offer to receive audio/video" without adding any tracks, so we just
5215 // set up ICE/DTLS with no media.
5216 PeerConnectionInterface::RTCOfferAnswerOptions options;
5217 options.offer_to_receive_audio = 1;
5218 options.offer_to_receive_video = 1;
5219 caller()->SetOfferAnswerOptions(options);
5220 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07005221 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
Yves Gerey100fe632020-01-17 19:15:53 +01005222 FakeClock());
Seth Hampson1d4a76d2018-06-19 14:31:41 -07005223 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
5224 // If this is not done a DCHECK can be hit in ports.cc, because a large
5225 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07005226 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07005227}
5228
Jonas Orelandbdcee282017-10-10 14:01:40 +02005229// Verify that a TurnCustomizer passed in through RTCConfiguration
5230// is actually used by the underlying TURN candidate pair.
5231// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005232TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02005233 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
5234 3478};
5235 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
5236 0};
5237 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
5238 3478};
5239 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
5240 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07005241 CreateTurnServer(turn_server_1_internal_address,
5242 turn_server_1_external_address);
5243 CreateTurnServer(turn_server_2_internal_address,
5244 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005245
5246 PeerConnectionInterface::RTCConfiguration client_1_config;
5247 webrtc::PeerConnectionInterface::IceServer ice_server_1;
5248 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
5249 ice_server_1.username = "test";
5250 ice_server_1.password = "test";
5251 client_1_config.servers.push_back(ice_server_1);
5252 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005253 auto* customizer1 = CreateTurnCustomizer();
5254 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005255
5256 PeerConnectionInterface::RTCConfiguration client_2_config;
5257 webrtc::PeerConnectionInterface::IceServer ice_server_2;
5258 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
5259 ice_server_2.username = "test";
5260 ice_server_2.password = "test";
5261 client_2_config.servers.push_back(ice_server_2);
5262 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005263 auto* customizer2 = CreateTurnCustomizer();
5264 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005265
5266 ASSERT_TRUE(
5267 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5268 ConnectFakeSignaling();
5269
5270 // Set "offer to receive audio/video" without adding any tracks, so we just
5271 // set up ICE/DTLS with no media.
5272 PeerConnectionInterface::RTCOfferAnswerOptions options;
5273 options.offer_to_receive_audio = 1;
5274 options.offer_to_receive_video = 1;
5275 caller()->SetOfferAnswerOptions(options);
5276 caller()->CreateAndSetAndSignalOffer();
5277 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5278
Seth Hampsonaed71642018-06-11 07:41:32 -07005279 ExpectTurnCustomizerCountersIncremented(customizer1);
5280 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005281}
5282
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005283// Verifies that you can use TCP instead of UDP to connect to a TURN server and
5284// send media between the caller and the callee.
5285TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
5286 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5287 3478};
5288 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5289
5290 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07005291 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5292 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005293
5294 webrtc::PeerConnectionInterface::IceServer ice_server;
5295 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
5296 ice_server.username = "test";
5297 ice_server.password = "test";
5298
5299 PeerConnectionInterface::RTCConfiguration client_1_config;
5300 client_1_config.servers.push_back(ice_server);
5301 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5302
5303 PeerConnectionInterface::RTCConfiguration client_2_config;
5304 client_2_config.servers.push_back(ice_server);
5305 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5306
5307 ASSERT_TRUE(
5308 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5309
5310 // Do normal offer/answer and wait for ICE to complete.
5311 ConnectFakeSignaling();
5312 caller()->AddAudioVideoTracks();
5313 callee()->AddAudioVideoTracks();
5314 caller()->CreateAndSetAndSignalOffer();
5315 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5316 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5317 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5318
5319 MediaExpectations media_expectations;
5320 media_expectations.ExpectBidirectionalAudioAndVideo();
5321 EXPECT_TRUE(ExpectNewFrames(media_expectations));
5322}
5323
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005324// Verify that a SSLCertificateVerifier passed in through
5325// PeerConnectionDependencies is actually used by the underlying SSL
5326// implementation to determine whether a certificate presented by the TURN
5327// server is accepted by the client. Note that openssladapter_unittest.cc
5328// contains more detailed, lower-level tests.
5329TEST_P(PeerConnectionIntegrationTest,
5330 SSLCertificateVerifierUsedForTurnConnections) {
5331 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5332 3478};
5333 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5334
5335 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5336 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005337 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5338 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005339
5340 webrtc::PeerConnectionInterface::IceServer ice_server;
5341 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5342 ice_server.username = "test";
5343 ice_server.password = "test";
5344
5345 PeerConnectionInterface::RTCConfiguration client_1_config;
5346 client_1_config.servers.push_back(ice_server);
5347 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5348
5349 PeerConnectionInterface::RTCConfiguration client_2_config;
5350 client_2_config.servers.push_back(ice_server);
5351 // Setting the type to kRelay forces the connection to go through a TURN
5352 // server.
5353 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5354
5355 // Get a copy to the pointer so we can verify calls later.
5356 rtc::TestCertificateVerifier* client_1_cert_verifier =
5357 new rtc::TestCertificateVerifier();
5358 client_1_cert_verifier->verify_certificate_ = true;
5359 rtc::TestCertificateVerifier* client_2_cert_verifier =
5360 new rtc::TestCertificateVerifier();
5361 client_2_cert_verifier->verify_certificate_ = true;
5362
5363 // Create the dependencies with the test certificate verifier.
5364 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5365 client_1_deps.tls_cert_verifier =
5366 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5367 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5368 client_2_deps.tls_cert_verifier =
5369 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5370
5371 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5372 client_1_config, std::move(client_1_deps), client_2_config,
5373 std::move(client_2_deps)));
5374 ConnectFakeSignaling();
5375
5376 // Set "offer to receive audio/video" without adding any tracks, so we just
5377 // set up ICE/DTLS with no media.
5378 PeerConnectionInterface::RTCOfferAnswerOptions options;
5379 options.offer_to_receive_audio = 1;
5380 options.offer_to_receive_video = 1;
5381 caller()->SetOfferAnswerOptions(options);
5382 caller()->CreateAndSetAndSignalOffer();
5383 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5384
5385 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5386 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005387}
5388
5389TEST_P(PeerConnectionIntegrationTest,
5390 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
5391 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5392 3478};
5393 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5394
5395 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5396 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005397 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5398 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005399
5400 webrtc::PeerConnectionInterface::IceServer ice_server;
5401 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5402 ice_server.username = "test";
5403 ice_server.password = "test";
5404
5405 PeerConnectionInterface::RTCConfiguration client_1_config;
5406 client_1_config.servers.push_back(ice_server);
5407 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5408
5409 PeerConnectionInterface::RTCConfiguration client_2_config;
5410 client_2_config.servers.push_back(ice_server);
5411 // Setting the type to kRelay forces the connection to go through a TURN
5412 // server.
5413 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5414
5415 // Get a copy to the pointer so we can verify calls later.
5416 rtc::TestCertificateVerifier* client_1_cert_verifier =
5417 new rtc::TestCertificateVerifier();
5418 client_1_cert_verifier->verify_certificate_ = false;
5419 rtc::TestCertificateVerifier* client_2_cert_verifier =
5420 new rtc::TestCertificateVerifier();
5421 client_2_cert_verifier->verify_certificate_ = false;
5422
5423 // Create the dependencies with the test certificate verifier.
5424 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5425 client_1_deps.tls_cert_verifier =
5426 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5427 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5428 client_2_deps.tls_cert_verifier =
5429 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5430
5431 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5432 client_1_config, std::move(client_1_deps), client_2_config,
5433 std::move(client_2_deps)));
5434 ConnectFakeSignaling();
5435
5436 // Set "offer to receive audio/video" without adding any tracks, so we just
5437 // set up ICE/DTLS with no media.
5438 PeerConnectionInterface::RTCOfferAnswerOptions options;
5439 options.offer_to_receive_audio = 1;
5440 options.offer_to_receive_video = 1;
5441 caller()->SetOfferAnswerOptions(options);
5442 caller()->CreateAndSetAndSignalOffer();
5443 bool wait_res = true;
5444 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
5445 // properly, should be able to just wait for a state of "failed" instead of
5446 // waiting a fixed 10 seconds.
5447 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
5448 ASSERT_FALSE(wait_res);
5449
5450 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5451 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005452}
5453
Qingsi Wang25ec8882019-11-15 12:33:05 -08005454// Test that the injected ICE transport factory is used to create ICE transports
5455// for WebRTC connections.
5456TEST_P(PeerConnectionIntegrationTest, IceTransportFactoryUsedForConnections) {
5457 PeerConnectionInterface::RTCConfiguration default_config;
5458 PeerConnectionDependencies dependencies(nullptr);
5459 auto ice_transport_factory = std::make_unique<MockIceTransportFactory>();
5460 EXPECT_CALL(*ice_transport_factory, RecordIceTransportCreated()).Times(1);
5461 dependencies.ice_transport_factory = std::move(ice_transport_factory);
Johannes Kron8e8b36a2020-02-07 14:23:45 +00005462 auto wrapper =
5463 CreatePeerConnectionWrapper("Caller", nullptr, &default_config,
5464 std::move(dependencies), nullptr, nullptr);
Qingsi Wang25ec8882019-11-15 12:33:05 -08005465 ASSERT_TRUE(wrapper);
5466 wrapper->CreateDataChannel();
5467 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5468 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5469 wrapper->pc()->SetLocalDescription(observer,
5470 wrapper->CreateOfferAndWait().release());
5471}
5472
deadbeefc964d0b2017-04-03 10:03:35 -07005473// Test that audio and video flow end-to-end when codec names don't use the
5474// expected casing, given that they're supposed to be case insensitive. To test
5475// this, all but one codec is removed from each media description, and its
5476// casing is changed.
5477//
5478// In the past, this has regressed and caused crashes/black video, due to the
5479// fact that code at some layers was doing case-insensitive comparisons and
5480// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005481TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07005482 ASSERT_TRUE(CreatePeerConnectionWrappers());
5483 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005484 caller()->AddAudioVideoTracks();
5485 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07005486
5487 // Remove all but one audio/video codec (opus and VP8), and change the
5488 // casing of the caller's generated offer.
5489 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
5490 cricket::AudioContentDescription* audio =
5491 GetFirstAudioContentDescription(description);
5492 ASSERT_NE(nullptr, audio);
5493 auto audio_codecs = audio->codecs();
5494 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
5495 [](const cricket::AudioCodec& codec) {
5496 return codec.name != "opus";
5497 }),
5498 audio_codecs.end());
5499 ASSERT_EQ(1u, audio_codecs.size());
5500 audio_codecs[0].name = "OpUs";
5501 audio->set_codecs(audio_codecs);
5502
5503 cricket::VideoContentDescription* video =
5504 GetFirstVideoContentDescription(description);
5505 ASSERT_NE(nullptr, video);
5506 auto video_codecs = video->codecs();
5507 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
5508 [](const cricket::VideoCodec& codec) {
5509 return codec.name != "VP8";
5510 }),
5511 video_codecs.end());
5512 ASSERT_EQ(1u, video_codecs.size());
5513 video_codecs[0].name = "vP8";
5514 video->set_codecs(video_codecs);
5515 });
5516
5517 caller()->CreateAndSetAndSignalOffer();
5518 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5519
5520 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005521 MediaExpectations media_expectations;
5522 media_expectations.ExpectBidirectionalAudioAndVideo();
5523 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07005524}
5525
Jonas Oreland49ac5952018-09-26 16:04:32 +02005526TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07005527 ASSERT_TRUE(CreatePeerConnectionWrappers());
5528 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005529 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07005530 caller()->CreateAndSetAndSignalOffer();
5531 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07005532 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005533 MediaExpectations media_expectations;
5534 media_expectations.CalleeExpectsSomeAudio(1);
5535 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02005536 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07005537 auto receiver = callee()->pc()->GetReceivers()[0];
5538 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005539 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07005540 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
5541 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02005542 sources[0].source_id());
5543 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
5544}
5545
5546TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
5547 ASSERT_TRUE(CreatePeerConnectionWrappers());
5548 ConnectFakeSignaling();
5549 caller()->AddVideoTrack();
5550 caller()->CreateAndSetAndSignalOffer();
5551 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5552 // Wait for one video frame to be received by the callee.
5553 MediaExpectations media_expectations;
5554 media_expectations.CalleeExpectsSomeVideo(1);
5555 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5556 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
5557 auto receiver = callee()->pc()->GetReceivers()[0];
5558 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
5559 auto sources = receiver->GetSources();
5560 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02005561 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005562 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
5563 sources[0].source_id());
5564 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07005565}
5566
deadbeef2f425aa2017-04-14 10:41:32 -07005567// Test that if a track is removed and added again with a different stream ID,
5568// the new stream ID is successfully communicated in SDP and media continues to
5569// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005570// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
5571// it will not reuse a transceiver that has already been sending. After creating
5572// a new transceiver it tries to create an offer with two senders of the same
5573// track ids and it fails.
5574TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07005575 ASSERT_TRUE(CreatePeerConnectionWrappers());
5576 ConnectFakeSignaling();
5577
deadbeef2f425aa2017-04-14 10:41:32 -07005578 // Add track using stream 1, do offer/answer.
5579 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
5580 caller()->CreateLocalAudioTrack();
5581 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07005582 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07005583 caller()->CreateAndSetAndSignalOffer();
5584 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005585 {
5586 MediaExpectations media_expectations;
5587 media_expectations.CalleeExpectsSomeAudio(1);
5588 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5589 }
deadbeef2f425aa2017-04-14 10:41:32 -07005590 // Remove the sender, and create a new one with the new stream.
5591 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07005592 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07005593 caller()->CreateAndSetAndSignalOffer();
5594 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5595 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005596 {
5597 MediaExpectations media_expectations;
5598 media_expectations.CalleeExpectsSomeAudio();
5599 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5600 }
deadbeef2f425aa2017-04-14 10:41:32 -07005601}
5602
Seth Hampson2f0d7022018-02-20 11:54:42 -08005603TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02005604 ASSERT_TRUE(CreatePeerConnectionWrappers());
5605 ConnectFakeSignaling();
5606
Mirko Bonadei317a1f02019-09-17 17:06:18 +02005607 auto output = std::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005608 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
5609 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02005610 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01005611 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
5612 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02005613
Steve Anton15324772018-01-16 10:26:49 -08005614 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02005615 caller()->CreateAndSetAndSignalOffer();
5616 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5617}
5618
Steve Antonede9ca52017-10-16 13:04:27 -07005619// Test that if candidates are only signaled by applying full session
5620// descriptions (instead of using AddIceCandidate), the peers can connect to
5621// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005622TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07005623 ASSERT_TRUE(CreatePeerConnectionWrappers());
5624 // Each side will signal the session descriptions but not candidates.
5625 ConnectFakeSignalingForSdpOnly();
5626
5627 // Add audio video track and exchange the initial offer/answer with media
5628 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08005629 caller()->AddAudioVideoTracks();
5630 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07005631 caller()->CreateAndSetAndSignalOffer();
5632
5633 // Wait for all candidates to be gathered on both the caller and callee.
5634 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5635 caller()->ice_gathering_state(), kDefaultTimeout);
5636 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5637 callee()->ice_gathering_state(), kDefaultTimeout);
5638
5639 // The candidates will now be included in the session description, so
5640 // signaling them will start the ICE connection.
5641 caller()->CreateAndSetAndSignalOffer();
5642 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5643
5644 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005645 MediaExpectations media_expectations;
5646 media_expectations.ExpectBidirectionalAudioAndVideo();
5647 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07005648}
5649
henrika5f6bf242017-11-01 11:06:56 +01005650// Test that SetAudioPlayout can be used to disable audio playout from the
5651// start, then later enable it. This may be useful, for example, if the caller
5652// needs to play a local ringtone until some event occurs, after which it
5653// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005654TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01005655 ASSERT_TRUE(CreatePeerConnectionWrappers());
5656 ConnectFakeSignaling();
5657
5658 // Set up audio-only call where audio playout is disabled on caller's side.
5659 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08005660 caller()->AddAudioTrack();
5661 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005662 caller()->CreateAndSetAndSignalOffer();
5663 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5664
5665 // Pump messages for a second.
5666 WAIT(false, 1000);
5667 // Since audio playout is disabled, the caller shouldn't have received
5668 // anything (at the playout level, at least).
5669 EXPECT_EQ(0, caller()->audio_frames_received());
5670 // As a sanity check, make sure the callee (for which playout isn't disabled)
5671 // did still see frames on its audio level.
5672 ASSERT_GT(callee()->audio_frames_received(), 0);
5673
5674 // Enable playout again, and ensure audio starts flowing.
5675 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005676 MediaExpectations media_expectations;
5677 media_expectations.ExpectBidirectionalAudio();
5678 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01005679}
5680
5681double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5682 auto report = pc->NewGetStats();
5683 auto track_stats_list =
5684 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5685 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5686 for (const auto* track_stats : track_stats_list) {
5687 if (track_stats->remote_source.is_defined() &&
5688 *track_stats->remote_source) {
5689 remote_track_stats = track_stats;
5690 break;
5691 }
5692 }
5693
5694 if (!remote_track_stats->total_audio_energy.is_defined()) {
5695 return 0.0;
5696 }
5697 return *remote_track_stats->total_audio_energy;
5698}
5699
5700// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5701// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005702TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005703 DisableAudioPlayoutStillGeneratesAudioStats) {
5704 ASSERT_TRUE(CreatePeerConnectionWrappers());
5705 ConnectFakeSignaling();
5706
5707 // Set up audio-only call where playout is disabled but audio-processing is
5708 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005709 caller()->AddAudioTrack();
5710 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005711 caller()->pc()->SetAudioPlayout(false);
5712
5713 caller()->CreateAndSetAndSignalOffer();
5714 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5715
5716 // Wait for the callee to receive audio stats.
5717 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5718}
5719
henrika4f167df2017-11-01 14:45:55 +01005720// Test that SetAudioRecording can be used to disable audio recording from the
5721// start, then later enable it. This may be useful, for example, if the caller
5722// wants to ensure that no audio resources are active before a certain state
5723// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005724TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005725 ASSERT_TRUE(CreatePeerConnectionWrappers());
5726 ConnectFakeSignaling();
5727
5728 // Set up audio-only call where audio recording is disabled on caller's side.
5729 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005730 caller()->AddAudioTrack();
5731 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005732 caller()->CreateAndSetAndSignalOffer();
5733 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5734
5735 // Pump messages for a second.
5736 WAIT(false, 1000);
5737 // Since caller has disabled audio recording, the callee shouldn't have
5738 // received anything.
5739 EXPECT_EQ(0, callee()->audio_frames_received());
5740 // As a sanity check, make sure the caller did still see frames on its
5741 // audio level since audio recording is enabled on the calle side.
5742 ASSERT_GT(caller()->audio_frames_received(), 0);
5743
5744 // Enable audio recording again, and ensure audio starts flowing.
5745 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005746 MediaExpectations media_expectations;
5747 media_expectations.ExpectBidirectionalAudio();
5748 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005749}
5750
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005751// Test that after closing PeerConnections, they stop sending any packets (ICE,
5752// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005753TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005754 // Set up audio/video/data, wait for some frames to be received.
5755 ASSERT_TRUE(CreatePeerConnectionWrappers());
5756 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005757 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005758#ifdef HAVE_SCTP
5759 caller()->CreateDataChannel();
5760#endif
5761 caller()->CreateAndSetAndSignalOffer();
5762 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005763 MediaExpectations media_expectations;
5764 media_expectations.CalleeExpectsSomeAudioAndVideo();
5765 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005766 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005767 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005768 // Pump messages for a second, and ensure no new packets end up sent.
5769 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5770 WAIT(false, 1000);
5771 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5772 EXPECT_EQ(sent_packets_a, sent_packets_b);
5773}
5774
Steve Anton7eca0932018-03-30 15:18:41 -07005775// Test that transport stats are generated by the RTCStatsCollector for a
5776// connection that only involves data channels. This is a regression test for
5777// crbug.com/826972.
5778#ifdef HAVE_SCTP
5779TEST_P(PeerConnectionIntegrationTest,
5780 TransportStatsReportedForDataChannelOnlyConnection) {
5781 ASSERT_TRUE(CreatePeerConnectionWrappers());
5782 ConnectFakeSignaling();
5783 caller()->CreateDataChannel();
5784
5785 caller()->CreateAndSetAndSignalOffer();
5786 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5787 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5788
5789 auto caller_report = caller()->NewGetStats();
5790 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5791 auto callee_report = callee()->NewGetStats();
5792 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5793}
5794#endif // HAVE_SCTP
5795
Qingsi Wang7685e862018-06-11 20:15:46 -07005796TEST_P(PeerConnectionIntegrationTest,
5797 IceEventsGeneratedAndLoggedInRtcEventLog) {
5798 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5799 ConnectFakeSignaling();
5800 PeerConnectionInterface::RTCOfferAnswerOptions options;
5801 options.offer_to_receive_audio = 1;
5802 caller()->SetOfferAnswerOptions(options);
5803 caller()->CreateAndSetAndSignalOffer();
5804 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5805 ASSERT_NE(nullptr, caller()->event_log_factory());
5806 ASSERT_NE(nullptr, callee()->event_log_factory());
5807 webrtc::FakeRtcEventLog* caller_event_log =
5808 static_cast<webrtc::FakeRtcEventLog*>(
5809 caller()->event_log_factory()->last_log_created());
5810 webrtc::FakeRtcEventLog* callee_event_log =
5811 static_cast<webrtc::FakeRtcEventLog*>(
5812 callee()->event_log_factory()->last_log_created());
5813 ASSERT_NE(nullptr, caller_event_log);
5814 ASSERT_NE(nullptr, callee_event_log);
5815 int caller_ice_config_count = caller_event_log->GetEventCount(
5816 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5817 int caller_ice_event_count = caller_event_log->GetEventCount(
5818 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5819 int callee_ice_config_count = callee_event_log->GetEventCount(
5820 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5821 int callee_ice_event_count = callee_event_log->GetEventCount(
5822 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5823 EXPECT_LT(0, caller_ice_config_count);
5824 EXPECT_LT(0, caller_ice_event_count);
5825 EXPECT_LT(0, callee_ice_config_count);
5826 EXPECT_LT(0, callee_ice_event_count);
5827}
5828
Qingsi Wangc129c352019-04-18 10:41:58 -07005829TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005830 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5831 3478};
5832 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5833
5834 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5835
5836 webrtc::PeerConnectionInterface::IceServer ice_server;
5837 ice_server.urls.push_back("turn:88.88.88.0:3478");
5838 ice_server.username = "test";
5839 ice_server.password = "test";
5840
5841 PeerConnectionInterface::RTCConfiguration caller_config;
5842 caller_config.servers.push_back(ice_server);
5843 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5844 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005845 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005846
5847 PeerConnectionInterface::RTCConfiguration callee_config;
5848 callee_config.servers.push_back(ice_server);
5849 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5850 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005851 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005852
5853 ASSERT_TRUE(
5854 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5855
5856 // Do normal offer/answer and wait for ICE to complete.
5857 ConnectFakeSignaling();
5858 caller()->AddAudioVideoTracks();
5859 callee()->AddAudioVideoTracks();
5860 caller()->CreateAndSetAndSignalOffer();
5861 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5862 // Since we are doing continual gathering, the ICE transport does not reach
5863 // kIceGatheringComplete (see
5864 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5865 // kIceConnectionComplete.
5866 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5867 caller()->ice_connection_state(), kDefaultTimeout);
5868 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5869 callee()->ice_connection_state(), kDefaultTimeout);
5870 // Note that we cannot use the metric
5871 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5872 // metric is only populated when we reach kIceConnectionComplete in the
5873 // current implementation.
5874 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5875 caller()->last_candidate_gathered().type());
5876 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5877 callee()->last_candidate_gathered().type());
5878
5879 // Loosen the caller's candidate filter.
5880 caller_config = caller()->pc()->GetConfiguration();
5881 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5882 caller()->pc()->SetConfiguration(caller_config);
5883 // We should have gathered a new host candidate.
5884 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5885 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5886
5887 // Loosen the callee's candidate filter.
5888 callee_config = callee()->pc()->GetConfiguration();
5889 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5890 callee()->pc()->SetConfiguration(callee_config);
5891 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5892 callee()->last_candidate_gathered().type(), kDefaultTimeout);
5893}
5894
Eldar Relloda13ea22019-06-01 12:23:43 +03005895TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03005896 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5897 3478};
5898 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5899
5900 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5901
5902 webrtc::PeerConnectionInterface::IceServer ice_server;
5903 ice_server.urls.push_back("turn:88.88.88.0:3478");
5904 ice_server.username = "test";
5905 ice_server.password = "123";
5906
5907 PeerConnectionInterface::RTCConfiguration caller_config;
5908 caller_config.servers.push_back(ice_server);
5909 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5910 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5911
5912 PeerConnectionInterface::RTCConfiguration callee_config;
5913 callee_config.servers.push_back(ice_server);
5914 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5915 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5916
5917 ASSERT_TRUE(
5918 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5919
5920 // Do normal offer/answer and wait for ICE to complete.
5921 ConnectFakeSignaling();
5922 caller()->AddAudioVideoTracks();
5923 callee()->AddAudioVideoTracks();
5924 caller()->CreateAndSetAndSignalOffer();
5925 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5926 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5927 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5928 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
Eldar Rello0095d372019-12-02 22:22:07 +02005929 EXPECT_NE(caller()->error_event().address, "");
Eldar Relloda13ea22019-06-01 12:23:43 +03005930}
5931
Eldar Rello5ab79e62019-10-09 18:29:44 +03005932TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5933 AudioKeepsFlowingAfterImplicitRollback) {
5934 PeerConnectionInterface::RTCConfiguration config;
5935 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5936 config.enable_implicit_rollback = true;
5937 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5938 ConnectFakeSignaling();
5939 caller()->AddAudioTrack();
5940 callee()->AddAudioTrack();
5941 caller()->CreateAndSetAndSignalOffer();
5942 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5943 MediaExpectations media_expectations;
5944 media_expectations.ExpectBidirectionalAudio();
5945 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5946 SetSignalIceCandidates(false); // Workaround candidate outrace sdp.
5947 caller()->AddVideoTrack();
5948 callee()->AddVideoTrack();
5949 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5950 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5951 callee()->pc()->SetLocalDescription(observer,
5952 callee()->CreateOfferAndWait().release());
5953 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
5954 caller()->CreateAndSetAndSignalOffer(); // Implicit rollback.
5955 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5956 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5957}
5958
5959TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5960 ImplicitRollbackVisitsStableState) {
5961 RTCConfiguration config;
5962 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5963 config.enable_implicit_rollback = true;
5964
5965 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5966
5967 rtc::scoped_refptr<MockSetSessionDescriptionObserver> sld_observer(
5968 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5969 callee()->pc()->SetLocalDescription(sld_observer,
5970 callee()->CreateOfferAndWait().release());
5971 EXPECT_TRUE_WAIT(sld_observer->called(), kDefaultTimeout);
5972 EXPECT_EQ(sld_observer->error(), "");
5973
5974 rtc::scoped_refptr<MockSetSessionDescriptionObserver> srd_observer(
5975 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5976 callee()->pc()->SetRemoteDescription(
5977 srd_observer, caller()->CreateOfferAndWait().release());
5978 EXPECT_TRUE_WAIT(srd_observer->called(), kDefaultTimeout);
5979 EXPECT_EQ(srd_observer->error(), "");
5980
5981 EXPECT_THAT(callee()->peer_connection_signaling_state_history(),
5982 ElementsAre(PeerConnectionInterface::kHaveLocalOffer,
5983 PeerConnectionInterface::kStable,
5984 PeerConnectionInterface::kHaveRemoteOffer));
5985}
5986
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005987INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5988 PeerConnectionIntegrationTest,
5989 Values(SdpSemantics::kPlanB,
5990 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005991
Yves Gerey100fe632020-01-17 19:15:53 +01005992INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5993 PeerConnectionIntegrationTestWithFakeClock,
5994 Values(SdpSemantics::kPlanB,
5995 SdpSemantics::kUnifiedPlan));
5996
Steve Anton74255ff2018-01-24 18:32:57 -08005997// Tests that verify interoperability between Plan B and Unified Plan
5998// PeerConnections.
5999class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08006000 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08006001 public ::testing::WithParamInterface<
6002 std::tuple<SdpSemantics, SdpSemantics>> {
6003 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08006004 // Setting the SdpSemantics for the base test to kDefault does not matter
6005 // because we specify not to use the test semantics when creating
6006 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08006007 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07006008 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08006009 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08006010 callee_semantics_(std::get<1>(GetParam())) {}
6011
6012 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07006013 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
6014 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08006015 }
6016
6017 const SdpSemantics caller_semantics_;
6018 const SdpSemantics callee_semantics_;
6019};
6020
6021TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
6022 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6023 ConnectFakeSignaling();
6024
6025 caller()->CreateAndSetAndSignalOffer();
6026 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6027}
6028
6029TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
6030 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6031 ConnectFakeSignaling();
6032 auto audio_sender = caller()->AddAudioTrack();
6033
6034 caller()->CreateAndSetAndSignalOffer();
6035 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6036
6037 // Verify that one audio receiver has been created on the remote and that it
6038 // has the same track ID as the sending track.
6039 auto receivers = callee()->pc()->GetReceivers();
6040 ASSERT_EQ(1u, receivers.size());
6041 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
6042 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
6043
Seth Hampson2f0d7022018-02-20 11:54:42 -08006044 MediaExpectations media_expectations;
6045 media_expectations.CalleeExpectsSomeAudio();
6046 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006047}
6048
6049TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
6050 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6051 ConnectFakeSignaling();
6052 auto video_sender = caller()->AddVideoTrack();
6053 auto audio_sender = caller()->AddAudioTrack();
6054
6055 caller()->CreateAndSetAndSignalOffer();
6056 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6057
6058 // Verify that one audio and one video receiver have been created on the
6059 // remote and that they have the same track IDs as the sending tracks.
6060 auto audio_receivers =
6061 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
6062 ASSERT_EQ(1u, audio_receivers.size());
6063 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
6064 auto video_receivers =
6065 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
6066 ASSERT_EQ(1u, video_receivers.size());
6067 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
6068
Seth Hampson2f0d7022018-02-20 11:54:42 -08006069 MediaExpectations media_expectations;
6070 media_expectations.CalleeExpectsSomeAudioAndVideo();
6071 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006072}
6073
6074TEST_P(PeerConnectionIntegrationInteropTest,
6075 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
6076 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6077 ConnectFakeSignaling();
6078 caller()->AddAudioVideoTracks();
6079 callee()->AddAudioVideoTracks();
6080
6081 caller()->CreateAndSetAndSignalOffer();
6082 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6083
Seth Hampson2f0d7022018-02-20 11:54:42 -08006084 MediaExpectations media_expectations;
6085 media_expectations.ExpectBidirectionalAudioAndVideo();
6086 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006087}
6088
6089TEST_P(PeerConnectionIntegrationInteropTest,
6090 ReverseRolesOneAudioLocalToOneVideoRemote) {
6091 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6092 ConnectFakeSignaling();
6093 caller()->AddAudioTrack();
6094 callee()->AddVideoTrack();
6095
6096 caller()->CreateAndSetAndSignalOffer();
6097 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6098
6099 // Verify that only the audio track has been negotiated.
6100 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
6101 // Might also check that the callee's NegotiationNeeded flag is set.
6102
6103 // Reverse roles.
6104 callee()->CreateAndSetAndSignalOffer();
6105 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6106
Seth Hampson2f0d7022018-02-20 11:54:42 -08006107 MediaExpectations media_expectations;
6108 media_expectations.CallerExpectsSomeVideo();
6109 media_expectations.CalleeExpectsSomeAudio();
6110 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006111}
6112
Mirko Bonadeic84f6612019-01-31 12:20:57 +01006113INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07006114 PeerConnectionIntegrationTest,
6115 PeerConnectionIntegrationInteropTest,
6116 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
6117 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
6118
6119// Test that if the Unified Plan side offers two video tracks then the Plan B
6120// side will only see the first one and ignore the second.
6121TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07006122 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
6123 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08006124 ConnectFakeSignaling();
6125 auto first_sender = caller()->AddVideoTrack();
6126 caller()->AddVideoTrack();
6127
6128 caller()->CreateAndSetAndSignalOffer();
6129 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6130
6131 // Verify that there is only one receiver and it corresponds to the first
6132 // added track.
6133 auto receivers = callee()->pc()->GetReceivers();
6134 ASSERT_EQ(1u, receivers.size());
6135 EXPECT_TRUE(receivers[0]->track()->enabled());
6136 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
6137
Seth Hampson2f0d7022018-02-20 11:54:42 -08006138 MediaExpectations media_expectations;
6139 media_expectations.CalleeExpectsSomeVideo();
6140 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006141}
6142
Steve Anton2bed3972019-01-04 17:04:30 -08006143// Test that if the initial offer tagged BUNDLE section is rejected due to its
6144// associated RtpTransceiver being stopped and another transceiver is added,
6145// then renegotiation causes the callee to receive the new video track without
6146// error.
6147// This is a regression test for bugs.webrtc.org/9954
6148TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6149 ReOfferWithStoppedBundleTaggedTransceiver) {
6150 RTCConfiguration config;
6151 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
6152 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
6153 ConnectFakeSignaling();
6154 auto audio_transceiver_or_error =
6155 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
6156 ASSERT_TRUE(audio_transceiver_or_error.ok());
6157 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
6158
6159 caller()->CreateAndSetAndSignalOffer();
6160 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6161 {
6162 MediaExpectations media_expectations;
6163 media_expectations.CalleeExpectsSomeAudio();
6164 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6165 }
6166
6167 audio_transceiver->Stop();
6168 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
6169
6170 caller()->CreateAndSetAndSignalOffer();
6171 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6172 {
6173 MediaExpectations media_expectations;
6174 media_expectations.CalleeExpectsSomeVideo();
6175 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6176 }
6177}
6178
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006179#ifdef HAVE_SCTP
6180
6181TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6182 EndToEndCallWithBundledSctpDataChannel) {
6183 ASSERT_TRUE(CreatePeerConnectionWrappers());
6184 ConnectFakeSignaling();
6185 caller()->CreateDataChannel();
6186 caller()->AddAudioVideoTracks();
6187 callee()->AddAudioVideoTracks();
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006188 caller()->CreateAndSetAndSignalOffer();
6189 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01006190 ASSERT_EQ_WAIT(SctpTransportState::kConnected,
6191 caller()->pc()->GetSctpTransport()->Information().state(),
6192 kDefaultTimeout);
6193 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
6194 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6195}
6196
6197TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6198 EndToEndCallWithDataChannelOnlyConnects) {
6199 ASSERT_TRUE(CreatePeerConnectionWrappers());
6200 ConnectFakeSignaling();
6201 caller()->CreateDataChannel();
6202 caller()->CreateAndSetAndSignalOffer();
6203 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6204 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
6205 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6206 ASSERT_TRUE(caller()->data_observer()->IsOpen());
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006207}
6208
Harald Alvestrand2697ac12019-12-16 10:37:04 +01006209TEST_F(PeerConnectionIntegrationTestUnifiedPlan, DataChannelClosesWhenClosed) {
6210 ASSERT_TRUE(CreatePeerConnectionWrappers());
6211 ConnectFakeSignaling();
6212 caller()->CreateDataChannel();
6213 caller()->CreateAndSetAndSignalOffer();
6214 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6215 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6216 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6217 caller()->data_channel()->Close();
6218 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
6219}
6220
6221TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6222 DataChannelClosesWhenClosedReverse) {
6223 ASSERT_TRUE(CreatePeerConnectionWrappers());
6224 ConnectFakeSignaling();
6225 caller()->CreateDataChannel();
6226 caller()->CreateAndSetAndSignalOffer();
6227 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6228 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6229 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6230 callee()->data_channel()->Close();
6231 ASSERT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
6232}
6233
6234TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6235 DataChannelClosesWhenPeerConnectionClosed) {
6236 ASSERT_TRUE(CreatePeerConnectionWrappers());
6237 ConnectFakeSignaling();
6238 caller()->CreateDataChannel();
6239 caller()->CreateAndSetAndSignalOffer();
6240 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6241 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6242 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6243 caller()->pc()->Close();
6244 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
6245}
6246
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006247#endif // HAVE_SCTP
6248
deadbeef1dcb1642017-03-29 21:08:16 -07006249} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01006250} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07006251
6252#endif // if !defined(THREAD_SANITIZER)