blob: 0a6e5d1faf897932943cc8f23a9fc6b7ff93d523 [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 }
595
deadbeef1dcb1642017-03-29 21:08:16 -0700596 private:
597 explicit PeerConnectionWrapper(const std::string& debug_name)
598 : debug_name_(debug_name) {}
599
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800600 bool Init(
601 const PeerConnectionFactory::Options* options,
602 const PeerConnectionInterface::RTCConfiguration* config,
603 webrtc::PeerConnectionDependencies dependencies,
604 rtc::Thread* network_thread,
605 rtc::Thread* worker_thread,
606 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron8e8b36a2020-02-07 14:23:45 +0000607 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700608 // There's an error in this test code if Init ends up being called twice.
609 RTC_DCHECK(!peer_connection_);
610 RTC_DCHECK(!peer_connection_factory_);
611
612 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700613 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700614
615 std::unique_ptr<cricket::PortAllocator> port_allocator(
616 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700617 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700618 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
619 if (!fake_audio_capture_module_) {
620 return false;
621 }
deadbeef1dcb1642017-03-29 21:08:16 -0700622 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700623
624 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
625 pc_factory_dependencies.network_thread = network_thread;
626 pc_factory_dependencies.worker_thread = worker_thread;
627 pc_factory_dependencies.signaling_thread = signaling_thread;
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200628 pc_factory_dependencies.task_queue_factory =
629 webrtc::CreateDefaultTaskQueueFactory();
630 cricket::MediaEngineDependencies media_deps;
631 media_deps.task_queue_factory =
632 pc_factory_dependencies.task_queue_factory.get();
633 media_deps.adm = fake_audio_capture_module_;
634 webrtc::SetMediaEngineDefaults(&media_deps);
Qingsi Wang7685e862018-06-11 20:15:46 -0700635 pc_factory_dependencies.media_engine =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200636 cricket::CreateMediaEngine(std::move(media_deps));
Qingsi Wang7685e862018-06-11 20:15:46 -0700637 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
638 if (event_log_factory) {
639 event_log_factory_ = event_log_factory.get();
640 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
641 } else {
642 pc_factory_dependencies.event_log_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200643 std::make_unique<webrtc::RtcEventLogFactory>(
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200644 pc_factory_dependencies.task_queue_factory.get());
Qingsi Wang7685e862018-06-11 20:15:46 -0700645 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800646 if (media_transport_factory) {
647 pc_factory_dependencies.media_transport_factory =
648 std::move(media_transport_factory);
649 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700650 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
651 std::move(pc_factory_dependencies));
652
deadbeef1dcb1642017-03-29 21:08:16 -0700653 if (!peer_connection_factory_) {
654 return false;
655 }
656 if (options) {
657 peer_connection_factory_->SetOptions(*options);
658 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800659 if (config) {
660 sdp_semantics_ = config->sdp_semantics;
661 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700662
663 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200664 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700665 return peer_connection_.get() != nullptr;
666 }
667
668 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700669 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700670 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700671 PeerConnectionInterface::RTCConfiguration modified_config;
672 // If |config| is null, this will result in a default configuration being
673 // used.
674 if (config) {
675 modified_config = *config;
676 }
677 // Disable resolution adaptation; we don't want it interfering with the
678 // test results.
679 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
680 // ratios and not specific resolutions, is this even necessary?
681 modified_config.set_cpu_adaptation(false);
682
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700683 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700684 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700685 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700686 }
687
688 void set_signaling_message_receiver(
689 SignalingMessageReceiver* signaling_message_receiver) {
690 signaling_message_receiver_ = signaling_message_receiver;
691 }
692
693 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
694
Steve Antonede9ca52017-10-16 13:04:27 -0700695 void set_signal_ice_candidates(bool signal) {
696 signal_ice_candidates_ = signal;
697 }
698
deadbeef1dcb1642017-03-29 21:08:16 -0700699 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200700 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700701 // Set max frame rate to 10fps to reduce the risk of test flakiness.
702 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200703 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700704
Niels Möller5c7efe72018-05-11 10:34:46 +0200705 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200706 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
707 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700708 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200709 peer_connection_factory_->CreateVideoTrack(
710 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700711 if (!local_video_renderer_) {
712 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
713 }
714 return track;
715 }
716
717 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100718 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800719 std::unique_ptr<SessionDescriptionInterface> desc =
720 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700721 if (received_sdp_munger_) {
722 received_sdp_munger_(desc->description());
723 }
724
725 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
726 // Setting a remote description may have changed the number of receivers,
727 // so reset the receiver observers.
728 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800729 if (remote_offer_handler_) {
730 remote_offer_handler_();
731 }
deadbeef1dcb1642017-03-29 21:08:16 -0700732 auto answer = CreateAnswer();
733 ASSERT_NE(nullptr, answer);
734 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
735 }
736
737 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800739 std::unique_ptr<SessionDescriptionInterface> desc =
740 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700741 if (received_sdp_munger_) {
742 received_sdp_munger_(desc->description());
743 }
744
745 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
746 // Set the RtpReceiverObserver after receivers are created.
747 ResetRtpReceiverObservers();
748 }
749
750 // Returns null on failure.
deadbeef1dcb1642017-03-29 21:08:16 -0700751 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
752 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
753 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
754 pc()->CreateAnswer(observer, offer_answer_options_);
755 return WaitForDescriptionFromObserver(observer);
756 }
757
758 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100759 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700760 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
761 if (!observer->result()) {
762 return nullptr;
763 }
764 auto description = observer->MoveDescription();
765 if (generated_sdp_munger_) {
766 generated_sdp_munger_(description->description());
767 }
768 return description;
769 }
770
771 // Setting the local description and sending the SDP message over the fake
772 // signaling channel are combined into the same method because the SDP
773 // message needs to be sent as soon as SetLocalDescription finishes, without
774 // waiting for the observer to be called. This ensures that ICE candidates
775 // don't outrace the description.
776 bool SetLocalDescriptionAndSendSdpMessage(
777 std::unique_ptr<SessionDescriptionInterface> desc) {
778 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
779 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100780 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800781 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700782 std::string sdp;
783 EXPECT_TRUE(desc->ToString(&sdp));
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700784 RTC_LOG(LS_INFO) << debug_name_ << ": local SDP contents=\n" << sdp;
deadbeef1dcb1642017-03-29 21:08:16 -0700785 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800786 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
787 RemoveUnusedVideoRenderers();
788 }
deadbeef1dcb1642017-03-29 21:08:16 -0700789 // As mentioned above, we need to send the message immediately after
790 // SetLocalDescription.
791 SendSdpMessage(type, sdp);
792 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
793 return true;
794 }
795
796 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
797 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
798 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100799 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700800 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800801 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
802 RemoveUnusedVideoRenderers();
803 }
deadbeef1dcb1642017-03-29 21:08:16 -0700804 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
805 return observer->result();
806 }
807
Seth Hampson2f0d7022018-02-20 11:54:42 -0800808 // This is a work around to remove unused fake_video_renderers from
809 // transceivers that have either stopped or are no longer receiving.
810 void RemoveUnusedVideoRenderers() {
811 auto transceivers = pc()->GetTransceivers();
812 for (auto& transceiver : transceivers) {
813 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
814 continue;
815 }
816 // Remove fake video renderers from any stopped transceivers.
817 if (transceiver->stopped()) {
818 auto it =
819 fake_video_renderers_.find(transceiver->receiver()->track()->id());
820 if (it != fake_video_renderers_.end()) {
821 fake_video_renderers_.erase(it);
822 }
823 }
824 // Remove fake video renderers from any transceivers that are no longer
825 // receiving.
826 if ((transceiver->current_direction() &&
827 !webrtc::RtpTransceiverDirectionHasRecv(
828 *transceiver->current_direction()))) {
829 auto it =
830 fake_video_renderers_.find(transceiver->receiver()->track()->id());
831 if (it != fake_video_renderers_.end()) {
832 fake_video_renderers_.erase(it);
833 }
834 }
835 }
836 }
837
deadbeef1dcb1642017-03-29 21:08:16 -0700838 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
839 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800840 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700841 if (signaling_delay_ms_ == 0) {
842 RelaySdpMessageIfReceiverExists(type, msg);
843 } else {
844 invoker_.AsyncInvokeDelayed<void>(
845 RTC_FROM_HERE, rtc::Thread::Current(),
846 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
847 this, type, msg),
848 signaling_delay_ms_);
849 }
850 }
851
Steve Antona3a92c22017-12-07 10:27:41 -0800852 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700853 if (signaling_message_receiver_) {
854 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
855 }
856 }
857
858 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
859 // default).
860 void SendIceMessage(const std::string& sdp_mid,
861 int sdp_mline_index,
862 const std::string& msg) {
863 if (signaling_delay_ms_ == 0) {
864 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
865 } else {
866 invoker_.AsyncInvokeDelayed<void>(
867 RTC_FROM_HERE, rtc::Thread::Current(),
868 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
869 this, sdp_mid, sdp_mline_index, msg),
870 signaling_delay_ms_);
871 }
872 }
873
874 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
875 int sdp_mline_index,
876 const std::string& msg) {
877 if (signaling_message_receiver_) {
878 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
879 msg);
880 }
881 }
882
883 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800884 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
885 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700886 HandleIncomingOffer(msg);
887 } else {
888 HandleIncomingAnswer(msg);
889 }
890 }
891
892 void ReceiveIceMessage(const std::string& sdp_mid,
893 int sdp_mline_index,
894 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100895 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700896 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
897 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
898 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
899 }
900
901 // PeerConnectionObserver callbacks.
902 void OnSignalingChange(
903 webrtc::PeerConnectionInterface::SignalingState new_state) override {
904 EXPECT_EQ(pc()->signaling_state(), new_state);
Eldar Rello5ab79e62019-10-09 18:29:44 +0300905 peer_connection_signaling_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700906 }
Steve Anton15324772018-01-16 10:26:49 -0800907 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
908 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
909 streams) override {
910 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
911 rtc::scoped_refptr<VideoTrackInterface> video_track(
912 static_cast<VideoTrackInterface*>(receiver->track().get()));
913 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700914 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800915 fake_video_renderers_[video_track->id()] =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200916 std::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700917 }
918 }
Steve Anton15324772018-01-16 10:26:49 -0800919 void OnRemoveTrack(
920 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
921 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
922 auto it = fake_video_renderers_.find(receiver->track()->id());
923 RTC_DCHECK(it != fake_video_renderers_.end());
924 fake_video_renderers_.erase(it);
925 }
926 }
deadbeef1dcb1642017-03-29 21:08:16 -0700927 void OnRenegotiationNeeded() override {}
928 void OnIceConnectionChange(
929 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
930 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700931 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700932 }
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100933 void OnStandardizedIceConnectionChange(
934 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
935 standardized_ice_connection_state_history_.push_back(new_state);
936 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200937 void OnConnectionChange(
938 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
939 peer_connection_state_history_.push_back(new_state);
940 }
941
deadbeef1dcb1642017-03-29 21:08:16 -0700942 void OnIceGatheringChange(
943 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700944 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700945 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700946 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700947
948 void OnIceSelectedCandidatePairChanged(
949 const cricket::CandidatePairChangeEvent& event) {
950 ice_candidate_pair_change_history_.push_back(event);
951 }
Alex Drake43faee02019-08-12 16:27:34 -0700952
deadbeef1dcb1642017-03-29 21:08:16 -0700953 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100954 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700955
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800956 if (remote_async_resolver_) {
957 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800958 if (local_candidate.address().IsUnresolvedIP()) {
959 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
960 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700961 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800962 local_candidate.address().hostname());
963 RTC_DCHECK(!resolved_ip.IsNil());
964 resolved_addr.SetResolvedIP(resolved_ip);
965 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
966 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
967 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700968 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700969 }
970
deadbeef1dcb1642017-03-29 21:08:16 -0700971 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800972 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700973 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700974 // Remote party may be deleted.
975 return;
976 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800977 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700978 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700979 }
Eldar Rello0095d372019-12-02 22:22:07 +0200980 void OnIceCandidateError(const std::string& address,
981 int port,
Eldar Relloda13ea22019-06-01 12:23:43 +0300982 const std::string& url,
983 int error_code,
984 const std::string& error_text) override {
Eldar Rello0095d372019-12-02 22:22:07 +0200985 error_event_ = cricket::IceCandidateErrorEvent(address, port, url,
Eldar Relloda13ea22019-06-01 12:23:43 +0300986 error_code, error_text);
987 }
deadbeef1dcb1642017-03-29 21:08:16 -0700988 void OnDataChannel(
989 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100990 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700991 data_channel_ = data_channel;
992 data_observer_.reset(new MockDataChannelObserver(data_channel));
993 }
994
deadbeef1dcb1642017-03-29 21:08:16 -0700995 std::string debug_name_;
996
997 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -0700998 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
999 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001000
1001 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
1002 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
1003 peer_connection_factory_;
1004
Steve Antonede9ca52017-10-16 13:04:27 -07001005 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -07001006 // Needed to keep track of number of frames sent.
1007 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1008 // Needed to keep track of number of frames received.
1009 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1010 fake_video_renderers_;
1011 // Needed to ensure frames aren't received for removed tracks.
1012 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1013 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001014
1015 // For remote peer communication.
1016 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1017 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001018 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001019 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001020 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001021
Niels Möller5c7efe72018-05-11 10:34:46 +02001022 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001023 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001024 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1025 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001026 // |local_video_renderer_| attached to the first created local video track.
1027 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1028
Seth Hampson2f0d7022018-02-20 11:54:42 -08001029 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001030 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1031 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1032 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001033 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001034 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001035 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1036 std::unique_ptr<MockDataChannelObserver> data_observer_;
1037
1038 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1039
Steve Antonede9ca52017-10-16 13:04:27 -07001040 std::vector<PeerConnectionInterface::IceConnectionState>
1041 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001042 std::vector<PeerConnectionInterface::IceConnectionState>
1043 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001044 std::vector<PeerConnectionInterface::PeerConnectionState>
1045 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001046 std::vector<PeerConnectionInterface::IceGatheringState>
1047 ice_gathering_state_history_;
Alex Drake00c7ecf2019-08-06 10:54:47 -07001048 std::vector<cricket::CandidatePairChangeEvent>
1049 ice_candidate_pair_change_history_;
Eldar Rello5ab79e62019-10-09 18:29:44 +03001050 std::vector<PeerConnectionInterface::SignalingState>
1051 peer_connection_signaling_state_history_;
Qingsi Wang7685e862018-06-11 20:15:46 -07001052 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1053
deadbeef1dcb1642017-03-29 21:08:16 -07001054 rtc::AsyncInvoker invoker_;
1055
Seth Hampson2f0d7022018-02-20 11:54:42 -08001056 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001057};
1058
Elad Alon99c3fe52017-10-13 16:29:40 +02001059class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1060 public:
1061 virtual ~MockRtcEventLogOutput() = default;
1062 MOCK_CONST_METHOD0(IsActive, bool());
1063 MOCK_METHOD1(Write, bool(const std::string&));
1064};
1065
Seth Hampson2f0d7022018-02-20 11:54:42 -08001066// This helper object is used for both specifying how many audio/video frames
1067// are expected to be received for a caller/callee. It provides helper functions
1068// to specify these expectations. The object initially starts in a state of no
1069// expectations.
1070class MediaExpectations {
1071 public:
1072 enum ExpectFrames {
1073 kExpectSomeFrames,
1074 kExpectNoFrames,
1075 kNoExpectation,
1076 };
1077
1078 void ExpectBidirectionalAudioAndVideo() {
1079 ExpectBidirectionalAudio();
1080 ExpectBidirectionalVideo();
1081 }
1082
1083 void ExpectBidirectionalAudio() {
1084 CallerExpectsSomeAudio();
1085 CalleeExpectsSomeAudio();
1086 }
1087
1088 void ExpectNoAudio() {
1089 CallerExpectsNoAudio();
1090 CalleeExpectsNoAudio();
1091 }
1092
1093 void ExpectBidirectionalVideo() {
1094 CallerExpectsSomeVideo();
1095 CalleeExpectsSomeVideo();
1096 }
1097
1098 void ExpectNoVideo() {
1099 CallerExpectsNoVideo();
1100 CalleeExpectsNoVideo();
1101 }
1102
1103 void CallerExpectsSomeAudioAndVideo() {
1104 CallerExpectsSomeAudio();
1105 CallerExpectsSomeVideo();
1106 }
1107
1108 void CalleeExpectsSomeAudioAndVideo() {
1109 CalleeExpectsSomeAudio();
1110 CalleeExpectsSomeVideo();
1111 }
1112
1113 // Caller's audio functions.
1114 void CallerExpectsSomeAudio(
1115 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1116 caller_audio_expectation_ = kExpectSomeFrames;
1117 caller_audio_frames_expected_ = expected_audio_frames;
1118 }
1119
1120 void CallerExpectsNoAudio() {
1121 caller_audio_expectation_ = kExpectNoFrames;
1122 caller_audio_frames_expected_ = 0;
1123 }
1124
1125 // Caller's video functions.
1126 void CallerExpectsSomeVideo(
1127 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1128 caller_video_expectation_ = kExpectSomeFrames;
1129 caller_video_frames_expected_ = expected_video_frames;
1130 }
1131
1132 void CallerExpectsNoVideo() {
1133 caller_video_expectation_ = kExpectNoFrames;
1134 caller_video_frames_expected_ = 0;
1135 }
1136
1137 // Callee's audio functions.
1138 void CalleeExpectsSomeAudio(
1139 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1140 callee_audio_expectation_ = kExpectSomeFrames;
1141 callee_audio_frames_expected_ = expected_audio_frames;
1142 }
1143
1144 void CalleeExpectsNoAudio() {
1145 callee_audio_expectation_ = kExpectNoFrames;
1146 callee_audio_frames_expected_ = 0;
1147 }
1148
1149 // Callee's video functions.
1150 void CalleeExpectsSomeVideo(
1151 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1152 callee_video_expectation_ = kExpectSomeFrames;
1153 callee_video_frames_expected_ = expected_video_frames;
1154 }
1155
1156 void CalleeExpectsNoVideo() {
1157 callee_video_expectation_ = kExpectNoFrames;
1158 callee_video_frames_expected_ = 0;
1159 }
1160
1161 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1162 ExpectFrames caller_video_expectation_ = kNoExpectation;
1163 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1164 ExpectFrames callee_video_expectation_ = kNoExpectation;
1165 int caller_audio_frames_expected_ = 0;
1166 int caller_video_frames_expected_ = 0;
1167 int callee_audio_frames_expected_ = 0;
1168 int callee_video_frames_expected_ = 0;
1169};
1170
Qingsi Wang25ec8882019-11-15 12:33:05 -08001171class MockIceTransport : public webrtc::IceTransportInterface {
1172 public:
1173 MockIceTransport(const std::string& name, int component)
1174 : internal_(std::make_unique<cricket::FakeIceTransport>(
1175 name,
1176 component,
1177 nullptr /* network_thread */)) {}
1178 ~MockIceTransport() = default;
1179 cricket::IceTransportInternal* internal() { return internal_.get(); }
1180
1181 private:
1182 std::unique_ptr<cricket::FakeIceTransport> internal_;
1183};
1184
1185class MockIceTransportFactory : public IceTransportFactory {
1186 public:
1187 ~MockIceTransportFactory() override = default;
1188 rtc::scoped_refptr<IceTransportInterface> CreateIceTransport(
1189 const std::string& transport_name,
1190 int component,
1191 IceTransportInit init) {
1192 RecordIceTransportCreated();
1193 return new rtc::RefCountedObject<MockIceTransport>(transport_name,
1194 component);
1195 }
1196 MOCK_METHOD0(RecordIceTransportCreated, void());
1197};
1198
deadbeef1dcb1642017-03-29 21:08:16 -07001199// Tests two PeerConnections connecting to each other end-to-end, using a
1200// virtual network, fake A/V capture and fake encoder/decoders. The
1201// PeerConnections share the threads/socket servers, but use separate versions
1202// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001203class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001204 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001205 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1206 : sdp_semantics_(sdp_semantics),
1207 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001208 fss_(new rtc::FirewallSocketServer(ss_.get())),
1209 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001210 worker_thread_(rtc::Thread::Create()),
1211 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001212 network_thread_->SetName("PCNetworkThread", this);
1213 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001214 RTC_CHECK(network_thread_->Start());
1215 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001216 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001217 }
1218
Seth Hampson2f0d7022018-02-20 11:54:42 -08001219 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001220 // The PeerConnections should deleted before the TurnCustomizers.
1221 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1222 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1223 // that the TurnCustomizer outlives the life of the PeerConnection or else
1224 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001225 if (caller_) {
1226 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001227 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001228 }
1229 if (callee_) {
1230 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001231 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001232 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001233
1234 // If turn servers were created for the test they need to be destroyed on
1235 // the network thread.
1236 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1237 turn_servers_.clear();
1238 turn_customizers_.clear();
1239 });
deadbeef1dcb1642017-03-29 21:08:16 -07001240 }
1241
1242 bool SignalingStateStable() {
1243 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1244 }
1245
deadbeef71452802017-05-07 17:21:01 -07001246 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001247 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1248 // are connected. This is an important distinction. Once we have separate
1249 // ICE and DTLS state, this check needs to use the DTLS state.
1250 return (callee()->ice_connection_state() ==
1251 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1252 callee()->ice_connection_state() ==
1253 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1254 (caller()->ice_connection_state() ==
1255 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1256 caller()->ice_connection_state() ==
1257 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001258 }
1259
Qingsi Wang7685e862018-06-11 20:15:46 -07001260 // When |event_log_factory| is null, the default implementation of the event
1261 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001262 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1263 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001264 const PeerConnectionFactory::Options* options,
1265 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001266 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001267 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001268 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001269 RTCConfiguration modified_config;
1270 if (config) {
1271 modified_config = *config;
1272 }
Steve Anton3acffc32018-04-12 17:21:03 -07001273 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001274 if (!dependencies.cert_generator) {
1275 dependencies.cert_generator =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001276 std::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001277 }
1278 std::unique_ptr<PeerConnectionWrapper> client(
1279 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001280
Niels Möllerf06f9232018-08-07 12:32:18 +02001281 if (!client->Init(options, &modified_config, std::move(dependencies),
1282 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001283 std::move(event_log_factory),
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001284 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001285 return nullptr;
1286 }
1287 return client;
1288 }
1289
Qingsi Wang7685e862018-06-11 20:15:46 -07001290 std::unique_ptr<PeerConnectionWrapper>
1291 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1292 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001293 const PeerConnectionFactory::Options* options,
1294 const RTCConfiguration* config,
1295 webrtc::PeerConnectionDependencies dependencies) {
1296 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1297 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001298 return CreatePeerConnectionWrapper(debug_name, options, config,
1299 std::move(dependencies),
1300 std::move(event_log_factory),
1301 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001302 }
1303
deadbeef1dcb1642017-03-29 21:08:16 -07001304 bool CreatePeerConnectionWrappers() {
1305 return CreatePeerConnectionWrappersWithConfig(
1306 PeerConnectionInterface::RTCConfiguration(),
1307 PeerConnectionInterface::RTCConfiguration());
1308 }
1309
Steve Anton3acffc32018-04-12 17:21:03 -07001310 bool CreatePeerConnectionWrappersWithSdpSemantics(
1311 SdpSemantics caller_semantics,
1312 SdpSemantics callee_semantics) {
1313 // Can't specify the sdp_semantics in the passed-in configuration since it
1314 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1315 // stored in sdp_semantics_. So get around this by modifying the instance
1316 // variable before calling CreatePeerConnectionWrapper for the caller and
1317 // callee PeerConnections.
1318 SdpSemantics original_semantics = sdp_semantics_;
1319 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001320 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001321 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001322 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001323 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001324 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001325 "Callee", 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_ = original_semantics;
1328 return caller_ && callee_;
1329 }
1330
deadbeef1dcb1642017-03-29 21:08:16 -07001331 bool CreatePeerConnectionWrappersWithConfig(
1332 const PeerConnectionInterface::RTCConfiguration& caller_config,
1333 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001334 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001335 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001336 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001337 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001338 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001339 "Callee", nullptr, &callee_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);
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001342 return caller_ && callee_;
1343 }
1344
1345 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1346 const PeerConnectionInterface::RTCConfiguration& caller_config,
1347 const PeerConnectionInterface::RTCConfiguration& callee_config,
1348 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1349 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001350 caller_ =
1351 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1352 webrtc::PeerConnectionDependencies(nullptr),
1353 nullptr, std::move(caller_factory));
1354 callee_ =
1355 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1356 webrtc::PeerConnectionDependencies(nullptr),
1357 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001358 return caller_ && callee_;
1359 }
1360
1361 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1362 const PeerConnectionInterface::RTCConfiguration& caller_config,
1363 webrtc::PeerConnectionDependencies caller_dependencies,
1364 const PeerConnectionInterface::RTCConfiguration& callee_config,
1365 webrtc::PeerConnectionDependencies callee_dependencies) {
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001366 caller_ =
1367 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1368 std::move(caller_dependencies), nullptr,
1369 /*media_transport_factory=*/nullptr);
1370 callee_ =
1371 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1372 std::move(callee_dependencies), nullptr,
1373 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001374 return caller_ && callee_;
1375 }
1376
1377 bool CreatePeerConnectionWrappersWithOptions(
1378 const PeerConnectionFactory::Options& caller_options,
1379 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001380 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001381 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001382 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001383 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001384 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001385 "Callee", &callee_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);
Qingsi Wang7685e862018-06-11 20:15:46 -07001388 return caller_ && callee_;
1389 }
1390
1391 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1392 PeerConnectionInterface::RTCConfiguration default_config;
1393 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001394 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001395 webrtc::PeerConnectionDependencies(nullptr));
1396 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001397 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001398 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001399 return caller_ && callee_;
1400 }
1401
Seth Hampson2f0d7022018-02-20 11:54:42 -08001402 std::unique_ptr<PeerConnectionWrapper>
1403 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001404 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1405 new FakeRTCCertificateGenerator());
1406 cert_generator->use_alternate_key();
1407
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001408 webrtc::PeerConnectionDependencies dependencies(nullptr);
1409 dependencies.cert_generator = std::move(cert_generator);
Johannes Kron8e8b36a2020-02-07 14:23:45 +00001410 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
1411 std::move(dependencies), nullptr,
1412 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001413 }
1414
Seth Hampsonaed71642018-06-11 07:41:32 -07001415 cricket::TestTurnServer* CreateTurnServer(
1416 rtc::SocketAddress internal_address,
1417 rtc::SocketAddress external_address,
1418 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1419 const std::string& common_name = "test turn server") {
1420 rtc::Thread* thread = network_thread();
1421 std::unique_ptr<cricket::TestTurnServer> turn_server =
1422 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1423 RTC_FROM_HERE,
1424 [thread, internal_address, external_address, type, common_name] {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001425 return std::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001426 thread, internal_address, external_address, type,
1427 /*ignore_bad_certs=*/true, common_name);
1428 });
1429 turn_servers_.push_back(std::move(turn_server));
1430 // Interactions with the turn server should be done on the network thread.
1431 return turn_servers_.back().get();
1432 }
1433
1434 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1435 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1436 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1437 RTC_FROM_HERE,
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001438 [] { return std::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001439 turn_customizers_.push_back(std::move(turn_customizer));
1440 // Interactions with the turn customizer should be done on the network
1441 // thread.
1442 return turn_customizers_.back().get();
1443 }
1444
1445 // Checks that the function counters for a TestTurnCustomizer are greater than
1446 // 0.
1447 void ExpectTurnCustomizerCountersIncremented(
1448 cricket::TestTurnCustomizer* turn_customizer) {
1449 unsigned int allow_channel_data_counter =
1450 network_thread()->Invoke<unsigned int>(
1451 RTC_FROM_HERE, [turn_customizer] {
1452 return turn_customizer->allow_channel_data_cnt_;
1453 });
1454 EXPECT_GT(allow_channel_data_counter, 0u);
1455 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1456 RTC_FROM_HERE,
1457 [turn_customizer] { return turn_customizer->modify_cnt_; });
1458 EXPECT_GT(modify_counter, 0u);
1459 }
1460
deadbeef1dcb1642017-03-29 21:08:16 -07001461 // Once called, SDP blobs and ICE candidates will be automatically signaled
1462 // between PeerConnections.
1463 void ConnectFakeSignaling() {
1464 caller_->set_signaling_message_receiver(callee_.get());
1465 callee_->set_signaling_message_receiver(caller_.get());
1466 }
1467
Steve Antonede9ca52017-10-16 13:04:27 -07001468 // Once called, SDP blobs will be automatically signaled between
1469 // PeerConnections. Note that ICE candidates will not be signaled unless they
1470 // are in the exchanged SDP blobs.
1471 void ConnectFakeSignalingForSdpOnly() {
1472 ConnectFakeSignaling();
1473 SetSignalIceCandidates(false);
1474 }
1475
deadbeef1dcb1642017-03-29 21:08:16 -07001476 void SetSignalingDelayMs(int delay_ms) {
1477 caller_->set_signaling_delay_ms(delay_ms);
1478 callee_->set_signaling_delay_ms(delay_ms);
1479 }
1480
Steve Antonede9ca52017-10-16 13:04:27 -07001481 void SetSignalIceCandidates(bool signal) {
1482 caller_->set_signal_ice_candidates(signal);
1483 callee_->set_signal_ice_candidates(signal);
1484 }
1485
deadbeef1dcb1642017-03-29 21:08:16 -07001486 // Messages may get lost on the unreliable DataChannel, so we send multiple
1487 // times to avoid test flakiness.
1488 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1489 const std::string& data,
1490 int retries) {
1491 for (int i = 0; i < retries; ++i) {
1492 dc->Send(DataBuffer(data));
1493 }
1494 }
1495
1496 rtc::Thread* network_thread() { return network_thread_.get(); }
1497
1498 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1499
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001500 webrtc::MediaTransportPair* loopback_media_transports() {
1501 return &loopback_media_transports_;
1502 }
1503
deadbeef1dcb1642017-03-29 21:08:16 -07001504 PeerConnectionWrapper* caller() { return caller_.get(); }
1505
1506 // Set the |caller_| to the |wrapper| passed in and return the
1507 // original |caller_|.
1508 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1509 PeerConnectionWrapper* wrapper) {
1510 PeerConnectionWrapper* old = caller_.release();
1511 caller_.reset(wrapper);
1512 return old;
1513 }
1514
1515 PeerConnectionWrapper* callee() { return callee_.get(); }
1516
1517 // Set the |callee_| to the |wrapper| passed in and return the
1518 // original |callee_|.
1519 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1520 PeerConnectionWrapper* wrapper) {
1521 PeerConnectionWrapper* old = callee_.release();
1522 callee_.reset(wrapper);
1523 return old;
1524 }
1525
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001526 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1527 network_thread()->Invoke<void>(
1528 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1529 caller()->port_allocator(), caller_flags));
1530 network_thread()->Invoke<void>(
1531 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1532 callee()->port_allocator(), callee_flags));
1533 }
1534
Steve Antonede9ca52017-10-16 13:04:27 -07001535 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1536
Seth Hampson2f0d7022018-02-20 11:54:42 -08001537 // Expects the provided number of new frames to be received within
1538 // kMaxWaitForFramesMs. The new expected frames are specified in
1539 // |media_expectations|. Returns false if any of the expectations were
1540 // not met.
1541 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1542 // First initialize the expected frame counts based upon the current
1543 // frame count.
1544 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1545 if (media_expectations.caller_audio_expectation_ ==
1546 MediaExpectations::kExpectSomeFrames) {
1547 total_caller_audio_frames_expected +=
1548 media_expectations.caller_audio_frames_expected_;
1549 }
1550 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001551 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001552 if (media_expectations.caller_video_expectation_ ==
1553 MediaExpectations::kExpectSomeFrames) {
1554 total_caller_video_frames_expected +=
1555 media_expectations.caller_video_frames_expected_;
1556 }
1557 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1558 if (media_expectations.callee_audio_expectation_ ==
1559 MediaExpectations::kExpectSomeFrames) {
1560 total_callee_audio_frames_expected +=
1561 media_expectations.callee_audio_frames_expected_;
1562 }
1563 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001564 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001565 if (media_expectations.callee_video_expectation_ ==
1566 MediaExpectations::kExpectSomeFrames) {
1567 total_callee_video_frames_expected +=
1568 media_expectations.callee_video_frames_expected_;
1569 }
deadbeef1dcb1642017-03-29 21:08:16 -07001570
Seth Hampson2f0d7022018-02-20 11:54:42 -08001571 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001572 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001573 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001574 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001575 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001576 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001577 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001578 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001579 total_callee_video_frames_expected,
1580 kMaxWaitForFramesMs);
1581 bool expectations_correct =
1582 caller()->audio_frames_received() >=
1583 total_caller_audio_frames_expected &&
1584 caller()->min_video_frames_received_per_track() >=
1585 total_caller_video_frames_expected &&
1586 callee()->audio_frames_received() >=
1587 total_callee_audio_frames_expected &&
1588 callee()->min_video_frames_received_per_track() >=
1589 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001590
Seth Hampson2f0d7022018-02-20 11:54:42 -08001591 // After the combined wait, print out a more detailed message upon
1592 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001593 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001594 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001595 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001596 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001597 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001598 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001599 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001600 total_callee_video_frames_expected);
1601
1602 // We want to make sure nothing unexpected was received.
1603 if (media_expectations.caller_audio_expectation_ ==
1604 MediaExpectations::kExpectNoFrames) {
1605 EXPECT_EQ(caller()->audio_frames_received(),
1606 total_caller_audio_frames_expected);
1607 if (caller()->audio_frames_received() !=
1608 total_caller_audio_frames_expected) {
1609 expectations_correct = false;
1610 }
1611 }
1612 if (media_expectations.caller_video_expectation_ ==
1613 MediaExpectations::kExpectNoFrames) {
1614 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1615 total_caller_video_frames_expected);
1616 if (caller()->min_video_frames_received_per_track() !=
1617 total_caller_video_frames_expected) {
1618 expectations_correct = false;
1619 }
1620 }
1621 if (media_expectations.callee_audio_expectation_ ==
1622 MediaExpectations::kExpectNoFrames) {
1623 EXPECT_EQ(callee()->audio_frames_received(),
1624 total_callee_audio_frames_expected);
1625 if (callee()->audio_frames_received() !=
1626 total_callee_audio_frames_expected) {
1627 expectations_correct = false;
1628 }
1629 }
1630 if (media_expectations.callee_video_expectation_ ==
1631 MediaExpectations::kExpectNoFrames) {
1632 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1633 total_callee_video_frames_expected);
1634 if (callee()->min_video_frames_received_per_track() !=
1635 total_callee_video_frames_expected) {
1636 expectations_correct = false;
1637 }
1638 }
1639 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001640 }
1641
Steve Antond91969e2019-05-30 12:27:03 -07001642 void ClosePeerConnections() {
1643 caller()->pc()->Close();
1644 callee()->pc()->Close();
1645 }
1646
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001647 void TestNegotiatedCipherSuite(
1648 const PeerConnectionFactory::Options& caller_options,
1649 const PeerConnectionFactory::Options& callee_options,
1650 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001651 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1652 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001653 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001654 caller()->AddAudioVideoTracks();
1655 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001656 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001657 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001658 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001659 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001660 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01001661 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
1662 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1663 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001664 }
1665
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001666 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1667 bool remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001668 bool aes_ctr_enabled,
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001669 int expected_cipher_suite) {
1670 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001671 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1672 local_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001673 caller_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1674 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001675 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001676 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1677 remote_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001678 callee_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1679 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001680 TestNegotiatedCipherSuite(caller_options, callee_options,
1681 expected_cipher_suite);
1682 }
1683
Seth Hampson2f0d7022018-02-20 11:54:42 -08001684 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001685 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001686
deadbeef1dcb1642017-03-29 21:08:16 -07001687 private:
1688 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001689 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001690 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001691 // |network_thread_| and |worker_thread_| are used by both
1692 // |caller_| and |callee_| so they must be destroyed
1693 // later.
1694 std::unique_ptr<rtc::Thread> network_thread_;
1695 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001696 // The turn servers and turn customizers should be accessed & deleted on the
1697 // network thread to avoid a race with the socket read/write that occurs
1698 // on the network thread.
1699 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1700 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001701 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001702 std::unique_ptr<PeerConnectionWrapper> caller_;
1703 std::unique_ptr<PeerConnectionWrapper> callee_;
1704};
1705
Seth Hampson2f0d7022018-02-20 11:54:42 -08001706class PeerConnectionIntegrationTest
1707 : public PeerConnectionIntegrationBaseTest,
1708 public ::testing::WithParamInterface<SdpSemantics> {
1709 protected:
1710 PeerConnectionIntegrationTest()
1711 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1712};
1713
Yves Gerey100fe632020-01-17 19:15:53 +01001714// Fake clock must be set before threads are started to prevent race on
1715// Set/GetClockForTesting().
1716// To achieve that, multiple inheritance is used as a mixin pattern
1717// where order of construction is finely controlled.
1718// This also ensures peerconnection is closed before switching back to non-fake
1719// clock, avoiding other races and DCHECK failures such as in rtp_sender.cc.
1720class FakeClockForTest : public rtc::ScopedFakeClock {
1721 protected:
1722 FakeClockForTest() {
1723 // Some things use a time of "0" as a special value, so we need to start out
1724 // the fake clock at a nonzero time.
1725 // TODO(deadbeef): Fix this.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001726 AdvanceTime(webrtc::TimeDelta::Seconds(1));
Yves Gerey100fe632020-01-17 19:15:53 +01001727 }
1728
1729 // Explicit handle.
1730 ScopedFakeClock& FakeClock() { return *this; }
1731};
1732
1733// Ensure FakeClockForTest is constructed first (see class for rationale).
1734class PeerConnectionIntegrationTestWithFakeClock
1735 : public FakeClockForTest,
1736 public PeerConnectionIntegrationTest {};
1737
Seth Hampson2f0d7022018-02-20 11:54:42 -08001738class PeerConnectionIntegrationTestPlanB
1739 : public PeerConnectionIntegrationBaseTest {
1740 protected:
1741 PeerConnectionIntegrationTestPlanB()
1742 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1743};
1744
1745class PeerConnectionIntegrationTestUnifiedPlan
1746 : public PeerConnectionIntegrationBaseTest {
1747 protected:
1748 PeerConnectionIntegrationTestUnifiedPlan()
1749 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1750};
1751
deadbeef1dcb1642017-03-29 21:08:16 -07001752// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1753// includes testing that the callback is invoked if an observer is connected
1754// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001755TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001756 RtpReceiverObserverOnFirstPacketReceived) {
1757 ASSERT_TRUE(CreatePeerConnectionWrappers());
1758 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001759 caller()->AddAudioVideoTracks();
1760 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001761 // Start offer/answer exchange and wait for it to complete.
1762 caller()->CreateAndSetAndSignalOffer();
1763 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1764 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001765 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1766 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001767 // Wait for all "first packet received" callbacks to be fired.
1768 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001769 absl::c_all_of(caller()->rtp_receiver_observers(),
1770 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1771 return o->first_packet_received();
1772 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001773 kMaxWaitForFramesMs);
1774 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001775 absl::c_all_of(callee()->rtp_receiver_observers(),
1776 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1777 return o->first_packet_received();
1778 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001779 kMaxWaitForFramesMs);
1780 // If new observers are set after the first packet was already received, the
1781 // callback should still be invoked.
1782 caller()->ResetRtpReceiverObservers();
1783 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001784 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1785 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001786 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001787 absl::c_all_of(caller()->rtp_receiver_observers(),
1788 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1789 return o->first_packet_received();
1790 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001791 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001792 absl::c_all_of(callee()->rtp_receiver_observers(),
1793 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1794 return o->first_packet_received();
1795 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001796}
1797
1798class DummyDtmfObserver : public DtmfSenderObserverInterface {
1799 public:
1800 DummyDtmfObserver() : completed_(false) {}
1801
1802 // Implements DtmfSenderObserverInterface.
1803 void OnToneChange(const std::string& tone) override {
1804 tones_.push_back(tone);
1805 if (tone.empty()) {
1806 completed_ = true;
1807 }
1808 }
1809
1810 const std::vector<std::string>& tones() const { return tones_; }
1811 bool completed() const { return completed_; }
1812
1813 private:
1814 bool completed_;
1815 std::vector<std::string> tones_;
1816};
1817
1818// Assumes |sender| already has an audio track added and the offer/answer
1819// exchange is done.
1820void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1821 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001822 // We should be able to get a DTMF sender from the local sender.
1823 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1824 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1825 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001826 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001827 dtmf_sender->RegisterObserver(&observer);
1828
1829 // Test the DtmfSender object just created.
1830 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1831 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1832
1833 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1834 std::vector<std::string> tones = {"1", "a", ""};
1835 EXPECT_EQ(tones, observer.tones());
1836 dtmf_sender->UnregisterObserver();
1837 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1838}
1839
1840// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1841// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001842TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001843 ASSERT_TRUE(CreatePeerConnectionWrappers());
1844 ConnectFakeSignaling();
1845 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001846 caller()->AddAudioTrack();
1847 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001848 caller()->CreateAndSetAndSignalOffer();
1849 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001850 // DTLS must finish before the DTMF sender can be used reliably.
1851 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001852 TestDtmfFromSenderToReceiver(caller(), callee());
1853 TestDtmfFromSenderToReceiver(callee(), caller());
1854}
1855
1856// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1857// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001858TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001859 ASSERT_TRUE(CreatePeerConnectionWrappers());
1860 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001861
deadbeef1dcb1642017-03-29 21:08:16 -07001862 // Do normal offer/answer and wait for some frames to be received in each
1863 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001864 caller()->AddAudioVideoTracks();
1865 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001866 caller()->CreateAndSetAndSignalOffer();
1867 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001868 MediaExpectations media_expectations;
1869 media_expectations.ExpectBidirectionalAudioAndVideo();
1870 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001871 EXPECT_METRIC_LE(
1872 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1873 webrtc::kEnumCounterKeyProtocolDtls));
1874 EXPECT_METRIC_EQ(
1875 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1876 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001877}
1878
1879// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001880TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001881 PeerConnectionInterface::RTCConfiguration sdes_config;
1882 sdes_config.enable_dtls_srtp.emplace(false);
1883 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1884 ConnectFakeSignaling();
1885
1886 // Do normal offer/answer and wait for some frames to be received in each
1887 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001888 caller()->AddAudioVideoTracks();
1889 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001890 caller()->CreateAndSetAndSignalOffer();
1891 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001892 MediaExpectations media_expectations;
1893 media_expectations.ExpectBidirectionalAudioAndVideo();
1894 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001895 EXPECT_METRIC_LE(
1896 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1897 webrtc::kEnumCounterKeyProtocolSdes));
1898 EXPECT_METRIC_EQ(
1899 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1900 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001901}
1902
Steve Anton9a44b2d2019-07-12 12:58:30 -07001903// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1904// option to offer encrypted versions of all header extensions alongside the
1905// unencrypted versions.
1906TEST_P(PeerConnectionIntegrationTest,
1907 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1908 CryptoOptions crypto_options;
1909 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1910 PeerConnectionInterface::RTCConfiguration config;
1911 config.crypto_options = crypto_options;
1912 // Note: This allows offering >14 RTP header extensions.
1913 config.offer_extmap_allow_mixed = true;
1914 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1915 ConnectFakeSignaling();
1916
1917 // Do normal offer/answer and wait for some frames to be received in each
1918 // direction.
1919 caller()->AddAudioVideoTracks();
1920 callee()->AddAudioVideoTracks();
1921 caller()->CreateAndSetAndSignalOffer();
1922 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1923 MediaExpectations media_expectations;
1924 media_expectations.ExpectBidirectionalAudioAndVideo();
1925 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1926}
1927
Steve Anton8c0f7a72017-10-03 10:03:10 -07001928// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1929// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001930TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001931 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1932 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1933 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1934 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1935 return pc->GetRemoteAudioSSLCertificate();
1936 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001937 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1938 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1939 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1940 return pc->GetRemoteAudioSSLCertChain();
1941 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001942
1943 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1944 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1945
1946 // Configure each side with a known certificate so they can be compared later.
1947 PeerConnectionInterface::RTCConfiguration caller_config;
1948 caller_config.enable_dtls_srtp.emplace(true);
1949 caller_config.certificates.push_back(caller_cert);
1950 PeerConnectionInterface::RTCConfiguration callee_config;
1951 callee_config.enable_dtls_srtp.emplace(true);
1952 callee_config.certificates.push_back(callee_cert);
1953 ASSERT_TRUE(
1954 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1955 ConnectFakeSignaling();
1956
1957 // When first initialized, there should not be a remote SSL certificate (and
1958 // calling this method should not crash).
1959 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1960 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001961 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1962 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001963
Steve Anton15324772018-01-16 10:26:49 -08001964 caller()->AddAudioTrack();
1965 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001966 caller()->CreateAndSetAndSignalOffer();
1967 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1968 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1969
1970 // Once DTLS has been connected, each side should return the other's SSL
1971 // certificate when calling GetRemoteAudioSSLCertificate.
1972
1973 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1974 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001975 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001976 caller_remote_cert->ToPEMString());
1977
1978 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1979 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001980 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001981 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001982
1983 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1984 ASSERT_TRUE(caller_remote_cert_chain);
1985 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1986 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001987 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001988 remote_cert->ToPEMString());
1989
1990 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1991 ASSERT_TRUE(callee_remote_cert_chain);
1992 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1993 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001994 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001995 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001996}
1997
deadbeef1dcb1642017-03-29 21:08:16 -07001998// This test sets up a call between two parties with a source resolution of
1999// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002000TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002001 Send1280By720ResolutionAndReceive16To9AspectRatio) {
2002 ASSERT_TRUE(CreatePeerConnectionWrappers());
2003 ConnectFakeSignaling();
2004
Niels Möller5c7efe72018-05-11 10:34:46 +02002005 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
2006 webrtc::FakePeriodicVideoSource::Config config;
2007 config.width = 1280;
2008 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02002009 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02002010 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
2011 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07002012
2013 // Do normal offer/answer and wait for at least one frame to be received in
2014 // each direction.
2015 caller()->CreateAndSetAndSignalOffer();
2016 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2017 callee()->min_video_frames_received_per_track() > 0,
2018 kMaxWaitForFramesMs);
2019
2020 // Check rendered aspect ratio.
2021 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
2022 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
2023 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
2024 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
2025}
2026
2027// This test sets up an one-way call, with media only from caller to
2028// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002029TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07002030 ASSERT_TRUE(CreatePeerConnectionWrappers());
2031 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002032 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002033 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002034 MediaExpectations media_expectations;
2035 media_expectations.CalleeExpectsSomeAudioAndVideo();
2036 media_expectations.CallerExpectsNoAudio();
2037 media_expectations.CallerExpectsNoVideo();
2038 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002039}
2040
2041// This test sets up a audio call initially, with the callee rejecting video
2042// initially. Then later the callee decides to upgrade to audio/video, and
2043// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002044TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07002045 ASSERT_TRUE(CreatePeerConnectionWrappers());
2046 ConnectFakeSignaling();
2047 // Initially, offer an audio/video stream from the caller, but refuse to
2048 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08002049 caller()->AddAudioVideoTracks();
2050 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002051 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2052 PeerConnectionInterface::RTCOfferAnswerOptions options;
2053 options.offer_to_receive_video = 0;
2054 callee()->SetOfferAnswerOptions(options);
2055 } else {
2056 callee()->SetRemoteOfferHandler([this] {
2057 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2058 });
2059 }
deadbeef1dcb1642017-03-29 21:08:16 -07002060 // Do offer/answer and make sure audio is still received end-to-end.
2061 caller()->CreateAndSetAndSignalOffer();
2062 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002063 {
2064 MediaExpectations media_expectations;
2065 media_expectations.ExpectBidirectionalAudio();
2066 media_expectations.ExpectNoVideo();
2067 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2068 }
deadbeef1dcb1642017-03-29 21:08:16 -07002069 // Sanity check that the callee's description has a rejected video section.
2070 ASSERT_NE(nullptr, callee()->pc()->local_description());
2071 const ContentInfo* callee_video_content =
2072 GetFirstVideoContent(callee()->pc()->local_description()->description());
2073 ASSERT_NE(nullptr, callee_video_content);
2074 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002075
deadbeef1dcb1642017-03-29 21:08:16 -07002076 // Now negotiate with video and ensure negotiation succeeds, with video
2077 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002078 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002079 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2080 PeerConnectionInterface::RTCOfferAnswerOptions options;
2081 options.offer_to_receive_video = 1;
2082 callee()->SetOfferAnswerOptions(options);
2083 } else {
2084 callee()->SetRemoteOfferHandler(nullptr);
2085 caller()->SetRemoteOfferHandler([this] {
2086 // The caller creates a new transceiver to receive video on when receiving
2087 // the offer, but by default it is send only.
2088 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002089 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002090 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
2091 transceivers[2]->receiver()->media_type());
2092 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2093 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
2094 });
2095 }
deadbeef1dcb1642017-03-29 21:08:16 -07002096 callee()->CreateAndSetAndSignalOffer();
2097 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002098 {
2099 // Expect additional audio frames to be received after the upgrade.
2100 MediaExpectations media_expectations;
2101 media_expectations.ExpectBidirectionalAudioAndVideo();
2102 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2103 }
deadbeef1dcb1642017-03-29 21:08:16 -07002104}
2105
deadbeef4389b4d2017-09-07 09:07:36 -07002106// Simpler than the above test; just add an audio track to an established
2107// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002108TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002109 ASSERT_TRUE(CreatePeerConnectionWrappers());
2110 ConnectFakeSignaling();
2111 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002112 caller()->AddVideoTrack();
2113 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002114 caller()->CreateAndSetAndSignalOffer();
2115 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2116 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002117 caller()->AddAudioTrack();
2118 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002119 caller()->CreateAndSetAndSignalOffer();
2120 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2121 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002122 MediaExpectations media_expectations;
2123 media_expectations.ExpectBidirectionalAudioAndVideo();
2124 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002125}
2126
deadbeef1dcb1642017-03-29 21:08:16 -07002127// This test sets up a call that's transferred to a new caller with a different
2128// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002129TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002130 ASSERT_TRUE(CreatePeerConnectionWrappers());
2131 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002132 caller()->AddAudioVideoTracks();
2133 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002134 caller()->CreateAndSetAndSignalOffer();
2135 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2136
2137 // Keep the original peer around which will still send packets to the
2138 // receiving client. These SRTP packets will be dropped.
2139 std::unique_ptr<PeerConnectionWrapper> original_peer(
2140 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002141 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002142 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2143 // directly above.
2144 original_peer->pc()->Close();
2145
2146 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002147 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002148 caller()->CreateAndSetAndSignalOffer();
2149 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2150 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002151 MediaExpectations media_expectations;
2152 media_expectations.ExpectBidirectionalAudioAndVideo();
2153 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002154}
2155
2156// This test sets up a call that's transferred to a new callee with a different
2157// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002158TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002159 ASSERT_TRUE(CreatePeerConnectionWrappers());
2160 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002161 caller()->AddAudioVideoTracks();
2162 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002163 caller()->CreateAndSetAndSignalOffer();
2164 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2165
2166 // Keep the original peer around which will still send packets to the
2167 // receiving client. These SRTP packets will be dropped.
2168 std::unique_ptr<PeerConnectionWrapper> original_peer(
2169 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002170 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002171 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2172 // directly above.
2173 original_peer->pc()->Close();
2174
2175 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002176 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002177 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2178 caller()->CreateAndSetAndSignalOffer();
2179 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2180 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002181 MediaExpectations media_expectations;
2182 media_expectations.ExpectBidirectionalAudioAndVideo();
2183 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002184}
2185
2186// This test sets up a non-bundled call and negotiates bundling at the same
2187// time as starting an ICE restart. When bundling is in effect in the restart,
2188// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002189TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002190 ASSERT_TRUE(CreatePeerConnectionWrappers());
2191 ConnectFakeSignaling();
2192
Steve Anton15324772018-01-16 10:26:49 -08002193 caller()->AddAudioVideoTracks();
2194 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002195 // Remove the bundle group from the SDP received by the callee.
2196 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2197 desc->RemoveGroupByName("BUNDLE");
2198 });
2199 caller()->CreateAndSetAndSignalOffer();
2200 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002201 {
2202 MediaExpectations media_expectations;
2203 media_expectations.ExpectBidirectionalAudioAndVideo();
2204 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2205 }
deadbeef1dcb1642017-03-29 21:08:16 -07002206 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2207 callee()->SetReceivedSdpMunger(nullptr);
2208 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2209 caller()->CreateAndSetAndSignalOffer();
2210 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2211
2212 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002213 {
2214 MediaExpectations media_expectations;
2215 media_expectations.ExpectBidirectionalAudioAndVideo();
2216 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2217 }
deadbeef1dcb1642017-03-29 21:08:16 -07002218}
2219
2220// Test CVO (Coordination of Video Orientation). If a video source is rotated
2221// and both peers support the CVO RTP header extension, the actual video frames
2222// don't need to be encoded in different resolutions, since the rotation is
2223// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002224TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002225 ASSERT_TRUE(CreatePeerConnectionWrappers());
2226 ConnectFakeSignaling();
2227 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002228 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002229 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002230 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002231 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2232
2233 // Wait for video frames to be received by both sides.
2234 caller()->CreateAndSetAndSignalOffer();
2235 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2236 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2237 callee()->min_video_frames_received_per_track() > 0,
2238 kMaxWaitForFramesMs);
2239
2240 // Ensure that the aspect ratio is unmodified.
2241 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2242 // not just assumed.
2243 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2244 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2245 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2246 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2247 // Ensure that the CVO bits were surfaced to the renderer.
2248 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2249 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2250}
2251
2252// Test that when the CVO extension isn't supported, video is rotated the
2253// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002254TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002255 ASSERT_TRUE(CreatePeerConnectionWrappers());
2256 ConnectFakeSignaling();
2257 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002258 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002259 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002260 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002261 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2262
2263 // Remove the CVO extension from the offered SDP.
2264 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2265 cricket::VideoContentDescription* video =
2266 GetFirstVideoContentDescription(desc);
2267 video->ClearRtpHeaderExtensions();
2268 });
2269 // Wait for video frames to be received by both sides.
2270 caller()->CreateAndSetAndSignalOffer();
2271 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2272 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2273 callee()->min_video_frames_received_per_track() > 0,
2274 kMaxWaitForFramesMs);
2275
2276 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2277 // rotation.
2278 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2279 // not just assumed.
2280 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2281 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2282 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2283 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2284 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2285 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2286 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2287}
2288
deadbeef1dcb1642017-03-29 21:08:16 -07002289// Test that if the answerer rejects the audio m= section, no audio is sent or
2290// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002291TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002292 ASSERT_TRUE(CreatePeerConnectionWrappers());
2293 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002294 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002295 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2296 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2297 // it will reject the audio m= section completely.
2298 PeerConnectionInterface::RTCOfferAnswerOptions options;
2299 options.offer_to_receive_audio = 0;
2300 callee()->SetOfferAnswerOptions(options);
2301 } else {
2302 // Stopping the audio RtpTransceiver will cause the media section to be
2303 // rejected in the answer.
2304 callee()->SetRemoteOfferHandler([this] {
2305 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2306 });
2307 }
Steve Anton15324772018-01-16 10:26:49 -08002308 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002309 // Do offer/answer and wait for successful end-to-end video frames.
2310 caller()->CreateAndSetAndSignalOffer();
2311 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002312 MediaExpectations media_expectations;
2313 media_expectations.ExpectBidirectionalVideo();
2314 media_expectations.ExpectNoAudio();
2315 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2316
deadbeef1dcb1642017-03-29 21:08:16 -07002317 // Sanity check that the callee's description has a rejected audio section.
2318 ASSERT_NE(nullptr, callee()->pc()->local_description());
2319 const ContentInfo* callee_audio_content =
2320 GetFirstAudioContent(callee()->pc()->local_description()->description());
2321 ASSERT_NE(nullptr, callee_audio_content);
2322 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002323 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2324 // The caller's transceiver should have stopped after receiving the answer.
2325 EXPECT_TRUE(caller()
2326 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2327 ->stopped());
2328 }
deadbeef1dcb1642017-03-29 21:08:16 -07002329}
2330
2331// Test that if the answerer rejects the video m= section, no video is sent or
2332// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002333TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002334 ASSERT_TRUE(CreatePeerConnectionWrappers());
2335 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002336 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002337 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2338 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2339 // it will reject the video m= section completely.
2340 PeerConnectionInterface::RTCOfferAnswerOptions options;
2341 options.offer_to_receive_video = 0;
2342 callee()->SetOfferAnswerOptions(options);
2343 } else {
2344 // Stopping the video RtpTransceiver will cause the media section to be
2345 // rejected in the answer.
2346 callee()->SetRemoteOfferHandler([this] {
2347 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2348 });
2349 }
Steve Anton15324772018-01-16 10:26:49 -08002350 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002351 // Do offer/answer and wait for successful end-to-end audio frames.
2352 caller()->CreateAndSetAndSignalOffer();
2353 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002354 MediaExpectations media_expectations;
2355 media_expectations.ExpectBidirectionalAudio();
2356 media_expectations.ExpectNoVideo();
2357 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2358
deadbeef1dcb1642017-03-29 21:08:16 -07002359 // Sanity check that the callee's description has a rejected video section.
2360 ASSERT_NE(nullptr, callee()->pc()->local_description());
2361 const ContentInfo* callee_video_content =
2362 GetFirstVideoContent(callee()->pc()->local_description()->description());
2363 ASSERT_NE(nullptr, callee_video_content);
2364 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002365 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2366 // The caller's transceiver should have stopped after receiving the answer.
2367 EXPECT_TRUE(caller()
2368 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2369 ->stopped());
2370 }
deadbeef1dcb1642017-03-29 21:08:16 -07002371}
2372
2373// Test that if the answerer rejects both audio and video m= sections, nothing
2374// bad happens.
2375// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2376// test anything but the fact that negotiation succeeds, which doesn't mean
2377// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002378TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002379 ASSERT_TRUE(CreatePeerConnectionWrappers());
2380 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002381 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002382 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2383 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2384 // will reject both audio and video m= sections.
2385 PeerConnectionInterface::RTCOfferAnswerOptions options;
2386 options.offer_to_receive_audio = 0;
2387 options.offer_to_receive_video = 0;
2388 callee()->SetOfferAnswerOptions(options);
2389 } else {
2390 callee()->SetRemoteOfferHandler([this] {
2391 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002392 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002393 transceiver->Stop();
2394 }
2395 });
2396 }
deadbeef1dcb1642017-03-29 21:08:16 -07002397 // Do offer/answer and wait for stable signaling state.
2398 caller()->CreateAndSetAndSignalOffer();
2399 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002400
deadbeef1dcb1642017-03-29 21:08:16 -07002401 // Sanity check that the callee's description has rejected m= sections.
2402 ASSERT_NE(nullptr, callee()->pc()->local_description());
2403 const ContentInfo* callee_audio_content =
2404 GetFirstAudioContent(callee()->pc()->local_description()->description());
2405 ASSERT_NE(nullptr, callee_audio_content);
2406 EXPECT_TRUE(callee_audio_content->rejected);
2407 const ContentInfo* callee_video_content =
2408 GetFirstVideoContent(callee()->pc()->local_description()->description());
2409 ASSERT_NE(nullptr, callee_video_content);
2410 EXPECT_TRUE(callee_video_content->rejected);
2411}
2412
2413// This test sets up an audio and video call between two parties. After the
2414// call runs for a while, the caller sends an updated offer with video being
2415// rejected. Once the re-negotiation is done, the video flow should stop and
2416// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002417TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002418 ASSERT_TRUE(CreatePeerConnectionWrappers());
2419 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002420 caller()->AddAudioVideoTracks();
2421 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002422 caller()->CreateAndSetAndSignalOffer();
2423 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002424 {
2425 MediaExpectations media_expectations;
2426 media_expectations.ExpectBidirectionalAudioAndVideo();
2427 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2428 }
deadbeef1dcb1642017-03-29 21:08:16 -07002429 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002430 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2431 caller()->SetGeneratedSdpMunger(
2432 [](cricket::SessionDescription* description) {
2433 for (cricket::ContentInfo& content : description->contents()) {
2434 if (cricket::IsVideoContent(&content)) {
2435 content.rejected = true;
2436 }
2437 }
2438 });
2439 } else {
2440 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2441 }
deadbeef1dcb1642017-03-29 21:08:16 -07002442 caller()->CreateAndSetAndSignalOffer();
2443 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2444
2445 // Sanity check that the caller's description has a rejected video section.
2446 ASSERT_NE(nullptr, caller()->pc()->local_description());
2447 const ContentInfo* caller_video_content =
2448 GetFirstVideoContent(caller()->pc()->local_description()->description());
2449 ASSERT_NE(nullptr, caller_video_content);
2450 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002451 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002452 {
2453 MediaExpectations media_expectations;
2454 media_expectations.ExpectBidirectionalAudio();
2455 media_expectations.ExpectNoVideo();
2456 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2457 }
deadbeef1dcb1642017-03-29 21:08:16 -07002458}
2459
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002460// Do one offer/answer with audio, another that disables it (rejecting the m=
2461// section), and another that re-enables it. Regression test for:
2462// bugs.webrtc.org/6023
2463TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2464 ASSERT_TRUE(CreatePeerConnectionWrappers());
2465 ConnectFakeSignaling();
2466
2467 // Add audio track, do normal offer/answer.
2468 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2469 caller()->CreateLocalAudioTrack();
2470 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2471 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2472 caller()->CreateAndSetAndSignalOffer();
2473 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2474
2475 // Remove audio track, and set offer_to_receive_audio to false to cause the
2476 // m= section to be completely disabled, not just "recvonly".
2477 caller()->pc()->RemoveTrack(sender);
2478 PeerConnectionInterface::RTCOfferAnswerOptions options;
2479 options.offer_to_receive_audio = 0;
2480 caller()->SetOfferAnswerOptions(options);
2481 caller()->CreateAndSetAndSignalOffer();
2482 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2483
2484 // Add the audio track again, expecting negotiation to succeed and frames to
2485 // flow.
2486 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2487 options.offer_to_receive_audio = 1;
2488 caller()->SetOfferAnswerOptions(options);
2489 caller()->CreateAndSetAndSignalOffer();
2490 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2491
2492 MediaExpectations media_expectations;
2493 media_expectations.CalleeExpectsSomeAudio();
2494 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2495}
2496
deadbeef1dcb1642017-03-29 21:08:16 -07002497// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2498// is needed to support legacy endpoints.
2499// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2500// add a test for an end-to-end test without MID signaling either (basically,
2501// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002502TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002503 ASSERT_TRUE(CreatePeerConnectionWrappers());
2504 ConnectFakeSignaling();
2505 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002506 caller()->AddAudioVideoTracks();
2507 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002508 // Remove SSRCs and MSIDs from the received offer SDP.
2509 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002510 caller()->CreateAndSetAndSignalOffer();
2511 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002512 MediaExpectations media_expectations;
2513 media_expectations.ExpectBidirectionalAudioAndVideo();
2514 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002515}
2516
Seth Hampson5897a6e2018-04-03 11:16:33 -07002517// Basic end-to-end test, without SSRC signaling. This means that the track
2518// was created properly and frames are delivered when the MSIDs are communicated
2519// with a=msid lines and no a=ssrc lines.
2520TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2521 EndToEndCallWithoutSsrcSignaling) {
2522 const char kStreamId[] = "streamId";
2523 ASSERT_TRUE(CreatePeerConnectionWrappers());
2524 ConnectFakeSignaling();
2525 // Add just audio tracks.
2526 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2527 callee()->AddAudioTrack();
2528
2529 // Remove SSRCs from the received offer SDP.
2530 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2531 caller()->CreateAndSetAndSignalOffer();
2532 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2533 MediaExpectations media_expectations;
2534 media_expectations.ExpectBidirectionalAudio();
2535 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2536}
2537
Steve Antondf527fd2018-04-27 15:52:03 -07002538// Tests that video flows between multiple video tracks when SSRCs are not
2539// signaled. This exercises the MID RTP header extension which is needed to
2540// demux the incoming video tracks.
2541TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2542 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2543 ASSERT_TRUE(CreatePeerConnectionWrappers());
2544 ConnectFakeSignaling();
2545 caller()->AddVideoTrack();
2546 caller()->AddVideoTrack();
2547 callee()->AddVideoTrack();
2548 callee()->AddVideoTrack();
2549
2550 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2551 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2552 caller()->CreateAndSetAndSignalOffer();
2553 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2554 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2555 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2556
2557 // Expect video to be received in both directions on both tracks.
2558 MediaExpectations media_expectations;
2559 media_expectations.ExpectBidirectionalVideo();
2560 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2561}
2562
Henrik Boström5b147782018-12-04 11:25:05 +01002563TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2564 ASSERT_TRUE(CreatePeerConnectionWrappers());
2565 ConnectFakeSignaling();
2566 caller()->AddAudioTrack();
2567 caller()->AddVideoTrack();
2568 caller()->CreateAndSetAndSignalOffer();
2569 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2570 auto callee_receivers = callee()->pc()->GetReceivers();
2571 ASSERT_EQ(2u, callee_receivers.size());
2572 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2573 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2574}
2575
2576TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2577 ASSERT_TRUE(CreatePeerConnectionWrappers());
2578 ConnectFakeSignaling();
2579 caller()->AddAudioTrack();
2580 caller()->AddVideoTrack();
2581 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2582 caller()->CreateAndSetAndSignalOffer();
2583 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2584 auto callee_receivers = callee()->pc()->GetReceivers();
2585 ASSERT_EQ(2u, callee_receivers.size());
2586 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2587 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2588 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2589 callee_receivers[1]->stream_ids()[0]);
2590 EXPECT_EQ(callee_receivers[0]->streams()[0],
2591 callee_receivers[1]->streams()[0]);
2592}
2593
deadbeef1dcb1642017-03-29 21:08:16 -07002594// Test that if two video tracks are sent (from caller to callee, in this test),
2595// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002596TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002597 ASSERT_TRUE(CreatePeerConnectionWrappers());
2598 ConnectFakeSignaling();
2599 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002600 caller()->AddAudioVideoTracks();
2601 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002602 caller()->CreateAndSetAndSignalOffer();
2603 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002604 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002605
2606 MediaExpectations media_expectations;
2607 media_expectations.CalleeExpectsSomeAudioAndVideo();
2608 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002609}
2610
2611static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2612 bool first = true;
2613 for (cricket::ContentInfo& content : desc->contents()) {
2614 if (first) {
2615 first = false;
2616 continue;
2617 }
2618 content.bundle_only = true;
2619 }
2620 first = true;
2621 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2622 if (first) {
2623 first = false;
2624 continue;
2625 }
2626 transport.description.ice_ufrag.clear();
2627 transport.description.ice_pwd.clear();
2628 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2629 transport.description.identity_fingerprint.reset(nullptr);
2630 }
2631}
2632
2633// Test that if applying a true "max bundle" offer, which uses ports of 0,
2634// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2635// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2636// successfully and media flows.
2637// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2638// TODO(deadbeef): Won't need this test once we start generating actual
2639// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002640TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002641 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2642 ASSERT_TRUE(CreatePeerConnectionWrappers());
2643 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002644 caller()->AddAudioVideoTracks();
2645 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002646 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2647 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2648 // but the first m= section.
2649 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2650 caller()->CreateAndSetAndSignalOffer();
2651 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002652 MediaExpectations media_expectations;
2653 media_expectations.ExpectBidirectionalAudioAndVideo();
2654 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002655}
2656
2657// Test that we can receive the audio output level from a remote audio track.
2658// TODO(deadbeef): Use a fake audio source and verify that the output level is
2659// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002660TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002661 ASSERT_TRUE(CreatePeerConnectionWrappers());
2662 ConnectFakeSignaling();
2663 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002664 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002665 caller()->CreateAndSetAndSignalOffer();
2666 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2667
2668 // Get the audio output level stats. Note that the level is not available
2669 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002670 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002671 kMaxWaitForFramesMs);
2672}
2673
2674// Test that an audio input level is reported.
2675// TODO(deadbeef): Use a fake audio source and verify that the input level is
2676// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002677TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002678 ASSERT_TRUE(CreatePeerConnectionWrappers());
2679 ConnectFakeSignaling();
2680 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002681 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002682 caller()->CreateAndSetAndSignalOffer();
2683 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2684
2685 // Get the audio input level stats. The level should be available very
2686 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002687 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002688 kMaxWaitForStatsMs);
2689}
2690
2691// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002692TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002693 ASSERT_TRUE(CreatePeerConnectionWrappers());
2694 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002695 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002696 // Do offer/answer, wait for the callee to receive some frames.
2697 caller()->CreateAndSetAndSignalOffer();
2698 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002699
2700 MediaExpectations media_expectations;
2701 media_expectations.CalleeExpectsSomeAudioAndVideo();
2702 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002703
2704 // Get a handle to the remote tracks created, so they can be used as GetStats
2705 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002706 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002707 // We received frames, so we definitely should have nonzero "received bytes"
2708 // stats at this point.
2709 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2710 0);
2711 }
deadbeef1dcb1642017-03-29 21:08:16 -07002712}
2713
2714// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002715TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002716 ASSERT_TRUE(CreatePeerConnectionWrappers());
2717 ConnectFakeSignaling();
2718 auto audio_track = caller()->CreateLocalAudioTrack();
2719 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002720 caller()->AddTrack(audio_track);
2721 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002722 // Do offer/answer, wait for the callee to receive some frames.
2723 caller()->CreateAndSetAndSignalOffer();
2724 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002725 MediaExpectations media_expectations;
2726 media_expectations.CalleeExpectsSomeAudioAndVideo();
2727 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002728
2729 // The callee received frames, so we definitely should have nonzero "sent
2730 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002731 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2732 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2733}
2734
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002735// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002736TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002737 ASSERT_TRUE(CreatePeerConnectionWrappers());
2738 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002739 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002740
Steve Anton15324772018-01-16 10:26:49 -08002741 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002742
2743 // Do offer/answer, wait for the callee to receive some frames.
2744 caller()->CreateAndSetAndSignalOffer();
2745 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2746
2747 // Get the remote audio track created on the receiver, so they can be used as
2748 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002749 auto receivers = callee()->pc()->GetReceivers();
2750 ASSERT_EQ(1u, receivers.size());
2751 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002752
2753 // Get the audio output level stats. Note that the level is not available
2754 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002755 EXPECT_TRUE_WAIT(
2756 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2757 0,
2758 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002759}
2760
Steve Antona41959e2018-11-28 11:15:33 -08002761// Test that the track ID is associated with all local and remote SSRC stats
2762// using the old GetStats() and more than 1 audio and more than 1 video track.
2763// This is a regression test for crbug.com/906988
2764TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2765 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2766 ASSERT_TRUE(CreatePeerConnectionWrappers());
2767 ConnectFakeSignaling();
2768 auto audio_sender_1 = caller()->AddAudioTrack();
2769 auto video_sender_1 = caller()->AddVideoTrack();
2770 auto audio_sender_2 = caller()->AddAudioTrack();
2771 auto video_sender_2 = caller()->AddVideoTrack();
2772 caller()->CreateAndSetAndSignalOffer();
2773 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2774
2775 MediaExpectations media_expectations;
2776 media_expectations.CalleeExpectsSomeAudioAndVideo();
2777 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2778
2779 std::vector<std::string> track_ids = {
2780 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2781 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2782
2783 auto caller_stats = caller()->OldGetStats();
2784 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2785 auto callee_stats = callee()->OldGetStats();
2786 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2787}
2788
Steve Antonffa6ce42018-11-30 09:26:08 -08002789// Test that the new GetStats() returns stats for all outgoing/incoming streams
2790// with the correct track IDs if there are more than one audio and more than one
2791// video senders/receivers.
2792TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2793 ASSERT_TRUE(CreatePeerConnectionWrappers());
2794 ConnectFakeSignaling();
2795 auto audio_sender_1 = caller()->AddAudioTrack();
2796 auto video_sender_1 = caller()->AddVideoTrack();
2797 auto audio_sender_2 = caller()->AddAudioTrack();
2798 auto video_sender_2 = caller()->AddVideoTrack();
2799 caller()->CreateAndSetAndSignalOffer();
2800 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2801
2802 MediaExpectations media_expectations;
2803 media_expectations.CalleeExpectsSomeAudioAndVideo();
2804 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2805
2806 std::vector<std::string> track_ids = {
2807 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2808 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2809
2810 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2811 caller()->NewGetStats();
2812 ASSERT_TRUE(caller_report);
2813 auto outbound_stream_stats =
2814 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2815 ASSERT_EQ(4u, outbound_stream_stats.size());
2816 std::vector<std::string> outbound_track_ids;
2817 for (const auto& stat : outbound_stream_stats) {
2818 ASSERT_TRUE(stat->bytes_sent.is_defined());
2819 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002820 if (*stat->kind == "video") {
2821 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
2822 EXPECT_GT(*stat->key_frames_encoded, 0u);
2823 ASSERT_TRUE(stat->frames_encoded.is_defined());
2824 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
2825 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002826 ASSERT_TRUE(stat->track_id.is_defined());
2827 const auto* track_stat =
2828 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2829 ASSERT_TRUE(track_stat);
2830 outbound_track_ids.push_back(*track_stat->track_identifier);
2831 }
2832 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2833
2834 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2835 callee()->NewGetStats();
2836 ASSERT_TRUE(callee_report);
2837 auto inbound_stream_stats =
2838 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2839 ASSERT_EQ(4u, inbound_stream_stats.size());
2840 std::vector<std::string> inbound_track_ids;
2841 for (const auto& stat : inbound_stream_stats) {
2842 ASSERT_TRUE(stat->bytes_received.is_defined());
2843 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002844 if (*stat->kind == "video") {
2845 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
2846 EXPECT_GT(*stat->key_frames_decoded, 0u);
2847 ASSERT_TRUE(stat->frames_decoded.is_defined());
2848 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
2849 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002850 ASSERT_TRUE(stat->track_id.is_defined());
2851 const auto* track_stat =
2852 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2853 ASSERT_TRUE(track_stat);
2854 inbound_track_ids.push_back(*track_stat->track_identifier);
2855 }
2856 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2857}
2858
2859// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002860// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2861// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002862TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002863 GetStatsForUnsignaledStreamWithNewStatsApi) {
2864 ASSERT_TRUE(CreatePeerConnectionWrappers());
2865 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002866 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002867 // Remove SSRCs and MSIDs from the received offer SDP.
2868 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2869 caller()->CreateAndSetAndSignalOffer();
2870 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002871 MediaExpectations media_expectations;
2872 media_expectations.CalleeExpectsSomeAudio(1);
2873 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002874
2875 // We received a frame, so we should have nonzero "bytes received" stats for
2876 // the unsignaled stream, if stats are working for it.
2877 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2878 callee()->NewGetStats();
2879 ASSERT_NE(nullptr, report);
2880 auto inbound_stream_stats =
2881 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2882 ASSERT_EQ(1U, inbound_stream_stats.size());
2883 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2884 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002885 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2886}
2887
Taylor Brandstettera4653442018-06-19 09:44:26 -07002888// Same as above but for the legacy stats implementation.
2889TEST_P(PeerConnectionIntegrationTest,
2890 GetStatsForUnsignaledStreamWithOldStatsApi) {
2891 ASSERT_TRUE(CreatePeerConnectionWrappers());
2892 ConnectFakeSignaling();
2893 caller()->AddAudioTrack();
2894 // Remove SSRCs and MSIDs from the received offer SDP.
2895 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2896 caller()->CreateAndSetAndSignalOffer();
2897 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2898
2899 // Note that, since the old stats implementation associates SSRCs with tracks
2900 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2901 // associated track ID. So we can't use the track "selector" argument.
2902 //
2903 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2904 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002905 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002906 kDefaultTimeout);
2907}
2908
zhihuangf8164932017-05-19 13:09:47 -07002909// Test that we can successfully get the media related stats (audio level
2910// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002911TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002912 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2913 ASSERT_TRUE(CreatePeerConnectionWrappers());
2914 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002915 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002916 // Remove SSRCs and MSIDs from the received offer SDP.
2917 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2918 caller()->CreateAndSetAndSignalOffer();
2919 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002920 MediaExpectations media_expectations;
2921 media_expectations.CalleeExpectsSomeAudio(1);
2922 media_expectations.CalleeExpectsSomeVideo(1);
2923 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002924
2925 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2926 callee()->NewGetStats();
2927 ASSERT_NE(nullptr, report);
2928
2929 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2930 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2931 ASSERT_GE(audio_index, 0);
2932 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002933}
2934
deadbeef4e2deab2017-09-20 13:56:21 -07002935// Helper for test below.
2936void ModifySsrcs(cricket::SessionDescription* desc) {
2937 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002938 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002939 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002940 for (uint32_t& ssrc : stream.ssrcs) {
2941 ssrc = rtc::CreateRandomId();
2942 }
2943 }
2944 }
2945}
2946
2947// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2948// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2949// This should result in two "RTCInboundRTPStreamStats", but only one
2950// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2951// being reset to 0 once the SSRC change occurs.
2952//
2953// Regression test for this bug:
2954// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2955//
2956// The bug causes the track stats to only represent one of the two streams:
2957// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2958// that the track stat counters would reset to 0 when the new stream is
2959// received, and a 50% chance that they'll stop updating (while
2960// "concealed_samples" continues increasing, due to silence being generated for
2961// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002962TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002963 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002964 ASSERT_TRUE(CreatePeerConnectionWrappers());
2965 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002966 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002967 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2968 // that doesn't signal SSRCs (from the callee's perspective).
2969 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2970 caller()->CreateAndSetAndSignalOffer();
2971 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2972 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002973 {
2974 MediaExpectations media_expectations;
2975 media_expectations.CalleeExpectsSomeAudio(50);
2976 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2977 }
deadbeef4e2deab2017-09-20 13:56:21 -07002978 // Some audio frames were received, so we should have nonzero "samples
2979 // received" for the track.
2980 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2981 callee()->NewGetStats();
2982 ASSERT_NE(nullptr, report);
2983 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2984 ASSERT_EQ(1U, track_stats.size());
2985 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2986 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2987 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2988
2989 // Create a new offer and munge it to cause the caller to use a new SSRC.
2990 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2991 caller()->CreateAndSetAndSignalOffer();
2992 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2993 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2994 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002995 {
2996 MediaExpectations media_expectations;
2997 media_expectations.CalleeExpectsSomeAudio(25);
2998 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2999 }
deadbeef4e2deab2017-09-20 13:56:21 -07003000
3001 report = callee()->NewGetStats();
3002 ASSERT_NE(nullptr, report);
3003 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3004 ASSERT_EQ(1U, track_stats.size());
3005 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3006 // The "total samples received" stat should only be greater than it was
3007 // before.
3008 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
3009 // Right now, the new SSRC will cause the counters to reset to 0.
3010 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
3011
3012 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08003013 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07003014 // good sign that we're seeing stats from the old stream that's no longer
3015 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08003016 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07003017 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
3018 EXPECT_LT(*track_stats[0]->concealed_samples,
3019 *track_stats[0]->total_samples_received *
3020 kAcceptableConcealedSamplesPercentage);
3021
3022 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
3023 // sanity check that the SSRC really changed.
3024 // TODO(deadbeef): This isn't working right now, because we're not returning
3025 // *any* stats for the inactive stream. Uncomment when the bug is completely
3026 // fixed.
3027 // auto inbound_stream_stats =
3028 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3029 // ASSERT_EQ(2U, inbound_stream_stats.size());
3030}
3031
deadbeef1dcb1642017-03-29 21:08:16 -07003032// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003033TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003034 PeerConnectionFactory::Options dtls_10_options;
3035 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3036 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3037 dtls_10_options));
3038 ConnectFakeSignaling();
3039 // Do normal offer/answer and wait for some frames to be received in each
3040 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003041 caller()->AddAudioVideoTracks();
3042 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003043 caller()->CreateAndSetAndSignalOffer();
3044 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003045 MediaExpectations media_expectations;
3046 media_expectations.ExpectBidirectionalAudioAndVideo();
3047 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003048}
3049
3050// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003051TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003052 PeerConnectionFactory::Options dtls_10_options;
3053 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3054 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3055 dtls_10_options));
3056 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003057 caller()->AddAudioVideoTracks();
3058 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003059 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003060 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003061 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003062 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003063 kDefaultTimeout);
3064 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003065 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003066 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003067 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3068 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3069 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003070}
3071
3072// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003073TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003074 PeerConnectionFactory::Options dtls_12_options;
3075 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3076 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3077 dtls_12_options));
3078 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003079 caller()->AddAudioVideoTracks();
3080 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003081 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003082 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003083 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003084 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003085 kDefaultTimeout);
3086 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003087 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003088 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003089 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3090 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3091 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003092}
3093
3094// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3095// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003096TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003097 PeerConnectionFactory::Options caller_options;
3098 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3099 PeerConnectionFactory::Options callee_options;
3100 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3101 ASSERT_TRUE(
3102 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3103 ConnectFakeSignaling();
3104 // Do normal offer/answer and wait for some frames to be received in each
3105 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003106 caller()->AddAudioVideoTracks();
3107 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003108 caller()->CreateAndSetAndSignalOffer();
3109 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003110 MediaExpectations media_expectations;
3111 media_expectations.ExpectBidirectionalAudioAndVideo();
3112 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003113}
3114
3115// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3116// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003117TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003118 PeerConnectionFactory::Options caller_options;
3119 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3120 PeerConnectionFactory::Options callee_options;
3121 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3122 ASSERT_TRUE(
3123 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3124 ConnectFakeSignaling();
3125 // Do normal offer/answer and wait for some frames to be received in each
3126 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003127 caller()->AddAudioVideoTracks();
3128 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003129 caller()->CreateAndSetAndSignalOffer();
3130 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003131 MediaExpectations media_expectations;
3132 media_expectations.ExpectBidirectionalAudioAndVideo();
3133 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003134}
3135
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003136// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3137// works as expected; the cipher should only be used if enabled by both sides.
3138TEST_P(PeerConnectionIntegrationTest,
3139 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3140 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003141 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003142 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003143 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3144 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003145 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3146 TestNegotiatedCipherSuite(caller_options, callee_options,
3147 expected_cipher_suite);
3148}
3149
3150TEST_P(PeerConnectionIntegrationTest,
3151 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3152 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003153 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3154 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003155 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003156 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003157 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3158 TestNegotiatedCipherSuite(caller_options, callee_options,
3159 expected_cipher_suite);
3160}
3161
3162TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3163 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003164 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003165 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003166 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003167 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3168 TestNegotiatedCipherSuite(caller_options, callee_options,
3169 expected_cipher_suite);
3170}
3171
deadbeef1dcb1642017-03-29 21:08:16 -07003172// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003173TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003174 bool local_gcm_enabled = false;
3175 bool remote_gcm_enabled = false;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003176 bool aes_ctr_enabled = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003177 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3178 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003179 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003180}
3181
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003182// Test that a GCM cipher is used if both ends support it and non-GCM is
3183// disabled.
3184TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenOnlyGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003185 bool local_gcm_enabled = true;
3186 bool remote_gcm_enabled = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003187 bool aes_ctr_enabled = false;
deadbeef1dcb1642017-03-29 21:08:16 -07003188 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3189 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003190 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003191}
3192
deadbeef7914b8c2017-04-21 03:23:33 -07003193// Verify that media can be transmitted end-to-end when GCM crypto suites are
3194// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3195// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3196// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003197TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003198 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003199 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003200 gcm_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher = false;
deadbeef7914b8c2017-04-21 03:23:33 -07003201 ASSERT_TRUE(
3202 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3203 ConnectFakeSignaling();
3204 // Do normal offer/answer and wait for some frames to be received in each
3205 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003206 caller()->AddAudioVideoTracks();
3207 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003208 caller()->CreateAndSetAndSignalOffer();
3209 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003210 MediaExpectations media_expectations;
3211 media_expectations.ExpectBidirectionalAudioAndVideo();
3212 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003213}
3214
deadbeef1dcb1642017-03-29 21:08:16 -07003215// This test sets up a call between two parties with audio, video and an RTP
3216// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003217TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003218 PeerConnectionInterface::RTCConfiguration rtc_config;
3219 rtc_config.enable_rtp_data_channel = true;
3220 rtc_config.enable_dtls_srtp = false;
3221 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003222 ConnectFakeSignaling();
3223 // Expect that data channel created on caller side will show up for callee as
3224 // well.
3225 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003226 caller()->AddAudioVideoTracks();
3227 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003228 caller()->CreateAndSetAndSignalOffer();
3229 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3230 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003231 MediaExpectations media_expectations;
3232 media_expectations.ExpectBidirectionalAudioAndVideo();
3233 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003234 ASSERT_NE(nullptr, caller()->data_channel());
3235 ASSERT_NE(nullptr, callee()->data_channel());
3236 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3237 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3238
3239 // Ensure data can be sent in both directions.
3240 std::string data = "hello world";
3241 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3242 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3243 kDefaultTimeout);
3244 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3245 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3246 kDefaultTimeout);
3247}
3248
3249// Ensure that an RTP data channel is signaled as closed for the caller when
3250// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003251TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003252 RtpDataChannelSignaledClosedInCalleeOffer) {
3253 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003254 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));
deadbeef1dcb1642017-03-29 21:08:16 -07003258 ConnectFakeSignaling();
3259 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003260 caller()->AddAudioVideoTracks();
3261 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003262 caller()->CreateAndSetAndSignalOffer();
3263 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3264 ASSERT_NE(nullptr, caller()->data_channel());
3265 ASSERT_NE(nullptr, callee()->data_channel());
3266 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3267 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3268
3269 // Close the data channel on the callee, and do an updated offer/answer.
3270 callee()->data_channel()->Close();
3271 callee()->CreateAndSetAndSignalOffer();
3272 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3273 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3274 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3275}
3276
3277// Tests that data is buffered in an RTP data channel until an observer is
3278// registered for it.
3279//
3280// NOTE: RTP data channels can receive data before the underlying
3281// transport has detected that a channel is writable and thus data can be
3282// received before the data channel state changes to open. That is hard to test
3283// but the same buffering is expected to be used in that case.
Yves Gerey100fe632020-01-17 19:15:53 +01003284//
3285// Use fake clock and simulated network delay so that we predictably can wait
3286// until an SCTP message has been delivered without "sleep()"ing.
3287TEST_P(PeerConnectionIntegrationTestWithFakeClock,
deadbeef1dcb1642017-03-29 21:08:16 -07003288 DataBufferedUntilRtpDataChannelObserverRegistered) {
deadbeef1dcb1642017-03-29 21:08:16 -07003289 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3290 virtual_socket_server()->UpdateDelayDistribution();
3291
Niels Möllerf06f9232018-08-07 12:32:18 +02003292 PeerConnectionInterface::RTCConfiguration rtc_config;
3293 rtc_config.enable_rtp_data_channel = true;
3294 rtc_config.enable_dtls_srtp = false;
3295 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003296 ConnectFakeSignaling();
3297 caller()->CreateDataChannel();
3298 caller()->CreateAndSetAndSignalOffer();
3299 ASSERT_TRUE(caller()->data_channel() != nullptr);
3300 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
Yves Gerey100fe632020-01-17 19:15:53 +01003301 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003302 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
Yves Gerey100fe632020-01-17 19:15:53 +01003303 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003304 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3305 callee()->data_channel()->state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003306 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003307
3308 // Unregister the observer which is normally automatically registered.
3309 callee()->data_channel()->UnregisterObserver();
3310 // Send data and advance fake clock until it should have been received.
3311 std::string data = "hello world";
3312 caller()->data_channel()->Send(DataBuffer(data));
Yves Gerey100fe632020-01-17 19:15:53 +01003313 SIMULATED_WAIT(false, 50, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003314
3315 // Attach data channel and expect data to be received immediately. Note that
3316 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3317 // further, but data can be received even if the callback is asynchronous.
3318 MockDataChannelObserver new_observer(callee()->data_channel());
3319 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003320 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003321}
3322
3323// This test sets up a call between two parties with audio, video and but only
3324// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003325TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003326 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3327 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003328 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003329 rtc_config_1.enable_dtls_srtp = false;
3330 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3331 rtc_config_2.enable_dtls_srtp = false;
3332 rtc_config_2.enable_dtls_srtp = false;
3333 ASSERT_TRUE(
3334 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003335 ConnectFakeSignaling();
3336 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003337 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003338 caller()->AddAudioVideoTracks();
3339 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003340 caller()->CreateAndSetAndSignalOffer();
3341 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3342 // The caller should still have a data channel, but it should be closed, and
3343 // one should ever have been created for the callee.
3344 EXPECT_TRUE(caller()->data_channel() != nullptr);
3345 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3346 EXPECT_EQ(nullptr, callee()->data_channel());
3347}
3348
3349// This test sets up a call between two parties with audio, and video. When
3350// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003351TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003352 PeerConnectionInterface::RTCConfiguration rtc_config;
3353 rtc_config.enable_rtp_data_channel = true;
3354 rtc_config.enable_dtls_srtp = false;
3355 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003356 ConnectFakeSignaling();
3357 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003358 caller()->AddAudioVideoTracks();
3359 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003360 caller()->CreateAndSetAndSignalOffer();
3361 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3362 // Create data channel and do new offer and answer.
3363 caller()->CreateDataChannel();
3364 caller()->CreateAndSetAndSignalOffer();
3365 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3366 ASSERT_NE(nullptr, caller()->data_channel());
3367 ASSERT_NE(nullptr, callee()->data_channel());
3368 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3369 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3370 // Ensure data can be sent in both directions.
3371 std::string data = "hello world";
3372 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3373 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3374 kDefaultTimeout);
3375 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3376 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3377 kDefaultTimeout);
3378}
3379
3380#ifdef HAVE_SCTP
3381
3382// This test sets up a call between two parties with audio, video and an SCTP
3383// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003384TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003385 ASSERT_TRUE(CreatePeerConnectionWrappers());
3386 ConnectFakeSignaling();
3387 // Expect that data channel created on caller side will show up for callee as
3388 // well.
3389 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003390 caller()->AddAudioVideoTracks();
3391 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003392 caller()->CreateAndSetAndSignalOffer();
3393 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3394 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003395 MediaExpectations media_expectations;
3396 media_expectations.ExpectBidirectionalAudioAndVideo();
3397 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003398 // Caller data channel should already exist (it created one). Callee data
3399 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3400 ASSERT_NE(nullptr, caller()->data_channel());
3401 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3402 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3403 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3404
3405 // Ensure data can be sent in both directions.
3406 std::string data = "hello world";
3407 caller()->data_channel()->Send(DataBuffer(data));
3408 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3409 kDefaultTimeout);
3410 callee()->data_channel()->Send(DataBuffer(data));
3411 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3412 kDefaultTimeout);
3413}
3414
3415// Ensure that when the callee closes an SCTP data channel, the closing
3416// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003417TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003418 // Same procedure as above test.
3419 ASSERT_TRUE(CreatePeerConnectionWrappers());
3420 ConnectFakeSignaling();
3421 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003422 caller()->AddAudioVideoTracks();
3423 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003424 caller()->CreateAndSetAndSignalOffer();
3425 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3426 ASSERT_NE(nullptr, caller()->data_channel());
3427 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3428 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3429 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3430
3431 // Close the data channel on the callee side, and wait for it to reach the
3432 // "closed" state on both sides.
3433 callee()->data_channel()->Close();
3434 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3435 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3436}
3437
Seth Hampson2f0d7022018-02-20 11:54:42 -08003438TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003439 ASSERT_TRUE(CreatePeerConnectionWrappers());
3440 ConnectFakeSignaling();
3441 webrtc::DataChannelInit init;
3442 init.id = 53;
3443 init.maxRetransmits = 52;
3444 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003445 caller()->AddAudioVideoTracks();
3446 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003447 caller()->CreateAndSetAndSignalOffer();
3448 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003449 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3450 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003451 // Since "negotiated" is false, the "id" parameter should be ignored.
3452 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003453 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3454 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3455 EXPECT_FALSE(callee()->data_channel()->negotiated());
3456}
3457
deadbeef1dcb1642017-03-29 21:08:16 -07003458// Test usrsctp's ability to process unordered data stream, where data actually
3459// arrives out of order using simulated delays. Previously there have been some
3460// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003461TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003462 // Introduce random network delays.
3463 // Otherwise it's not a true "unordered" test.
3464 virtual_socket_server()->set_delay_mean(20);
3465 virtual_socket_server()->set_delay_stddev(5);
3466 virtual_socket_server()->UpdateDelayDistribution();
3467 // Normal procedure, but with unordered data channel config.
3468 ASSERT_TRUE(CreatePeerConnectionWrappers());
3469 ConnectFakeSignaling();
3470 webrtc::DataChannelInit init;
3471 init.ordered = false;
3472 caller()->CreateDataChannel(&init);
3473 caller()->CreateAndSetAndSignalOffer();
3474 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3475 ASSERT_NE(nullptr, caller()->data_channel());
3476 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3477 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3478 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3479
3480 static constexpr int kNumMessages = 100;
3481 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3482 static constexpr size_t kMaxMessageSize = 4096;
3483 // Create and send random messages.
3484 std::vector<std::string> sent_messages;
3485 for (int i = 0; i < kNumMessages; ++i) {
3486 size_t length =
3487 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3488 std::string message;
3489 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3490 caller()->data_channel()->Send(DataBuffer(message));
3491 callee()->data_channel()->Send(DataBuffer(message));
3492 sent_messages.push_back(message);
3493 }
3494
3495 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003496 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003497 caller()->data_observer()->received_message_count(),
3498 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003499 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003500 callee()->data_observer()->received_message_count(),
3501 kDefaultTimeout);
3502
3503 // Sort and compare to make sure none of the messages were corrupted.
3504 std::vector<std::string> caller_received_messages =
3505 caller()->data_observer()->messages();
3506 std::vector<std::string> callee_received_messages =
3507 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003508 absl::c_sort(sent_messages);
3509 absl::c_sort(caller_received_messages);
3510 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003511 EXPECT_EQ(sent_messages, caller_received_messages);
3512 EXPECT_EQ(sent_messages, callee_received_messages);
3513}
3514
3515// This test sets up a call between two parties with audio, and video. When
3516// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003517TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003518 ASSERT_TRUE(CreatePeerConnectionWrappers());
3519 ConnectFakeSignaling();
3520 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003521 caller()->AddAudioVideoTracks();
3522 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003523 caller()->CreateAndSetAndSignalOffer();
3524 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3525 // Create data channel and do new offer and answer.
3526 caller()->CreateDataChannel();
3527 caller()->CreateAndSetAndSignalOffer();
3528 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3529 // Caller data channel should already exist (it created one). Callee data
3530 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3531 ASSERT_NE(nullptr, caller()->data_channel());
3532 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3533 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3534 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3535 // Ensure data can be sent in both directions.
3536 std::string data = "hello world";
3537 caller()->data_channel()->Send(DataBuffer(data));
3538 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3539 kDefaultTimeout);
3540 callee()->data_channel()->Send(DataBuffer(data));
3541 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3542 kDefaultTimeout);
3543}
3544
deadbeef7914b8c2017-04-21 03:23:33 -07003545// Set up a connection initially just using SCTP data channels, later upgrading
3546// to audio/video, ensuring frames are received end-to-end. Effectively the
3547// inverse of the test above.
3548// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003549TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003550 ASSERT_TRUE(CreatePeerConnectionWrappers());
3551 ConnectFakeSignaling();
3552 // Do initial offer/answer with just data channel.
3553 caller()->CreateDataChannel();
3554 caller()->CreateAndSetAndSignalOffer();
3555 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3556 // Wait until data can be sent over the data channel.
3557 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3558 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3559 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3560
3561 // Do subsequent offer/answer with two-way audio and video. Audio and video
3562 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003563 caller()->AddAudioVideoTracks();
3564 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003565 caller()->CreateAndSetAndSignalOffer();
3566 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003567 MediaExpectations media_expectations;
3568 media_expectations.ExpectBidirectionalAudioAndVideo();
3569 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003570}
3571
deadbeef8b7e9ad2017-05-25 09:38:55 -07003572static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003573 cricket::SctpDataContentDescription* dcd_offer =
3574 GetFirstSctpDataContentDescription(desc);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01003575 // See https://crbug.com/webrtc/11211 - this function is a no-op
Steve Antonb1c1de12017-12-21 15:14:30 -08003576 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003577 dcd_offer->set_use_sctpmap(false);
3578 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3579}
3580
3581// Test that the data channel works when a spec-compliant SCTP m= section is
3582// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3583// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003584TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003585 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3586 ASSERT_TRUE(CreatePeerConnectionWrappers());
3587 ConnectFakeSignaling();
3588 caller()->CreateDataChannel();
3589 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3590 caller()->CreateAndSetAndSignalOffer();
3591 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3592 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3593 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3594 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3595
3596 // Ensure data can be sent in both directions.
3597 std::string data = "hello world";
3598 caller()->data_channel()->Send(DataBuffer(data));
3599 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3600 kDefaultTimeout);
3601 callee()->data_channel()->Send(DataBuffer(data));
3602 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3603 kDefaultTimeout);
3604}
3605
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003606// Tests that the datagram transport to SCTP fallback works correctly when
3607// datagram transport negotiation fails.
3608TEST_P(PeerConnectionIntegrationTest,
3609 DatagramTransportDataChannelFallbackToSctp) {
3610 PeerConnectionInterface::RTCConfiguration rtc_config;
3611 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3612 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3613 rtc_config.use_datagram_transport_for_data_channels = true;
3614
3615 // Configure one endpoint to use datagram transport for data channels while
3616 // the other does not.
3617 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3618 rtc_config, RTCConfiguration(),
3619 loopback_media_transports()->first_factory(), nullptr));
3620 ConnectFakeSignaling();
3621
3622 // The caller offers a data channel using either datagram transport or SCTP.
3623 caller()->CreateDataChannel();
3624 caller()->AddAudioVideoTracks();
3625 callee()->AddAudioVideoTracks();
3626 caller()->CreateAndSetAndSignalOffer();
3627 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3628
3629 // Negotiation should fallback to SCTP, allowing the data channel to be
3630 // established.
3631 ASSERT_NE(nullptr, caller()->data_channel());
3632 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3633 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3634 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3635
3636 // Ensure data can be sent in both directions.
3637 std::string data = "hello world";
3638 caller()->data_channel()->Send(DataBuffer(data));
3639 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3640 kDefaultTimeout);
3641 callee()->data_channel()->Send(DataBuffer(data));
3642 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3643 kDefaultTimeout);
3644
3645 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3646 MediaExpectations media_expectations;
3647 media_expectations.ExpectBidirectionalAudioAndVideo();
3648 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3649}
3650
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07003651// Tests that the data channel transport works correctly when datagram transport
3652// negotiation succeeds and does not fall back to SCTP.
3653TEST_P(PeerConnectionIntegrationTest,
3654 DatagramTransportDataChannelDoesNotFallbackToSctp) {
3655 PeerConnectionInterface::RTCConfiguration rtc_config;
3656 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3657 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3658 rtc_config.use_datagram_transport_for_data_channels = true;
3659
3660 // Configure one endpoint to use datagram transport for data channels while
3661 // the other does not.
3662 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3663 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3664 loopback_media_transports()->second_factory()));
3665 ConnectFakeSignaling();
3666
3667 // The caller offers a data channel using either datagram transport or SCTP.
3668 caller()->CreateDataChannel();
3669 caller()->AddAudioVideoTracks();
3670 callee()->AddAudioVideoTracks();
3671 caller()->CreateAndSetAndSignalOffer();
3672 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3673
3674 // Ensure that the data channel transport is ready.
3675 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3676 loopback_media_transports()->FlushAsyncInvokes();
3677
3678 // Negotiation should succeed, allowing the data channel to be established.
3679 ASSERT_NE(nullptr, caller()->data_channel());
3680 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3681 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3682 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3683
3684 // Ensure data can be sent in both directions.
3685 std::string data = "hello world";
3686 caller()->data_channel()->Send(DataBuffer(data));
3687 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3688 kDefaultTimeout);
3689 callee()->data_channel()->Send(DataBuffer(data));
3690 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3691 kDefaultTimeout);
3692
3693 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3694 MediaExpectations media_expectations;
3695 media_expectations.ExpectBidirectionalAudioAndVideo();
3696 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3697}
3698
Bjorn A Mellem0cda7b82020-01-28 17:06:55 -08003699// Tests that the datagram transport to SCTP fallback works correctly when
3700// datagram transports do not advertise compatible transport parameters.
3701TEST_P(PeerConnectionIntegrationTest,
3702 DatagramTransportIncompatibleParametersFallsBackToSctp) {
3703 PeerConnectionInterface::RTCConfiguration rtc_config;
3704 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3705 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3706 rtc_config.use_datagram_transport_for_data_channels = true;
3707
3708 // By default, only equal parameters are compatible.
3709 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
3710 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
3711
3712 // Configure one endpoint to use datagram transport for data channels while
3713 // the other does not.
3714 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3715 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3716 loopback_media_transports()->second_factory()));
3717 ConnectFakeSignaling();
3718
3719 // The caller offers a data channel using either datagram transport or SCTP.
3720 caller()->CreateDataChannel();
3721 caller()->AddAudioVideoTracks();
3722 callee()->AddAudioVideoTracks();
3723 caller()->CreateAndSetAndSignalOffer();
3724 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3725
3726 // Negotiation should fallback to SCTP, allowing the data channel to be
3727 // established.
3728 ASSERT_NE(nullptr, caller()->data_channel());
3729 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3730 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3731 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3732
3733 // Both endpoints should agree to use SCTP for data channels.
3734 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
3735 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
3736
3737 // Ensure data can be sent in both directions.
3738 std::string data = "hello world";
3739 caller()->data_channel()->Send(DataBuffer(data));
3740 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3741 kDefaultTimeout);
3742 callee()->data_channel()->Send(DataBuffer(data));
3743 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3744 kDefaultTimeout);
3745
3746 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3747 MediaExpectations media_expectations;
3748 media_expectations.ExpectBidirectionalAudioAndVideo();
3749 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3750}
3751
3752// Tests that the datagram transport to SCTP fallback works correctly when
3753// only the answerer believes datagram transport parameters are incompatible.
3754TEST_P(PeerConnectionIntegrationTest,
3755 DatagramTransportIncompatibleParametersOnAnswererFallsBackToSctp) {
3756 PeerConnectionInterface::RTCConfiguration rtc_config;
3757 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3758 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3759 rtc_config.use_datagram_transport_for_data_channels = true;
3760
3761 // By default, only equal parameters are compatible.
3762 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
3763 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
3764
3765 // Set the offerer to accept different parameters, while the answerer rejects
3766 // them.
3767 loopback_media_transports()->SetFirstDatagramTransportParametersComparison(
3768 [](absl::string_view a, absl::string_view b) { return true; });
3769 loopback_media_transports()->SetSecondDatagramTransportParametersComparison(
3770 [](absl::string_view a, absl::string_view b) { return false; });
3771
3772 // Configure one endpoint to use datagram transport for data channels while
3773 // the other does not.
3774 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3775 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3776 loopback_media_transports()->second_factory()));
3777 ConnectFakeSignaling();
3778
3779 // The caller offers a data channel using either datagram transport or SCTP.
3780 caller()->CreateDataChannel();
3781 caller()->AddAudioVideoTracks();
3782 callee()->AddAudioVideoTracks();
3783 caller()->CreateAndSetAndSignalOffer();
3784 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3785
3786 // Negotiation should fallback to SCTP, allowing the data channel to be
3787 // established.
3788 ASSERT_NE(nullptr, caller()->data_channel());
3789 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3790 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3791 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3792
3793 // Both endpoints should agree to use SCTP for data channels.
3794 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
3795 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
3796
3797 // Ensure data can be sent in both directions.
3798 std::string data = "hello world";
3799 caller()->data_channel()->Send(DataBuffer(data));
3800 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3801 kDefaultTimeout);
3802 callee()->data_channel()->Send(DataBuffer(data));
3803 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3804 kDefaultTimeout);
3805
3806 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3807 MediaExpectations media_expectations;
3808 media_expectations.ExpectBidirectionalAudioAndVideo();
3809 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3810}
3811
3812// Tests that the data channel transport works correctly when datagram
3813// transports provide different, but compatible, transport parameters.
3814TEST_P(PeerConnectionIntegrationTest,
3815 DatagramTransportCompatibleParametersDoNotFallbackToSctp) {
3816 PeerConnectionInterface::RTCConfiguration rtc_config;
3817 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3818 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3819 rtc_config.use_datagram_transport_for_data_channels = true;
3820
3821 // By default, only equal parameters are compatible.
3822 loopback_media_transports()->SetFirstDatagramTransportParameters("foo");
3823 loopback_media_transports()->SetSecondDatagramTransportParameters("bar");
3824
3825 // Change the comparison used to treat these transport parameters are
3826 // compatible (on both sides).
3827 loopback_media_transports()->SetFirstDatagramTransportParametersComparison(
3828 [](absl::string_view a, absl::string_view b) { return true; });
3829 loopback_media_transports()->SetSecondDatagramTransportParametersComparison(
3830 [](absl::string_view a, absl::string_view b) { return true; });
3831
3832 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3833 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3834 loopback_media_transports()->second_factory()));
3835 ConnectFakeSignaling();
3836
3837 // The caller offers a data channel using either datagram transport or SCTP.
3838 caller()->CreateDataChannel();
3839 caller()->AddAudioVideoTracks();
3840 callee()->AddAudioVideoTracks();
3841 caller()->CreateAndSetAndSignalOffer();
3842 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3843
3844 // Ensure that the data channel transport is ready.
3845 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3846 loopback_media_transports()->FlushAsyncInvokes();
3847
3848 // Negotiation should succeed, allowing the data channel to be established.
3849 ASSERT_NE(nullptr, caller()->data_channel());
3850 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3851 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3852 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3853
3854 // Both endpoints should agree to use datagram transport for data channels.
3855 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
3856 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
3857
3858 // Ensure data can be sent in both directions.
3859 std::string data = "hello world";
3860 caller()->data_channel()->Send(DataBuffer(data));
3861 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3862 kDefaultTimeout);
3863 callee()->data_channel()->Send(DataBuffer(data));
3864 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3865 kDefaultTimeout);
3866
3867 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3868 MediaExpectations media_expectations;
3869 media_expectations.ExpectBidirectionalAudioAndVideo();
3870 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3871}
3872
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07003873TEST_P(PeerConnectionIntegrationTest,
3874 DatagramTransportDataChannelWithMediaOnCaller) {
3875 // Configure the caller to attempt use of datagram transport for media and
3876 // data channels.
3877 PeerConnectionInterface::RTCConfiguration offerer_config;
3878 offerer_config.rtcp_mux_policy =
3879 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3880 offerer_config.bundle_policy =
3881 PeerConnectionInterface::kBundlePolicyMaxBundle;
3882 offerer_config.use_datagram_transport_for_data_channels = true;
3883 offerer_config.use_datagram_transport = true;
3884
3885 // Configure the callee to only use datagram transport for data channels.
3886 PeerConnectionInterface::RTCConfiguration answerer_config;
3887 answerer_config.rtcp_mux_policy =
3888 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3889 answerer_config.bundle_policy =
3890 PeerConnectionInterface::kBundlePolicyMaxBundle;
3891 answerer_config.use_datagram_transport_for_data_channels = true;
3892
3893 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3894 offerer_config, answerer_config,
3895 loopback_media_transports()->first_factory(),
3896 loopback_media_transports()->second_factory()));
3897 ConnectFakeSignaling();
3898
3899 // Offer both media and data.
3900 caller()->AddAudioVideoTracks();
3901 callee()->AddAudioVideoTracks();
3902 caller()->CreateDataChannel();
3903 caller()->CreateAndSetAndSignalOffer();
3904 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3905
3906 // Ensure that the data channel transport is ready.
3907 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3908 loopback_media_transports()->FlushAsyncInvokes();
3909
3910 ASSERT_NE(nullptr, caller()->data_channel());
3911 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3912 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3913 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3914
3915 // Both endpoints should agree to use datagram transport for data channels.
3916 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
3917 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
3918
3919 // Ensure data can be sent in both directions.
3920 std::string data = "hello world";
3921 caller()->data_channel()->Send(DataBuffer(data));
3922 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3923 kDefaultTimeout);
3924 callee()->data_channel()->Send(DataBuffer(data));
3925 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3926 kDefaultTimeout);
3927
3928 // Media flow should not be impacted.
3929 MediaExpectations media_expectations;
3930 media_expectations.ExpectBidirectionalAudioAndVideo();
3931 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3932}
3933
3934TEST_P(PeerConnectionIntegrationTest,
3935 DatagramTransportMediaWithDataChannelOnCaller) {
3936 // Configure the caller to attempt use of datagram transport for media and
3937 // data channels.
3938 PeerConnectionInterface::RTCConfiguration offerer_config;
3939 offerer_config.rtcp_mux_policy =
3940 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3941 offerer_config.bundle_policy =
3942 PeerConnectionInterface::kBundlePolicyMaxBundle;
3943 offerer_config.use_datagram_transport_for_data_channels = true;
3944 offerer_config.use_datagram_transport = true;
3945
3946 // Configure the callee to only use datagram transport for media.
3947 PeerConnectionInterface::RTCConfiguration answerer_config;
3948 answerer_config.rtcp_mux_policy =
3949 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3950 answerer_config.bundle_policy =
3951 PeerConnectionInterface::kBundlePolicyMaxBundle;
3952 answerer_config.use_datagram_transport = true;
3953
3954 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3955 offerer_config, answerer_config,
3956 loopback_media_transports()->first_factory(),
3957 loopback_media_transports()->second_factory()));
3958 ConnectFakeSignaling();
3959
3960 // Offer both media and data.
3961 caller()->AddAudioVideoTracks();
3962 callee()->AddAudioVideoTracks();
3963 caller()->CreateDataChannel();
3964 caller()->CreateAndSetAndSignalOffer();
3965 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3966
3967 // Ensure that the data channel transport is ready.
3968 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3969 loopback_media_transports()->FlushAsyncInvokes();
3970
3971 ASSERT_NE(nullptr, caller()->data_channel());
3972 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3973 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3974 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3975
3976 // Both endpoints should agree to use SCTP for data channels.
3977 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
3978 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
3979
3980 // Ensure data can be sent in both directions.
3981 std::string data = "hello world";
3982 caller()->data_channel()->Send(DataBuffer(data));
3983 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3984 kDefaultTimeout);
3985 callee()->data_channel()->Send(DataBuffer(data));
3986 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3987 kDefaultTimeout);
3988
3989 // Media flow should not be impacted.
3990 MediaExpectations media_expectations;
3991 media_expectations.ExpectBidirectionalAudioAndVideo();
3992 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3993}
3994
3995TEST_P(PeerConnectionIntegrationTest,
3996 DatagramTransportDataChannelWithMediaOnCallee) {
3997 // Configure the caller to attempt use of datagram transport for data
3998 // channels.
3999 PeerConnectionInterface::RTCConfiguration offerer_config;
4000 offerer_config.rtcp_mux_policy =
4001 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4002 offerer_config.bundle_policy =
4003 PeerConnectionInterface::kBundlePolicyMaxBundle;
4004 offerer_config.use_datagram_transport_for_data_channels = true;
4005
4006 // Configure the callee to use datagram transport for data channels and media.
4007 PeerConnectionInterface::RTCConfiguration answerer_config;
4008 answerer_config.rtcp_mux_policy =
4009 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4010 answerer_config.bundle_policy =
4011 PeerConnectionInterface::kBundlePolicyMaxBundle;
4012 answerer_config.use_datagram_transport_for_data_channels = true;
4013 answerer_config.use_datagram_transport = true;
4014
4015 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4016 offerer_config, answerer_config,
4017 loopback_media_transports()->first_factory(),
4018 loopback_media_transports()->second_factory()));
4019 ConnectFakeSignaling();
4020
4021 // Offer both media and data.
4022 caller()->AddAudioVideoTracks();
4023 callee()->AddAudioVideoTracks();
4024 caller()->CreateDataChannel();
4025 caller()->CreateAndSetAndSignalOffer();
4026 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4027
4028 // Ensure that the data channel transport is ready.
4029 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4030 loopback_media_transports()->FlushAsyncInvokes();
4031
4032 ASSERT_NE(nullptr, caller()->data_channel());
4033 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4034 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4035 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4036
4037 // Both endpoints should agree to use datagram transport for data channels.
4038 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4039 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4040
4041 // Ensure data can be sent in both directions.
4042 std::string data = "hello world";
4043 caller()->data_channel()->Send(DataBuffer(data));
4044 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4045 kDefaultTimeout);
4046 callee()->data_channel()->Send(DataBuffer(data));
4047 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4048 kDefaultTimeout);
4049
4050 // Media flow should not be impacted.
4051 MediaExpectations media_expectations;
4052 media_expectations.ExpectBidirectionalAudioAndVideo();
4053 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4054}
4055
4056TEST_P(PeerConnectionIntegrationTest,
4057 DatagramTransportMediaWithDataChannelOnCallee) {
4058 // Configure the caller to attempt use of datagram transport for media.
4059 PeerConnectionInterface::RTCConfiguration offerer_config;
4060 offerer_config.rtcp_mux_policy =
4061 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4062 offerer_config.bundle_policy =
4063 PeerConnectionInterface::kBundlePolicyMaxBundle;
4064 offerer_config.use_datagram_transport = true;
4065
4066 // Configure the callee to only use datagram transport for media and data
4067 // channels.
4068 PeerConnectionInterface::RTCConfiguration answerer_config;
4069 answerer_config.rtcp_mux_policy =
4070 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4071 answerer_config.bundle_policy =
4072 PeerConnectionInterface::kBundlePolicyMaxBundle;
4073 answerer_config.use_datagram_transport = true;
4074 answerer_config.use_datagram_transport_for_data_channels = true;
4075
4076 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4077 offerer_config, answerer_config,
4078 loopback_media_transports()->first_factory(),
4079 loopback_media_transports()->second_factory()));
4080 ConnectFakeSignaling();
4081
4082 // Offer both media and data.
4083 caller()->AddAudioVideoTracks();
4084 callee()->AddAudioVideoTracks();
4085 caller()->CreateDataChannel();
4086 caller()->CreateAndSetAndSignalOffer();
4087 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4088
4089 // Ensure that the data channel transport is ready.
4090 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4091 loopback_media_transports()->FlushAsyncInvokes();
4092
4093 ASSERT_NE(nullptr, caller()->data_channel());
4094 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4095 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4096 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4097
4098 // Both endpoints should agree to use SCTP for data channels.
4099 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
4100 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
4101
4102 // Ensure data can be sent in both directions.
4103 std::string data = "hello world";
4104 caller()->data_channel()->Send(DataBuffer(data));
4105 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4106 kDefaultTimeout);
4107 callee()->data_channel()->Send(DataBuffer(data));
4108 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4109 kDefaultTimeout);
4110
4111 // Media flow should not be impacted.
4112 MediaExpectations media_expectations;
4113 media_expectations.ExpectBidirectionalAudioAndVideo();
4114 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4115}
4116
4117TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelAndMedia) {
4118 // Configure the caller to use datagram transport for data channels and media.
4119 PeerConnectionInterface::RTCConfiguration offerer_config;
4120 offerer_config.rtcp_mux_policy =
4121 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4122 offerer_config.bundle_policy =
4123 PeerConnectionInterface::kBundlePolicyMaxBundle;
4124 offerer_config.use_datagram_transport_for_data_channels = true;
4125 offerer_config.use_datagram_transport = true;
4126
4127 // Configure the callee to use datagram transport for data channels and media.
4128 PeerConnectionInterface::RTCConfiguration answerer_config;
4129 answerer_config.rtcp_mux_policy =
4130 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4131 answerer_config.bundle_policy =
4132 PeerConnectionInterface::kBundlePolicyMaxBundle;
4133 answerer_config.use_datagram_transport_for_data_channels = true;
4134 answerer_config.use_datagram_transport = true;
4135
4136 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4137 offerer_config, answerer_config,
4138 loopback_media_transports()->first_factory(),
4139 loopback_media_transports()->second_factory()));
4140 ConnectFakeSignaling();
4141
4142 // Offer both media and data.
4143 caller()->AddAudioVideoTracks();
4144 callee()->AddAudioVideoTracks();
4145 caller()->CreateDataChannel();
4146 caller()->CreateAndSetAndSignalOffer();
4147 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4148
4149 // Ensure that the data channel transport is ready.
4150 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4151 loopback_media_transports()->FlushAsyncInvokes();
4152
4153 ASSERT_NE(nullptr, caller()->data_channel());
4154 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4155 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4156 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4157
4158 // Both endpoints should agree to use datagram transport for data channels.
4159 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
4160 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
4161
4162 // Ensure data can be sent in both directions.
4163 std::string data = "hello world";
4164 caller()->data_channel()->Send(DataBuffer(data));
4165 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4166 kDefaultTimeout);
4167 callee()->data_channel()->Send(DataBuffer(data));
4168 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4169 kDefaultTimeout);
4170
4171 // Media flow should not be impacted.
4172 MediaExpectations media_expectations;
4173 media_expectations.ExpectBidirectionalAudioAndVideo();
4174 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4175}
4176
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004177// Tests that data channels use SCTP instead of datagram transport if datagram
4178// transport is configured in receive-only mode on the caller.
4179TEST_P(PeerConnectionIntegrationTest,
4180 DatagramTransportDataChannelReceiveOnlyOnCallerUsesSctp) {
4181 PeerConnectionInterface::RTCConfiguration rtc_config;
4182 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4183 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4184 rtc_config.use_datagram_transport_for_data_channels = true;
4185 rtc_config.use_datagram_transport_for_data_channels_receive_only = true;
4186
4187 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4188 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4189 loopback_media_transports()->second_factory()));
4190 ConnectFakeSignaling();
4191
4192 // The caller should offer a data channel using SCTP.
4193 caller()->CreateDataChannel();
4194 caller()->AddAudioVideoTracks();
4195 callee()->AddAudioVideoTracks();
4196 caller()->CreateAndSetAndSignalOffer();
4197 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4198
4199 ASSERT_NE(nullptr, caller()->data_channel());
4200 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4201 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4202 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4203
4204 // SCTP transports should be present, since they are in use.
4205 EXPECT_NE(caller()->pc()->GetSctpTransport(), nullptr);
4206 EXPECT_NE(callee()->pc()->GetSctpTransport(), nullptr);
4207
4208 // Ensure data can be sent in both directions.
4209 std::string data = "hello world";
4210 caller()->data_channel()->Send(DataBuffer(data));
4211 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4212 kDefaultTimeout);
4213 callee()->data_channel()->Send(DataBuffer(data));
4214 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4215 kDefaultTimeout);
4216}
4217
deadbeef1dcb1642017-03-29 21:08:16 -07004218#endif // HAVE_SCTP
4219
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004220// Tests that a callee configured for receive-only use of datagram transport
4221// data channels accepts them on incoming calls.
4222TEST_P(PeerConnectionIntegrationTest,
4223 DatagramTransportDataChannelReceiveOnlyOnCallee) {
4224 PeerConnectionInterface::RTCConfiguration offerer_config;
4225 offerer_config.rtcp_mux_policy =
4226 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4227 offerer_config.bundle_policy =
4228 PeerConnectionInterface::kBundlePolicyMaxBundle;
4229 offerer_config.use_datagram_transport_for_data_channels = true;
4230
4231 PeerConnectionInterface::RTCConfiguration answerer_config;
4232 answerer_config.rtcp_mux_policy =
4233 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4234 answerer_config.bundle_policy =
4235 PeerConnectionInterface::kBundlePolicyMaxBundle;
4236 answerer_config.use_datagram_transport_for_data_channels = true;
4237 answerer_config.use_datagram_transport_for_data_channels_receive_only = true;
4238
4239 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4240 offerer_config, answerer_config,
4241 loopback_media_transports()->first_factory(),
4242 loopback_media_transports()->second_factory()));
4243 ConnectFakeSignaling();
4244
4245 caller()->CreateDataChannel();
4246 caller()->CreateAndSetAndSignalOffer();
4247 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4248
4249 // Ensure that the data channel transport is ready.
4250 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4251 loopback_media_transports()->FlushAsyncInvokes();
4252
4253 ASSERT_NE(nullptr, caller()->data_channel());
4254 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4255 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4256 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4257
4258 // SCTP transports should not be present, since datagram transport is used.
4259 EXPECT_EQ(caller()->pc()->GetSctpTransport(), nullptr);
4260 EXPECT_EQ(callee()->pc()->GetSctpTransport(), nullptr);
4261
4262 // Ensure data can be sent in both directions.
4263 std::string data = "hello world";
4264 caller()->data_channel()->Send(DataBuffer(data));
4265 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4266 kDefaultTimeout);
4267 callee()->data_channel()->Send(DataBuffer(data));
4268 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4269 kDefaultTimeout);
4270}
4271
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004272// This test sets up a call between two parties with a datagram transport data
4273// channel.
4274TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelEndToEnd) {
4275 PeerConnectionInterface::RTCConfiguration rtc_config;
4276 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4277 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4278 rtc_config.use_datagram_transport_for_data_channels = true;
4279 rtc_config.enable_dtls_srtp = false;
4280 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4281 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4282 loopback_media_transports()->second_factory()));
4283 ConnectFakeSignaling();
4284
4285 // Expect that data channel created on caller side will show up for callee as
4286 // well.
4287 caller()->CreateDataChannel();
4288 caller()->CreateAndSetAndSignalOffer();
4289 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4290
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004291 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004292 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4293 loopback_media_transports()->FlushAsyncInvokes();
4294
4295 // Caller data channel should already exist (it created one). Callee data
4296 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4297 ASSERT_NE(nullptr, caller()->data_channel());
4298 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4299 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4300 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4301
4302 // Ensure data can be sent in both directions.
4303 std::string data = "hello world";
4304 caller()->data_channel()->Send(DataBuffer(data));
4305 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4306 kDefaultTimeout);
4307 callee()->data_channel()->Send(DataBuffer(data));
4308 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4309 kDefaultTimeout);
4310}
4311
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004312// Tests that 'zero-rtt' data channel transports (which are ready-to-send as
4313// soon as they're created) work correctly.
4314TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelZeroRtt) {
4315 PeerConnectionInterface::RTCConfiguration rtc_config;
4316 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4317 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4318 rtc_config.use_datagram_transport_for_data_channels = true;
4319 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
4320 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4321 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4322 loopback_media_transports()->second_factory()));
4323 ConnectFakeSignaling();
4324
4325 // Ensure that the callee's media transport is ready-to-send immediately.
4326 // Note that only the callee can become writable in zero RTTs. The caller
4327 // must wait for the callee's answer.
4328 loopback_media_transports()->SetSecondStateAfterConnect(
4329 webrtc::MediaTransportState::kWritable);
4330 loopback_media_transports()->FlushAsyncInvokes();
4331
4332 // Expect that data channel created on caller side will show up for callee as
4333 // well.
4334 caller()->CreateDataChannel();
4335 caller()->CreateAndSetAndSignalOffer();
4336 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4337
4338 loopback_media_transports()->SetFirstState(
4339 webrtc::MediaTransportState::kWritable);
4340 loopback_media_transports()->FlushAsyncInvokes();
4341
4342 // Caller data channel should already exist (it created one). Callee data
4343 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4344 ASSERT_NE(nullptr, caller()->data_channel());
4345 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4346 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4347 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4348
4349 // Ensure data can be sent in both directions.
4350 std::string data = "hello world";
4351 caller()->data_channel()->Send(DataBuffer(data));
4352 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4353 kDefaultTimeout);
4354 callee()->data_channel()->Send(DataBuffer(data));
4355 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4356 kDefaultTimeout);
4357}
4358
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004359// Ensures that when the callee closes a datagram transport data channel, the
4360// closing procedure results in the data channel being closed for the caller
4361// as well.
4362TEST_P(PeerConnectionIntegrationTest,
4363 DatagramTransportDataChannelCalleeCloses) {
4364 PeerConnectionInterface::RTCConfiguration rtc_config;
4365 rtc_config.use_datagram_transport_for_data_channels = true;
4366 rtc_config.enable_dtls_srtp = false;
4367 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4368 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4369 loopback_media_transports()->second_factory()));
4370 ConnectFakeSignaling();
4371
4372 // Create a data channel on the caller and signal it to the callee.
4373 caller()->CreateDataChannel();
4374 caller()->CreateAndSetAndSignalOffer();
4375 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4376
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004377 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004378 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4379 loopback_media_transports()->FlushAsyncInvokes();
4380
4381 // Data channels exist and open on both ends of the connection.
4382 ASSERT_NE(nullptr, caller()->data_channel());
4383 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4384 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4385 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4386
4387 // Close the data channel on the callee side, and wait for it to reach the
4388 // "closed" state on both sides.
4389 callee()->data_channel()->Close();
4390 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
4391 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
4392}
4393
4394// Tests that datagram transport data channels can do in-band negotiation.
4395TEST_P(PeerConnectionIntegrationTest,
4396 DatagramTransportDataChannelConfigSentToOtherSide) {
4397 PeerConnectionInterface::RTCConfiguration rtc_config;
4398 rtc_config.use_datagram_transport_for_data_channels = true;
4399 rtc_config.enable_dtls_srtp = false;
4400 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4401 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4402 loopback_media_transports()->second_factory()));
4403 ConnectFakeSignaling();
4404
4405 // Create a data channel with a non-default configuration and signal it to the
4406 // callee.
4407 webrtc::DataChannelInit init;
4408 init.id = 53;
4409 init.maxRetransmits = 52;
4410 caller()->CreateDataChannel("data-channel", &init);
4411 caller()->CreateAndSetAndSignalOffer();
4412 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4413
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004414 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004415 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4416 loopback_media_transports()->FlushAsyncInvokes();
4417
4418 // Ensure that the data channel exists on the callee with the correct
4419 // configuration.
4420 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4421 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4422 // Since "negotiate" is false, the "id" parameter is ignored.
4423 EXPECT_NE(init.id, callee()->data_channel()->id());
4424 EXPECT_EQ("data-channel", callee()->data_channel()->label());
4425 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
4426 EXPECT_FALSE(callee()->data_channel()->negotiated());
4427}
4428
4429TEST_P(PeerConnectionIntegrationTest,
4430 DatagramTransportDataChannelRejectedWithNoFallback) {
4431 PeerConnectionInterface::RTCConfiguration offerer_config;
4432 offerer_config.rtcp_mux_policy =
4433 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4434 offerer_config.bundle_policy =
4435 PeerConnectionInterface::kBundlePolicyMaxBundle;
4436 offerer_config.use_datagram_transport_for_data_channels = true;
4437 // Disabling DTLS precludes a fallback to SCTP.
4438 offerer_config.enable_dtls_srtp = false;
4439
4440 PeerConnectionInterface::RTCConfiguration answerer_config;
4441 answerer_config.rtcp_mux_policy =
4442 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4443 answerer_config.bundle_policy =
4444 PeerConnectionInterface::kBundlePolicyMaxBundle;
4445 // Both endpoints must disable DTLS or SetRemoteDescription will fail.
4446 answerer_config.enable_dtls_srtp = false;
4447
4448 // Configure one endpoint to use datagram transport for data channels while
4449 // the other does not.
4450 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4451 offerer_config, answerer_config,
4452 loopback_media_transports()->first_factory(), nullptr));
4453 ConnectFakeSignaling();
4454
4455 // The caller offers a data channel using either datagram transport or SCTP.
4456 caller()->CreateDataChannel();
4457 caller()->AddAudioVideoTracks();
4458 callee()->AddAudioVideoTracks();
4459 caller()->CreateAndSetAndSignalOffer();
4460 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4461
4462 // Caller data channel should already exist (it created one). Callee data
4463 // channel should not exist, since negotiation happens in-band, not in SDP.
4464 EXPECT_NE(nullptr, caller()->data_channel());
4465 EXPECT_EQ(nullptr, callee()->data_channel());
4466
4467 // The caller's data channel should close when the datagram transport is
4468 // rejected.
4469 EXPECT_FALSE(caller()->data_observer()->IsOpen());
4470
4471 // Media flow should not be impacted by the failed data channel.
4472 MediaExpectations media_expectations;
4473 media_expectations.ExpectBidirectionalAudioAndVideo();
4474 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4475}
4476
deadbeef1dcb1642017-03-29 21:08:16 -07004477// Test that the ICE connection and gathering states eventually reach
4478// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08004479TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07004480 ASSERT_TRUE(CreatePeerConnectionWrappers());
4481 ConnectFakeSignaling();
4482 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08004483 caller()->AddAudioVideoTracks();
4484 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004485 caller()->CreateAndSetAndSignalOffer();
4486 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4487 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4488 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
4489 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4490 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
4491 // After the best candidate pair is selected and all candidates are signaled,
4492 // the ICE connection state should reach "complete".
4493 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
4494 // answerer/"callee" by default) only reaches "connected". When this is
4495 // fixed, this test should be updated.
4496 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4497 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00004498 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4499 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07004500}
4501
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004502constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
4503 cricket::PORTALLOCATOR_DISABLE_RELAY |
4504 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004505
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004506// Use a mock resolver to resolve the hostname back to the original IP on both
4507// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004508TEST_P(PeerConnectionIntegrationTest,
4509 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004510 auto caller_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004511 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004512 auto callee_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004513 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004514 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
4515 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004516
4517 // This also verifies that the injected AsyncResolverFactory is used by
4518 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004519 EXPECT_CALL(*caller_resolver_factory, Create())
4520 .WillOnce(Return(&caller_async_resolver));
4521 webrtc::PeerConnectionDependencies caller_deps(nullptr);
4522 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
4523
4524 EXPECT_CALL(*callee_resolver_factory, Create())
4525 .WillOnce(Return(&callee_async_resolver));
4526 webrtc::PeerConnectionDependencies callee_deps(nullptr);
4527 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
4528
4529 PeerConnectionInterface::RTCConfiguration config;
4530 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4531 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4532
4533 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4534 config, std::move(caller_deps), config, std::move(callee_deps)));
4535
4536 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
4537 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
4538
4539 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07004540 caller()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004541 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wangecd30542019-05-22 14:34:56 -07004542 callee()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004543 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004544
4545 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004546
4547 ConnectFakeSignaling();
4548 caller()->AddAudioVideoTracks();
4549 callee()->AddAudioVideoTracks();
4550 caller()->CreateAndSetAndSignalOffer();
4551 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4552 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4553 caller()->ice_connection_state(), kDefaultTimeout);
4554 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4555 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08004556
Ying Wangef3998f2019-12-09 13:06:53 +01004557 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
4558 "WebRTC.PeerConnection.CandidatePairType_UDP",
4559 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004560}
4561
Steve Antonede9ca52017-10-16 13:04:27 -07004562// Test that firewalling the ICE connection causes the clients to identify the
4563// disconnected state and then removing the firewall causes them to reconnect.
4564class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004565 : public PeerConnectionIntegrationBaseTest,
4566 public ::testing::WithParamInterface<
4567 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07004568 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004569 PeerConnectionIntegrationIceStatesTest()
4570 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
4571 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07004572 }
4573
4574 void StartStunServer(const SocketAddress& server_address) {
4575 stun_server_.reset(
4576 cricket::TestStunServer::Create(network_thread(), server_address));
4577 }
4578
4579 bool TestIPv6() {
4580 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
4581 }
4582
4583 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004584 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
4585 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07004586 }
4587
4588 std::vector<SocketAddress> CallerAddresses() {
4589 std::vector<SocketAddress> addresses;
4590 addresses.push_back(SocketAddress("1.1.1.1", 0));
4591 if (TestIPv6()) {
4592 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
4593 }
4594 return addresses;
4595 }
4596
4597 std::vector<SocketAddress> CalleeAddresses() {
4598 std::vector<SocketAddress> addresses;
4599 addresses.push_back(SocketAddress("2.2.2.2", 0));
4600 if (TestIPv6()) {
4601 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
4602 }
4603 return addresses;
4604 }
4605
4606 void SetUpNetworkInterfaces() {
4607 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07004608 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
4609 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07004610
4611 // Add network addresses for test.
4612 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004613 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004614 }
4615 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004616 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004617 }
4618 }
4619
4620 private:
4621 uint32_t port_allocator_flags_;
4622 std::unique_ptr<cricket::TestStunServer> stun_server_;
4623};
4624
Yves Gerey100fe632020-01-17 19:15:53 +01004625// Ensure FakeClockForTest is constructed first (see class for rationale).
4626class PeerConnectionIntegrationIceStatesTestWithFakeClock
4627 : public FakeClockForTest,
4628 public PeerConnectionIntegrationIceStatesTest {};
4629
Steve Antonede9ca52017-10-16 13:04:27 -07004630// Tests that the PeerConnection goes through all the ICE gathering/connection
4631// states over the duration of the call. This includes Disconnected and Failed
4632// states, induced by putting a firewall between the peers and waiting for them
4633// to time out.
Yves Gerey100fe632020-01-17 19:15:53 +01004634TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock, VerifyIceStates) {
Steve Antonede9ca52017-10-16 13:04:27 -07004635 const SocketAddress kStunServerAddress =
4636 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
4637 StartStunServer(kStunServerAddress);
4638
4639 PeerConnectionInterface::RTCConfiguration config;
4640 PeerConnectionInterface::IceServer ice_stun_server;
4641 ice_stun_server.urls.push_back(
4642 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4643 kStunServerAddress.PortAsString());
4644 config.servers.push_back(ice_stun_server);
4645
4646 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4647 ConnectFakeSignaling();
4648 SetPortAllocatorFlags();
4649 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004650 caller()->AddAudioVideoTracks();
4651 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004652
4653 // Initial state before anything happens.
4654 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4655 caller()->ice_gathering_state());
4656 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4657 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004658 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4659 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004660
4661 // Start the call by creating the offer, setting it as the local description,
4662 // then sending it to the peer who will respond with an answer. This happens
4663 // asynchronously so that we can watch the states as it runs in the
4664 // background.
4665 caller()->CreateAndSetAndSignalOffer();
4666
Steve Antona9b67ce2020-01-16 14:00:44 -08004667 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4668 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004669 FakeClock());
Steve Antona9b67ce2020-01-16 14:00:44 -08004670 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4671 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004672 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004673
4674 // Verify that the observer was notified of the intermediate transitions.
4675 EXPECT_THAT(caller()->ice_connection_state_history(),
4676 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4677 PeerConnectionInterface::kIceConnectionConnected,
4678 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004679 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4680 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4681 PeerConnectionInterface::kIceConnectionConnected,
4682 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004683 EXPECT_THAT(
4684 caller()->peer_connection_state_history(),
4685 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004686 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004687 EXPECT_THAT(caller()->ice_gathering_state_history(),
4688 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4689 PeerConnectionInterface::kIceGatheringComplete));
4690
4691 // Block connections to/from the caller and wait for ICE to become
4692 // disconnected.
4693 for (const auto& caller_address : CallerAddresses()) {
4694 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4695 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004696 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004697 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4698 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004699 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004700 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4701 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004702 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004703
4704 // Let ICE re-establish by removing the firewall rules.
4705 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004706 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004707 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4708 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004709 FakeClock());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004710 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004711 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004712 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004713
4714 // According to RFC7675, if there is no response within 30 seconds then the
4715 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004716 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004717 constexpr int kConsentTimeout = 30000;
4718 for (const auto& caller_address : CallerAddresses()) {
4719 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4720 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004721 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004722 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4723 caller()->ice_connection_state(), kConsentTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004724 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004725 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4726 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004727 kConsentTimeout, FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004728}
4729
4730// Tests that if the connection doesn't get set up properly we eventually reach
4731// the "failed" iceConnectionState.
Yves Gerey100fe632020-01-17 19:15:53 +01004732TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock,
4733 IceStateSetupFailure) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004734 // Block connections to/from the caller and wait for ICE to become
4735 // disconnected.
4736 for (const auto& caller_address : CallerAddresses()) {
4737 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4738 }
4739
4740 ASSERT_TRUE(CreatePeerConnectionWrappers());
4741 ConnectFakeSignaling();
4742 SetPortAllocatorFlags();
4743 SetUpNetworkInterfaces();
4744 caller()->AddAudioVideoTracks();
4745 caller()->CreateAndSetAndSignalOffer();
4746
4747 // According to RFC7675, if there is no response within 30 seconds then the
4748 // peer should consider the other side to have rejected the connection. This
4749 // is signaled by the state transitioning to "failed".
4750 constexpr int kConsentTimeout = 30000;
4751 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4752 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004753 kConsentTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004754}
4755
4756// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4757// and that the statistics in the metric observers are updated correctly.
4758TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4759 ASSERT_TRUE(CreatePeerConnectionWrappers());
4760 ConnectFakeSignaling();
4761 SetPortAllocatorFlags();
4762 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004763 caller()->AddAudioVideoTracks();
4764 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004765 caller()->CreateAndSetAndSignalOffer();
4766
4767 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton692f3c72020-01-16 14:12:31 -08004768 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4769 caller()->ice_connection_state(), kDefaultTimeout);
4770 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4771 callee()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07004772
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004773 // TODO(bugs.webrtc.org/9456): Fix it.
4774 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4775 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4776 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4777 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004778 if (TestIPv6()) {
4779 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4780 // connection.
Ying Wangef3998f2019-12-09 13:06:53 +01004781 EXPECT_METRIC_EQ(0, num_best_ipv4);
4782 EXPECT_METRIC_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004783 } else {
Ying Wangef3998f2019-12-09 13:06:53 +01004784 EXPECT_METRIC_EQ(1, num_best_ipv4);
4785 EXPECT_METRIC_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004786 }
4787
Ying Wangef3998f2019-12-09 13:06:53 +01004788 EXPECT_METRIC_EQ(0, webrtc::metrics::NumEvents(
4789 "WebRTC.PeerConnection.CandidatePairType_UDP",
4790 webrtc::kIceCandidatePairHostHost));
4791 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
4792 "WebRTC.PeerConnection.CandidatePairType_UDP",
4793 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004794}
4795
4796constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4797 cricket::PORTALLOCATOR_DISABLE_STUN |
4798 cricket::PORTALLOCATOR_DISABLE_RELAY;
4799constexpr uint32_t kFlagsIPv6NoStun =
4800 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4801 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4802constexpr uint32_t kFlagsIPv4Stun =
4803 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4804
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004805INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004806 PeerConnectionIntegrationTest,
4807 PeerConnectionIntegrationIceStatesTest,
4808 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4809 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4810 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4811 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004812
Yves Gerey100fe632020-01-17 19:15:53 +01004813INSTANTIATE_TEST_SUITE_P(
4814 PeerConnectionIntegrationTest,
4815 PeerConnectionIntegrationIceStatesTestWithFakeClock,
4816 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4817 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4818 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4819 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
4820
deadbeef1dcb1642017-03-29 21:08:16 -07004821// This test sets up a call between two parties with audio and video.
4822// During the call, the caller restarts ICE and the test verifies that
4823// new ICE candidates are generated and audio and video still can flow, and the
4824// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004825TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004826 ASSERT_TRUE(CreatePeerConnectionWrappers());
4827 ConnectFakeSignaling();
4828 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004829 caller()->AddAudioVideoTracks();
4830 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004831 caller()->CreateAndSetAndSignalOffer();
4832 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4833 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4834 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004835 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4836 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004837
4838 // To verify that the ICE restart actually occurs, get
4839 // ufrag/password/candidates before and after restart.
4840 // Create an SDP string of the first audio candidate for both clients.
4841 const webrtc::IceCandidateCollection* audio_candidates_caller =
4842 caller()->pc()->local_description()->candidates(0);
4843 const webrtc::IceCandidateCollection* audio_candidates_callee =
4844 callee()->pc()->local_description()->candidates(0);
4845 ASSERT_GT(audio_candidates_caller->count(), 0u);
4846 ASSERT_GT(audio_candidates_callee->count(), 0u);
4847 std::string caller_candidate_pre_restart;
4848 ASSERT_TRUE(
4849 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4850 std::string callee_candidate_pre_restart;
4851 ASSERT_TRUE(
4852 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4853 const cricket::SessionDescription* desc =
4854 caller()->pc()->local_description()->description();
4855 std::string caller_ufrag_pre_restart =
4856 desc->transport_infos()[0].description.ice_ufrag;
4857 desc = callee()->pc()->local_description()->description();
4858 std::string callee_ufrag_pre_restart =
4859 desc->transport_infos()[0].description.ice_ufrag;
4860
Alex Drake00c7ecf2019-08-06 10:54:47 -07004861 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004862 // Have the caller initiate an ICE restart.
4863 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4864 caller()->CreateAndSetAndSignalOffer();
4865 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4866 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4867 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004868 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004869 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4870
4871 // Grab the ufrags/candidates again.
4872 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4873 audio_candidates_callee = 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_post_restart;
4877 ASSERT_TRUE(
4878 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4879 std::string callee_candidate_post_restart;
4880 ASSERT_TRUE(
4881 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4882 desc = caller()->pc()->local_description()->description();
4883 std::string caller_ufrag_post_restart =
4884 desc->transport_infos()[0].description.ice_ufrag;
4885 desc = callee()->pc()->local_description()->description();
4886 std::string callee_ufrag_post_restart =
4887 desc->transport_infos()[0].description.ice_ufrag;
4888 // Sanity check that an ICE restart was actually negotiated in SDP.
4889 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4890 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4891 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4892 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07004893 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004894
4895 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004896 MediaExpectations media_expectations;
4897 media_expectations.ExpectBidirectionalAudioAndVideo();
4898 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004899}
4900
4901// Verify that audio/video can be received end-to-end when ICE renomination is
4902// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004903TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004904 PeerConnectionInterface::RTCConfiguration config;
4905 config.enable_ice_renomination = true;
4906 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4907 ConnectFakeSignaling();
4908 // Do normal offer/answer and wait for some frames to be received in each
4909 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004910 caller()->AddAudioVideoTracks();
4911 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004912 caller()->CreateAndSetAndSignalOffer();
4913 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4914 // Sanity check that ICE renomination was actually negotiated.
4915 const cricket::SessionDescription* desc =
4916 caller()->pc()->local_description()->description();
4917 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004918 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004919 }
4920 desc = callee()->pc()->local_description()->description();
4921 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004922 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004923 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004924 MediaExpectations media_expectations;
4925 media_expectations.ExpectBidirectionalAudioAndVideo();
4926 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004927}
4928
Steve Anton6f25b092017-10-23 09:39:20 -07004929// With a max bundle policy and RTCP muxing, adding a new media description to
4930// the connection should not affect ICE at all because the new media will use
4931// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004932TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004933 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004934 PeerConnectionInterface::RTCConfiguration config;
4935 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4936 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4937 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4938 config, PeerConnectionInterface::RTCConfiguration()));
4939 ConnectFakeSignaling();
4940
Steve Anton15324772018-01-16 10:26:49 -08004941 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004942 caller()->CreateAndSetAndSignalOffer();
4943 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004944 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4945 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004946
4947 caller()->clear_ice_connection_state_history();
4948
Steve Anton15324772018-01-16 10:26:49 -08004949 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004950 caller()->CreateAndSetAndSignalOffer();
4951 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4952
4953 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4954}
4955
deadbeef1dcb1642017-03-29 21:08:16 -07004956// This test sets up a call between two parties with audio and video. It then
4957// renegotiates setting the video m-line to "port 0", then later renegotiates
4958// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004959TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004960 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4961 ASSERT_TRUE(CreatePeerConnectionWrappers());
4962 ConnectFakeSignaling();
4963
4964 // Do initial negotiation, only sending media from the caller. Will result in
4965 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004966 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004967 caller()->CreateAndSetAndSignalOffer();
4968 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4969
4970 // Negotiate again, disabling the video "m=" section (the callee will set the
4971 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004972 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4973 PeerConnectionInterface::RTCOfferAnswerOptions options;
4974 options.offer_to_receive_video = 0;
4975 callee()->SetOfferAnswerOptions(options);
4976 } else {
4977 callee()->SetRemoteOfferHandler([this] {
4978 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4979 });
4980 }
deadbeef1dcb1642017-03-29 21:08:16 -07004981 caller()->CreateAndSetAndSignalOffer();
4982 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4983 // Sanity check that video "m=" section was actually rejected.
4984 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4985 callee()->pc()->local_description()->description());
4986 ASSERT_NE(nullptr, answer_video_content);
4987 ASSERT_TRUE(answer_video_content->rejected);
4988
4989 // Enable video and do negotiation again, making sure video is received
4990 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004991 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4992 PeerConnectionInterface::RTCOfferAnswerOptions options;
4993 options.offer_to_receive_video = 1;
4994 callee()->SetOfferAnswerOptions(options);
4995 } else {
4996 // The caller's transceiver is stopped, so we need to add another track.
4997 auto caller_transceiver =
4998 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4999 EXPECT_TRUE(caller_transceiver->stopped());
5000 caller()->AddVideoTrack();
5001 }
5002 callee()->AddVideoTrack();
5003 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07005004 caller()->CreateAndSetAndSignalOffer();
5005 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005006
deadbeef1dcb1642017-03-29 21:08:16 -07005007 // Verify the caller receives frames from the newly added stream, and the
5008 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005009 MediaExpectations media_expectations;
5010 media_expectations.CalleeExpectsSomeAudio();
5011 media_expectations.ExpectBidirectionalVideo();
5012 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005013}
5014
deadbeef1dcb1642017-03-29 21:08:16 -07005015// This tests that if we negotiate after calling CreateSender but before we
5016// have a track, then set a track later, frames from the newly-set track are
5017// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005018TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07005019 MediaFlowsAfterEarlyWarmupWithCreateSender) {
5020 ASSERT_TRUE(CreatePeerConnectionWrappers());
5021 ConnectFakeSignaling();
5022 auto caller_audio_sender =
5023 caller()->pc()->CreateSender("audio", "caller_stream");
5024 auto caller_video_sender =
5025 caller()->pc()->CreateSender("video", "caller_stream");
5026 auto callee_audio_sender =
5027 callee()->pc()->CreateSender("audio", "callee_stream");
5028 auto callee_video_sender =
5029 callee()->pc()->CreateSender("video", "callee_stream");
5030 caller()->CreateAndSetAndSignalOffer();
5031 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5032 // Wait for ICE to complete, without any tracks being set.
5033 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5034 caller()->ice_connection_state(), kMaxWaitForFramesMs);
5035 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5036 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5037 // Now set the tracks, and expect frames to immediately start flowing.
5038 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
5039 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
5040 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
5041 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08005042 MediaExpectations media_expectations;
5043 media_expectations.ExpectBidirectionalAudioAndVideo();
5044 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5045}
5046
5047// This tests that if we negotiate after calling AddTransceiver but before we
5048// have a track, then set a track later, frames from the newly-set tracks are
5049// received end-to-end.
5050TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5051 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
5052 ASSERT_TRUE(CreatePeerConnectionWrappers());
5053 ConnectFakeSignaling();
5054 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
5055 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
5056 auto caller_audio_sender = audio_result.MoveValue()->sender();
5057 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
5058 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
5059 auto caller_video_sender = video_result.MoveValue()->sender();
5060 callee()->SetRemoteOfferHandler([this] {
5061 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
5062 callee()->pc()->GetTransceivers()[0]->SetDirection(
5063 RtpTransceiverDirection::kSendRecv);
5064 callee()->pc()->GetTransceivers()[1]->SetDirection(
5065 RtpTransceiverDirection::kSendRecv);
5066 });
5067 caller()->CreateAndSetAndSignalOffer();
5068 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5069 // Wait for ICE to complete, without any tracks being set.
5070 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
5071 caller()->ice_connection_state(), kMaxWaitForFramesMs);
5072 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5073 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5074 // Now set the tracks, and expect frames to immediately start flowing.
5075 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
5076 auto callee_video_sender = callee()->pc()->GetSenders()[1];
5077 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
5078 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
5079 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
5080 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
5081 MediaExpectations media_expectations;
5082 media_expectations.ExpectBidirectionalAudioAndVideo();
5083 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005084}
5085
5086// This test verifies that a remote video track can be added via AddStream,
5087// and sent end-to-end. For this particular test, it's simply echoed back
5088// from the caller to the callee, rather than being forwarded to a third
5089// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005090TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07005091 ASSERT_TRUE(CreatePeerConnectionWrappers());
5092 ConnectFakeSignaling();
5093 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08005094 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07005095 caller()->CreateAndSetAndSignalOffer();
5096 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02005097 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07005098
5099 // Echo the stream back, and do a new offer/anwer (initiated by callee this
5100 // time).
5101 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
5102 callee()->CreateAndSetAndSignalOffer();
5103 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
5104
Seth Hampson2f0d7022018-02-20 11:54:42 -08005105 MediaExpectations media_expectations;
5106 media_expectations.ExpectBidirectionalVideo();
5107 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07005108}
5109
5110// Test that we achieve the expected end-to-end connection time, using a
5111// fake clock and simulated latency on the media and signaling paths.
5112// We use a TURN<->TURN connection because this is usually the quickest to
5113// set up initially, especially when we're confident the connection will work
5114// and can start sending media before we get a STUN response.
5115//
5116// With various optimizations enabled, here are the network delays we expect to
5117// be on the critical path:
5118// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
5119// signaling answer (with DTLS fingerprint).
5120// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
5121// using TURN<->TURN pair, and DTLS exchange is 4 packets,
5122// the first of which should have arrived before the answer.
Yves Gerey100fe632020-01-17 19:15:53 +01005123TEST_P(PeerConnectionIntegrationTestWithFakeClock,
5124 EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07005125 static constexpr int media_hop_delay_ms = 50;
5126 static constexpr int signaling_trip_delay_ms = 500;
5127 // For explanation of these values, see comment above.
5128 static constexpr int required_media_hops = 9;
5129 static constexpr int required_signaling_trips = 2;
5130 // For internal delays (such as posting an event asychronously).
5131 static constexpr int allowed_internal_delay_ms = 20;
5132 static constexpr int total_connection_time_ms =
5133 media_hop_delay_ms * required_media_hops +
5134 signaling_trip_delay_ms * required_signaling_trips +
5135 allowed_internal_delay_ms;
5136
5137 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
5138 3478};
5139 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
5140 0};
5141 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
5142 3478};
5143 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
5144 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07005145 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
5146 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005147
Seth Hampsonaed71642018-06-11 07:41:32 -07005148 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
5149 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07005150 // Bypass permission check on received packets so media can be sent before
5151 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07005152 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
5153 turn_server_1->set_enable_permission_checks(false);
5154 });
5155 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
5156 turn_server_2->set_enable_permission_checks(false);
5157 });
deadbeef1dcb1642017-03-29 21:08:16 -07005158
5159 PeerConnectionInterface::RTCConfiguration client_1_config;
5160 webrtc::PeerConnectionInterface::IceServer ice_server_1;
5161 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
5162 ice_server_1.username = "test";
5163 ice_server_1.password = "test";
5164 client_1_config.servers.push_back(ice_server_1);
5165 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5166 client_1_config.presume_writable_when_fully_relayed = true;
5167
5168 PeerConnectionInterface::RTCConfiguration client_2_config;
5169 webrtc::PeerConnectionInterface::IceServer ice_server_2;
5170 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
5171 ice_server_2.username = "test";
5172 ice_server_2.password = "test";
5173 client_2_config.servers.push_back(ice_server_2);
5174 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5175 client_2_config.presume_writable_when_fully_relayed = true;
5176
5177 ASSERT_TRUE(
5178 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5179 // Set up the simulated delays.
5180 SetSignalingDelayMs(signaling_trip_delay_ms);
5181 ConnectFakeSignaling();
5182 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
5183 virtual_socket_server()->UpdateDelayDistribution();
5184
5185 // Set "offer to receive audio/video" without adding any tracks, so we just
5186 // set up ICE/DTLS with no media.
5187 PeerConnectionInterface::RTCOfferAnswerOptions options;
5188 options.offer_to_receive_audio = 1;
5189 options.offer_to_receive_video = 1;
5190 caller()->SetOfferAnswerOptions(options);
5191 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07005192 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
Yves Gerey100fe632020-01-17 19:15:53 +01005193 FakeClock());
Seth Hampson1d4a76d2018-06-19 14:31:41 -07005194 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
5195 // If this is not done a DCHECK can be hit in ports.cc, because a large
5196 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07005197 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07005198}
5199
Jonas Orelandbdcee282017-10-10 14:01:40 +02005200// Verify that a TurnCustomizer passed in through RTCConfiguration
5201// is actually used by the underlying TURN candidate pair.
5202// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005203TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02005204 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
5205 3478};
5206 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
5207 0};
5208 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
5209 3478};
5210 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
5211 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07005212 CreateTurnServer(turn_server_1_internal_address,
5213 turn_server_1_external_address);
5214 CreateTurnServer(turn_server_2_internal_address,
5215 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005216
5217 PeerConnectionInterface::RTCConfiguration client_1_config;
5218 webrtc::PeerConnectionInterface::IceServer ice_server_1;
5219 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
5220 ice_server_1.username = "test";
5221 ice_server_1.password = "test";
5222 client_1_config.servers.push_back(ice_server_1);
5223 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005224 auto* customizer1 = CreateTurnCustomizer();
5225 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005226
5227 PeerConnectionInterface::RTCConfiguration client_2_config;
5228 webrtc::PeerConnectionInterface::IceServer ice_server_2;
5229 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
5230 ice_server_2.username = "test";
5231 ice_server_2.password = "test";
5232 client_2_config.servers.push_back(ice_server_2);
5233 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005234 auto* customizer2 = CreateTurnCustomizer();
5235 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005236
5237 ASSERT_TRUE(
5238 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5239 ConnectFakeSignaling();
5240
5241 // Set "offer to receive audio/video" without adding any tracks, so we just
5242 // set up ICE/DTLS with no media.
5243 PeerConnectionInterface::RTCOfferAnswerOptions options;
5244 options.offer_to_receive_audio = 1;
5245 options.offer_to_receive_video = 1;
5246 caller()->SetOfferAnswerOptions(options);
5247 caller()->CreateAndSetAndSignalOffer();
5248 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5249
Seth Hampsonaed71642018-06-11 07:41:32 -07005250 ExpectTurnCustomizerCountersIncremented(customizer1);
5251 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005252}
5253
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005254// Verifies that you can use TCP instead of UDP to connect to a TURN server and
5255// send media between the caller and the callee.
5256TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
5257 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5258 3478};
5259 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5260
5261 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07005262 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5263 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005264
5265 webrtc::PeerConnectionInterface::IceServer ice_server;
5266 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
5267 ice_server.username = "test";
5268 ice_server.password = "test";
5269
5270 PeerConnectionInterface::RTCConfiguration client_1_config;
5271 client_1_config.servers.push_back(ice_server);
5272 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5273
5274 PeerConnectionInterface::RTCConfiguration client_2_config;
5275 client_2_config.servers.push_back(ice_server);
5276 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5277
5278 ASSERT_TRUE(
5279 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5280
5281 // Do normal offer/answer and wait for ICE to complete.
5282 ConnectFakeSignaling();
5283 caller()->AddAudioVideoTracks();
5284 callee()->AddAudioVideoTracks();
5285 caller()->CreateAndSetAndSignalOffer();
5286 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5287 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5288 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5289
5290 MediaExpectations media_expectations;
5291 media_expectations.ExpectBidirectionalAudioAndVideo();
5292 EXPECT_TRUE(ExpectNewFrames(media_expectations));
5293}
5294
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005295// Verify that a SSLCertificateVerifier passed in through
5296// PeerConnectionDependencies is actually used by the underlying SSL
5297// implementation to determine whether a certificate presented by the TURN
5298// server is accepted by the client. Note that openssladapter_unittest.cc
5299// contains more detailed, lower-level tests.
5300TEST_P(PeerConnectionIntegrationTest,
5301 SSLCertificateVerifierUsedForTurnConnections) {
5302 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5303 3478};
5304 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5305
5306 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5307 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005308 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5309 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005310
5311 webrtc::PeerConnectionInterface::IceServer ice_server;
5312 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5313 ice_server.username = "test";
5314 ice_server.password = "test";
5315
5316 PeerConnectionInterface::RTCConfiguration client_1_config;
5317 client_1_config.servers.push_back(ice_server);
5318 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5319
5320 PeerConnectionInterface::RTCConfiguration client_2_config;
5321 client_2_config.servers.push_back(ice_server);
5322 // Setting the type to kRelay forces the connection to go through a TURN
5323 // server.
5324 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5325
5326 // Get a copy to the pointer so we can verify calls later.
5327 rtc::TestCertificateVerifier* client_1_cert_verifier =
5328 new rtc::TestCertificateVerifier();
5329 client_1_cert_verifier->verify_certificate_ = true;
5330 rtc::TestCertificateVerifier* client_2_cert_verifier =
5331 new rtc::TestCertificateVerifier();
5332 client_2_cert_verifier->verify_certificate_ = true;
5333
5334 // Create the dependencies with the test certificate verifier.
5335 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5336 client_1_deps.tls_cert_verifier =
5337 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5338 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5339 client_2_deps.tls_cert_verifier =
5340 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5341
5342 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5343 client_1_config, std::move(client_1_deps), client_2_config,
5344 std::move(client_2_deps)));
5345 ConnectFakeSignaling();
5346
5347 // Set "offer to receive audio/video" without adding any tracks, so we just
5348 // set up ICE/DTLS with no media.
5349 PeerConnectionInterface::RTCOfferAnswerOptions options;
5350 options.offer_to_receive_audio = 1;
5351 options.offer_to_receive_video = 1;
5352 caller()->SetOfferAnswerOptions(options);
5353 caller()->CreateAndSetAndSignalOffer();
5354 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5355
5356 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5357 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005358}
5359
5360TEST_P(PeerConnectionIntegrationTest,
5361 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
5362 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5363 3478};
5364 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5365
5366 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5367 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005368 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5369 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005370
5371 webrtc::PeerConnectionInterface::IceServer ice_server;
5372 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5373 ice_server.username = "test";
5374 ice_server.password = "test";
5375
5376 PeerConnectionInterface::RTCConfiguration client_1_config;
5377 client_1_config.servers.push_back(ice_server);
5378 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5379
5380 PeerConnectionInterface::RTCConfiguration client_2_config;
5381 client_2_config.servers.push_back(ice_server);
5382 // Setting the type to kRelay forces the connection to go through a TURN
5383 // server.
5384 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5385
5386 // Get a copy to the pointer so we can verify calls later.
5387 rtc::TestCertificateVerifier* client_1_cert_verifier =
5388 new rtc::TestCertificateVerifier();
5389 client_1_cert_verifier->verify_certificate_ = false;
5390 rtc::TestCertificateVerifier* client_2_cert_verifier =
5391 new rtc::TestCertificateVerifier();
5392 client_2_cert_verifier->verify_certificate_ = false;
5393
5394 // Create the dependencies with the test certificate verifier.
5395 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5396 client_1_deps.tls_cert_verifier =
5397 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5398 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5399 client_2_deps.tls_cert_verifier =
5400 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5401
5402 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5403 client_1_config, std::move(client_1_deps), client_2_config,
5404 std::move(client_2_deps)));
5405 ConnectFakeSignaling();
5406
5407 // Set "offer to receive audio/video" without adding any tracks, so we just
5408 // set up ICE/DTLS with no media.
5409 PeerConnectionInterface::RTCOfferAnswerOptions options;
5410 options.offer_to_receive_audio = 1;
5411 options.offer_to_receive_video = 1;
5412 caller()->SetOfferAnswerOptions(options);
5413 caller()->CreateAndSetAndSignalOffer();
5414 bool wait_res = true;
5415 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
5416 // properly, should be able to just wait for a state of "failed" instead of
5417 // waiting a fixed 10 seconds.
5418 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
5419 ASSERT_FALSE(wait_res);
5420
5421 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5422 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005423}
5424
Qingsi Wang25ec8882019-11-15 12:33:05 -08005425// Test that the injected ICE transport factory is used to create ICE transports
5426// for WebRTC connections.
5427TEST_P(PeerConnectionIntegrationTest, IceTransportFactoryUsedForConnections) {
5428 PeerConnectionInterface::RTCConfiguration default_config;
5429 PeerConnectionDependencies dependencies(nullptr);
5430 auto ice_transport_factory = std::make_unique<MockIceTransportFactory>();
5431 EXPECT_CALL(*ice_transport_factory, RecordIceTransportCreated()).Times(1);
5432 dependencies.ice_transport_factory = std::move(ice_transport_factory);
Johannes Kron8e8b36a2020-02-07 14:23:45 +00005433 auto wrapper =
5434 CreatePeerConnectionWrapper("Caller", nullptr, &default_config,
5435 std::move(dependencies), nullptr, nullptr);
Qingsi Wang25ec8882019-11-15 12:33:05 -08005436 ASSERT_TRUE(wrapper);
5437 wrapper->CreateDataChannel();
5438 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5439 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5440 wrapper->pc()->SetLocalDescription(observer,
5441 wrapper->CreateOfferAndWait().release());
5442}
5443
deadbeefc964d0b2017-04-03 10:03:35 -07005444// Test that audio and video flow end-to-end when codec names don't use the
5445// expected casing, given that they're supposed to be case insensitive. To test
5446// this, all but one codec is removed from each media description, and its
5447// casing is changed.
5448//
5449// In the past, this has regressed and caused crashes/black video, due to the
5450// fact that code at some layers was doing case-insensitive comparisons and
5451// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005452TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07005453 ASSERT_TRUE(CreatePeerConnectionWrappers());
5454 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005455 caller()->AddAudioVideoTracks();
5456 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07005457
5458 // Remove all but one audio/video codec (opus and VP8), and change the
5459 // casing of the caller's generated offer.
5460 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
5461 cricket::AudioContentDescription* audio =
5462 GetFirstAudioContentDescription(description);
5463 ASSERT_NE(nullptr, audio);
5464 auto audio_codecs = audio->codecs();
5465 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
5466 [](const cricket::AudioCodec& codec) {
5467 return codec.name != "opus";
5468 }),
5469 audio_codecs.end());
5470 ASSERT_EQ(1u, audio_codecs.size());
5471 audio_codecs[0].name = "OpUs";
5472 audio->set_codecs(audio_codecs);
5473
5474 cricket::VideoContentDescription* video =
5475 GetFirstVideoContentDescription(description);
5476 ASSERT_NE(nullptr, video);
5477 auto video_codecs = video->codecs();
5478 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
5479 [](const cricket::VideoCodec& codec) {
5480 return codec.name != "VP8";
5481 }),
5482 video_codecs.end());
5483 ASSERT_EQ(1u, video_codecs.size());
5484 video_codecs[0].name = "vP8";
5485 video->set_codecs(video_codecs);
5486 });
5487
5488 caller()->CreateAndSetAndSignalOffer();
5489 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5490
5491 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005492 MediaExpectations media_expectations;
5493 media_expectations.ExpectBidirectionalAudioAndVideo();
5494 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07005495}
5496
Jonas Oreland49ac5952018-09-26 16:04:32 +02005497TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07005498 ASSERT_TRUE(CreatePeerConnectionWrappers());
5499 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005500 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07005501 caller()->CreateAndSetAndSignalOffer();
5502 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07005503 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005504 MediaExpectations media_expectations;
5505 media_expectations.CalleeExpectsSomeAudio(1);
5506 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02005507 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07005508 auto receiver = callee()->pc()->GetReceivers()[0];
5509 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005510 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07005511 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
5512 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02005513 sources[0].source_id());
5514 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
5515}
5516
5517TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
5518 ASSERT_TRUE(CreatePeerConnectionWrappers());
5519 ConnectFakeSignaling();
5520 caller()->AddVideoTrack();
5521 caller()->CreateAndSetAndSignalOffer();
5522 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5523 // Wait for one video frame to be received by the callee.
5524 MediaExpectations media_expectations;
5525 media_expectations.CalleeExpectsSomeVideo(1);
5526 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5527 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
5528 auto receiver = callee()->pc()->GetReceivers()[0];
5529 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
5530 auto sources = receiver->GetSources();
5531 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02005532 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005533 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
5534 sources[0].source_id());
5535 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07005536}
5537
deadbeef2f425aa2017-04-14 10:41:32 -07005538// Test that if a track is removed and added again with a different stream ID,
5539// the new stream ID is successfully communicated in SDP and media continues to
5540// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005541// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
5542// it will not reuse a transceiver that has already been sending. After creating
5543// a new transceiver it tries to create an offer with two senders of the same
5544// track ids and it fails.
5545TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07005546 ASSERT_TRUE(CreatePeerConnectionWrappers());
5547 ConnectFakeSignaling();
5548
deadbeef2f425aa2017-04-14 10:41:32 -07005549 // Add track using stream 1, do offer/answer.
5550 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
5551 caller()->CreateLocalAudioTrack();
5552 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07005553 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07005554 caller()->CreateAndSetAndSignalOffer();
5555 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005556 {
5557 MediaExpectations media_expectations;
5558 media_expectations.CalleeExpectsSomeAudio(1);
5559 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5560 }
deadbeef2f425aa2017-04-14 10:41:32 -07005561 // Remove the sender, and create a new one with the new stream.
5562 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07005563 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07005564 caller()->CreateAndSetAndSignalOffer();
5565 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5566 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005567 {
5568 MediaExpectations media_expectations;
5569 media_expectations.CalleeExpectsSomeAudio();
5570 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5571 }
deadbeef2f425aa2017-04-14 10:41:32 -07005572}
5573
Seth Hampson2f0d7022018-02-20 11:54:42 -08005574TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02005575 ASSERT_TRUE(CreatePeerConnectionWrappers());
5576 ConnectFakeSignaling();
5577
Mirko Bonadei317a1f02019-09-17 17:06:18 +02005578 auto output = std::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005579 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
5580 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02005581 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01005582 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
5583 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02005584
Steve Anton15324772018-01-16 10:26:49 -08005585 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02005586 caller()->CreateAndSetAndSignalOffer();
5587 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5588}
5589
Steve Antonede9ca52017-10-16 13:04:27 -07005590// Test that if candidates are only signaled by applying full session
5591// descriptions (instead of using AddIceCandidate), the peers can connect to
5592// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005593TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07005594 ASSERT_TRUE(CreatePeerConnectionWrappers());
5595 // Each side will signal the session descriptions but not candidates.
5596 ConnectFakeSignalingForSdpOnly();
5597
5598 // Add audio video track and exchange the initial offer/answer with media
5599 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08005600 caller()->AddAudioVideoTracks();
5601 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07005602 caller()->CreateAndSetAndSignalOffer();
5603
5604 // Wait for all candidates to be gathered on both the caller and callee.
5605 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5606 caller()->ice_gathering_state(), kDefaultTimeout);
5607 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5608 callee()->ice_gathering_state(), kDefaultTimeout);
5609
5610 // The candidates will now be included in the session description, so
5611 // signaling them will start the ICE connection.
5612 caller()->CreateAndSetAndSignalOffer();
5613 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5614
5615 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005616 MediaExpectations media_expectations;
5617 media_expectations.ExpectBidirectionalAudioAndVideo();
5618 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07005619}
5620
henrika5f6bf242017-11-01 11:06:56 +01005621// Test that SetAudioPlayout can be used to disable audio playout from the
5622// start, then later enable it. This may be useful, for example, if the caller
5623// needs to play a local ringtone until some event occurs, after which it
5624// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005625TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01005626 ASSERT_TRUE(CreatePeerConnectionWrappers());
5627 ConnectFakeSignaling();
5628
5629 // Set up audio-only call where audio playout is disabled on caller's side.
5630 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08005631 caller()->AddAudioTrack();
5632 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005633 caller()->CreateAndSetAndSignalOffer();
5634 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5635
5636 // Pump messages for a second.
5637 WAIT(false, 1000);
5638 // Since audio playout is disabled, the caller shouldn't have received
5639 // anything (at the playout level, at least).
5640 EXPECT_EQ(0, caller()->audio_frames_received());
5641 // As a sanity check, make sure the callee (for which playout isn't disabled)
5642 // did still see frames on its audio level.
5643 ASSERT_GT(callee()->audio_frames_received(), 0);
5644
5645 // Enable playout again, and ensure audio starts flowing.
5646 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005647 MediaExpectations media_expectations;
5648 media_expectations.ExpectBidirectionalAudio();
5649 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01005650}
5651
5652double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5653 auto report = pc->NewGetStats();
5654 auto track_stats_list =
5655 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5656 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5657 for (const auto* track_stats : track_stats_list) {
5658 if (track_stats->remote_source.is_defined() &&
5659 *track_stats->remote_source) {
5660 remote_track_stats = track_stats;
5661 break;
5662 }
5663 }
5664
5665 if (!remote_track_stats->total_audio_energy.is_defined()) {
5666 return 0.0;
5667 }
5668 return *remote_track_stats->total_audio_energy;
5669}
5670
5671// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5672// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005673TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005674 DisableAudioPlayoutStillGeneratesAudioStats) {
5675 ASSERT_TRUE(CreatePeerConnectionWrappers());
5676 ConnectFakeSignaling();
5677
5678 // Set up audio-only call where playout is disabled but audio-processing is
5679 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005680 caller()->AddAudioTrack();
5681 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005682 caller()->pc()->SetAudioPlayout(false);
5683
5684 caller()->CreateAndSetAndSignalOffer();
5685 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5686
5687 // Wait for the callee to receive audio stats.
5688 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5689}
5690
henrika4f167df2017-11-01 14:45:55 +01005691// Test that SetAudioRecording can be used to disable audio recording from the
5692// start, then later enable it. This may be useful, for example, if the caller
5693// wants to ensure that no audio resources are active before a certain state
5694// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005695TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005696 ASSERT_TRUE(CreatePeerConnectionWrappers());
5697 ConnectFakeSignaling();
5698
5699 // Set up audio-only call where audio recording is disabled on caller's side.
5700 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005701 caller()->AddAudioTrack();
5702 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005703 caller()->CreateAndSetAndSignalOffer();
5704 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5705
5706 // Pump messages for a second.
5707 WAIT(false, 1000);
5708 // Since caller has disabled audio recording, the callee shouldn't have
5709 // received anything.
5710 EXPECT_EQ(0, callee()->audio_frames_received());
5711 // As a sanity check, make sure the caller did still see frames on its
5712 // audio level since audio recording is enabled on the calle side.
5713 ASSERT_GT(caller()->audio_frames_received(), 0);
5714
5715 // Enable audio recording again, and ensure audio starts flowing.
5716 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005717 MediaExpectations media_expectations;
5718 media_expectations.ExpectBidirectionalAudio();
5719 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005720}
5721
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005722// Test that after closing PeerConnections, they stop sending any packets (ICE,
5723// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005724TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005725 // Set up audio/video/data, wait for some frames to be received.
5726 ASSERT_TRUE(CreatePeerConnectionWrappers());
5727 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005728 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005729#ifdef HAVE_SCTP
5730 caller()->CreateDataChannel();
5731#endif
5732 caller()->CreateAndSetAndSignalOffer();
5733 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005734 MediaExpectations media_expectations;
5735 media_expectations.CalleeExpectsSomeAudioAndVideo();
5736 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005737 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005738 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005739 // Pump messages for a second, and ensure no new packets end up sent.
5740 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5741 WAIT(false, 1000);
5742 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5743 EXPECT_EQ(sent_packets_a, sent_packets_b);
5744}
5745
Steve Anton7eca0932018-03-30 15:18:41 -07005746// Test that transport stats are generated by the RTCStatsCollector for a
5747// connection that only involves data channels. This is a regression test for
5748// crbug.com/826972.
5749#ifdef HAVE_SCTP
5750TEST_P(PeerConnectionIntegrationTest,
5751 TransportStatsReportedForDataChannelOnlyConnection) {
5752 ASSERT_TRUE(CreatePeerConnectionWrappers());
5753 ConnectFakeSignaling();
5754 caller()->CreateDataChannel();
5755
5756 caller()->CreateAndSetAndSignalOffer();
5757 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5758 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5759
5760 auto caller_report = caller()->NewGetStats();
5761 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5762 auto callee_report = callee()->NewGetStats();
5763 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5764}
5765#endif // HAVE_SCTP
5766
Qingsi Wang7685e862018-06-11 20:15:46 -07005767TEST_P(PeerConnectionIntegrationTest,
5768 IceEventsGeneratedAndLoggedInRtcEventLog) {
5769 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5770 ConnectFakeSignaling();
5771 PeerConnectionInterface::RTCOfferAnswerOptions options;
5772 options.offer_to_receive_audio = 1;
5773 caller()->SetOfferAnswerOptions(options);
5774 caller()->CreateAndSetAndSignalOffer();
5775 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5776 ASSERT_NE(nullptr, caller()->event_log_factory());
5777 ASSERT_NE(nullptr, callee()->event_log_factory());
5778 webrtc::FakeRtcEventLog* caller_event_log =
5779 static_cast<webrtc::FakeRtcEventLog*>(
5780 caller()->event_log_factory()->last_log_created());
5781 webrtc::FakeRtcEventLog* callee_event_log =
5782 static_cast<webrtc::FakeRtcEventLog*>(
5783 callee()->event_log_factory()->last_log_created());
5784 ASSERT_NE(nullptr, caller_event_log);
5785 ASSERT_NE(nullptr, callee_event_log);
5786 int caller_ice_config_count = caller_event_log->GetEventCount(
5787 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5788 int caller_ice_event_count = caller_event_log->GetEventCount(
5789 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5790 int callee_ice_config_count = callee_event_log->GetEventCount(
5791 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5792 int callee_ice_event_count = callee_event_log->GetEventCount(
5793 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5794 EXPECT_LT(0, caller_ice_config_count);
5795 EXPECT_LT(0, caller_ice_event_count);
5796 EXPECT_LT(0, callee_ice_config_count);
5797 EXPECT_LT(0, callee_ice_event_count);
5798}
5799
Qingsi Wangc129c352019-04-18 10:41:58 -07005800TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005801 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5802 3478};
5803 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5804
5805 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5806
5807 webrtc::PeerConnectionInterface::IceServer ice_server;
5808 ice_server.urls.push_back("turn:88.88.88.0:3478");
5809 ice_server.username = "test";
5810 ice_server.password = "test";
5811
5812 PeerConnectionInterface::RTCConfiguration caller_config;
5813 caller_config.servers.push_back(ice_server);
5814 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5815 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005816 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005817
5818 PeerConnectionInterface::RTCConfiguration callee_config;
5819 callee_config.servers.push_back(ice_server);
5820 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5821 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005822 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005823
5824 ASSERT_TRUE(
5825 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5826
5827 // Do normal offer/answer and wait for ICE to complete.
5828 ConnectFakeSignaling();
5829 caller()->AddAudioVideoTracks();
5830 callee()->AddAudioVideoTracks();
5831 caller()->CreateAndSetAndSignalOffer();
5832 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5833 // Since we are doing continual gathering, the ICE transport does not reach
5834 // kIceGatheringComplete (see
5835 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5836 // kIceConnectionComplete.
5837 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5838 caller()->ice_connection_state(), kDefaultTimeout);
5839 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5840 callee()->ice_connection_state(), kDefaultTimeout);
5841 // Note that we cannot use the metric
5842 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5843 // metric is only populated when we reach kIceConnectionComplete in the
5844 // current implementation.
5845 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5846 caller()->last_candidate_gathered().type());
5847 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5848 callee()->last_candidate_gathered().type());
5849
5850 // Loosen the caller's candidate filter.
5851 caller_config = caller()->pc()->GetConfiguration();
5852 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5853 caller()->pc()->SetConfiguration(caller_config);
5854 // We should have gathered a new host candidate.
5855 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5856 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5857
5858 // Loosen the callee's candidate filter.
5859 callee_config = callee()->pc()->GetConfiguration();
5860 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5861 callee()->pc()->SetConfiguration(callee_config);
5862 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5863 callee()->last_candidate_gathered().type(), kDefaultTimeout);
5864}
5865
Eldar Relloda13ea22019-06-01 12:23:43 +03005866TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03005867 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5868 3478};
5869 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5870
5871 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5872
5873 webrtc::PeerConnectionInterface::IceServer ice_server;
5874 ice_server.urls.push_back("turn:88.88.88.0:3478");
5875 ice_server.username = "test";
5876 ice_server.password = "123";
5877
5878 PeerConnectionInterface::RTCConfiguration caller_config;
5879 caller_config.servers.push_back(ice_server);
5880 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5881 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5882
5883 PeerConnectionInterface::RTCConfiguration callee_config;
5884 callee_config.servers.push_back(ice_server);
5885 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5886 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5887
5888 ASSERT_TRUE(
5889 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5890
5891 // Do normal offer/answer and wait for ICE to complete.
5892 ConnectFakeSignaling();
5893 caller()->AddAudioVideoTracks();
5894 callee()->AddAudioVideoTracks();
5895 caller()->CreateAndSetAndSignalOffer();
5896 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5897 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5898 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5899 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
Eldar Rello0095d372019-12-02 22:22:07 +02005900 EXPECT_NE(caller()->error_event().address, "");
Eldar Relloda13ea22019-06-01 12:23:43 +03005901}
5902
Eldar Rello5ab79e62019-10-09 18:29:44 +03005903TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5904 AudioKeepsFlowingAfterImplicitRollback) {
5905 PeerConnectionInterface::RTCConfiguration config;
5906 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5907 config.enable_implicit_rollback = true;
5908 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5909 ConnectFakeSignaling();
5910 caller()->AddAudioTrack();
5911 callee()->AddAudioTrack();
5912 caller()->CreateAndSetAndSignalOffer();
5913 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5914 MediaExpectations media_expectations;
5915 media_expectations.ExpectBidirectionalAudio();
5916 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5917 SetSignalIceCandidates(false); // Workaround candidate outrace sdp.
5918 caller()->AddVideoTrack();
5919 callee()->AddVideoTrack();
5920 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5921 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5922 callee()->pc()->SetLocalDescription(observer,
5923 callee()->CreateOfferAndWait().release());
5924 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
5925 caller()->CreateAndSetAndSignalOffer(); // Implicit rollback.
5926 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5927 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5928}
5929
5930TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5931 ImplicitRollbackVisitsStableState) {
5932 RTCConfiguration config;
5933 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5934 config.enable_implicit_rollback = true;
5935
5936 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5937
5938 rtc::scoped_refptr<MockSetSessionDescriptionObserver> sld_observer(
5939 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5940 callee()->pc()->SetLocalDescription(sld_observer,
5941 callee()->CreateOfferAndWait().release());
5942 EXPECT_TRUE_WAIT(sld_observer->called(), kDefaultTimeout);
5943 EXPECT_EQ(sld_observer->error(), "");
5944
5945 rtc::scoped_refptr<MockSetSessionDescriptionObserver> srd_observer(
5946 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5947 callee()->pc()->SetRemoteDescription(
5948 srd_observer, caller()->CreateOfferAndWait().release());
5949 EXPECT_TRUE_WAIT(srd_observer->called(), kDefaultTimeout);
5950 EXPECT_EQ(srd_observer->error(), "");
5951
5952 EXPECT_THAT(callee()->peer_connection_signaling_state_history(),
5953 ElementsAre(PeerConnectionInterface::kHaveLocalOffer,
5954 PeerConnectionInterface::kStable,
5955 PeerConnectionInterface::kHaveRemoteOffer));
5956}
5957
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005958INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5959 PeerConnectionIntegrationTest,
5960 Values(SdpSemantics::kPlanB,
5961 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005962
Yves Gerey100fe632020-01-17 19:15:53 +01005963INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5964 PeerConnectionIntegrationTestWithFakeClock,
5965 Values(SdpSemantics::kPlanB,
5966 SdpSemantics::kUnifiedPlan));
5967
Steve Anton74255ff2018-01-24 18:32:57 -08005968// Tests that verify interoperability between Plan B and Unified Plan
5969// PeerConnections.
5970class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08005971 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08005972 public ::testing::WithParamInterface<
5973 std::tuple<SdpSemantics, SdpSemantics>> {
5974 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08005975 // Setting the SdpSemantics for the base test to kDefault does not matter
5976 // because we specify not to use the test semantics when creating
5977 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08005978 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07005979 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08005980 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08005981 callee_semantics_(std::get<1>(GetParam())) {}
5982
5983 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07005984 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5985 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08005986 }
5987
5988 const SdpSemantics caller_semantics_;
5989 const SdpSemantics callee_semantics_;
5990};
5991
5992TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5993 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5994 ConnectFakeSignaling();
5995
5996 caller()->CreateAndSetAndSignalOffer();
5997 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5998}
5999
6000TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
6001 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6002 ConnectFakeSignaling();
6003 auto audio_sender = caller()->AddAudioTrack();
6004
6005 caller()->CreateAndSetAndSignalOffer();
6006 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6007
6008 // Verify that one audio receiver has been created on the remote and that it
6009 // has the same track ID as the sending track.
6010 auto receivers = callee()->pc()->GetReceivers();
6011 ASSERT_EQ(1u, receivers.size());
6012 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
6013 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
6014
Seth Hampson2f0d7022018-02-20 11:54:42 -08006015 MediaExpectations media_expectations;
6016 media_expectations.CalleeExpectsSomeAudio();
6017 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006018}
6019
6020TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
6021 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6022 ConnectFakeSignaling();
6023 auto video_sender = caller()->AddVideoTrack();
6024 auto audio_sender = caller()->AddAudioTrack();
6025
6026 caller()->CreateAndSetAndSignalOffer();
6027 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6028
6029 // Verify that one audio and one video receiver have been created on the
6030 // remote and that they have the same track IDs as the sending tracks.
6031 auto audio_receivers =
6032 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
6033 ASSERT_EQ(1u, audio_receivers.size());
6034 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
6035 auto video_receivers =
6036 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
6037 ASSERT_EQ(1u, video_receivers.size());
6038 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
6039
Seth Hampson2f0d7022018-02-20 11:54:42 -08006040 MediaExpectations media_expectations;
6041 media_expectations.CalleeExpectsSomeAudioAndVideo();
6042 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006043}
6044
6045TEST_P(PeerConnectionIntegrationInteropTest,
6046 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
6047 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6048 ConnectFakeSignaling();
6049 caller()->AddAudioVideoTracks();
6050 callee()->AddAudioVideoTracks();
6051
6052 caller()->CreateAndSetAndSignalOffer();
6053 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6054
Seth Hampson2f0d7022018-02-20 11:54:42 -08006055 MediaExpectations media_expectations;
6056 media_expectations.ExpectBidirectionalAudioAndVideo();
6057 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006058}
6059
6060TEST_P(PeerConnectionIntegrationInteropTest,
6061 ReverseRolesOneAudioLocalToOneVideoRemote) {
6062 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
6063 ConnectFakeSignaling();
6064 caller()->AddAudioTrack();
6065 callee()->AddVideoTrack();
6066
6067 caller()->CreateAndSetAndSignalOffer();
6068 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6069
6070 // Verify that only the audio track has been negotiated.
6071 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
6072 // Might also check that the callee's NegotiationNeeded flag is set.
6073
6074 // Reverse roles.
6075 callee()->CreateAndSetAndSignalOffer();
6076 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6077
Seth Hampson2f0d7022018-02-20 11:54:42 -08006078 MediaExpectations media_expectations;
6079 media_expectations.CallerExpectsSomeVideo();
6080 media_expectations.CalleeExpectsSomeAudio();
6081 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006082}
6083
Mirko Bonadeic84f6612019-01-31 12:20:57 +01006084INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07006085 PeerConnectionIntegrationTest,
6086 PeerConnectionIntegrationInteropTest,
6087 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
6088 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
6089
6090// Test that if the Unified Plan side offers two video tracks then the Plan B
6091// side will only see the first one and ignore the second.
6092TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07006093 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
6094 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08006095 ConnectFakeSignaling();
6096 auto first_sender = caller()->AddVideoTrack();
6097 caller()->AddVideoTrack();
6098
6099 caller()->CreateAndSetAndSignalOffer();
6100 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6101
6102 // Verify that there is only one receiver and it corresponds to the first
6103 // added track.
6104 auto receivers = callee()->pc()->GetReceivers();
6105 ASSERT_EQ(1u, receivers.size());
6106 EXPECT_TRUE(receivers[0]->track()->enabled());
6107 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
6108
Seth Hampson2f0d7022018-02-20 11:54:42 -08006109 MediaExpectations media_expectations;
6110 media_expectations.CalleeExpectsSomeVideo();
6111 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08006112}
6113
Steve Anton2bed3972019-01-04 17:04:30 -08006114// Test that if the initial offer tagged BUNDLE section is rejected due to its
6115// associated RtpTransceiver being stopped and another transceiver is added,
6116// then renegotiation causes the callee to receive the new video track without
6117// error.
6118// This is a regression test for bugs.webrtc.org/9954
6119TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6120 ReOfferWithStoppedBundleTaggedTransceiver) {
6121 RTCConfiguration config;
6122 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
6123 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
6124 ConnectFakeSignaling();
6125 auto audio_transceiver_or_error =
6126 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
6127 ASSERT_TRUE(audio_transceiver_or_error.ok());
6128 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
6129
6130 caller()->CreateAndSetAndSignalOffer();
6131 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6132 {
6133 MediaExpectations media_expectations;
6134 media_expectations.CalleeExpectsSomeAudio();
6135 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6136 }
6137
6138 audio_transceiver->Stop();
6139 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
6140
6141 caller()->CreateAndSetAndSignalOffer();
6142 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6143 {
6144 MediaExpectations media_expectations;
6145 media_expectations.CalleeExpectsSomeVideo();
6146 ASSERT_TRUE(ExpectNewFrames(media_expectations));
6147 }
6148}
6149
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006150#ifdef HAVE_SCTP
6151
6152TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6153 EndToEndCallWithBundledSctpDataChannel) {
6154 ASSERT_TRUE(CreatePeerConnectionWrappers());
6155 ConnectFakeSignaling();
6156 caller()->CreateDataChannel();
6157 caller()->AddAudioVideoTracks();
6158 callee()->AddAudioVideoTracks();
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006159 caller()->CreateAndSetAndSignalOffer();
6160 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01006161 ASSERT_EQ_WAIT(SctpTransportState::kConnected,
6162 caller()->pc()->GetSctpTransport()->Information().state(),
6163 kDefaultTimeout);
6164 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
6165 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6166}
6167
6168TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6169 EndToEndCallWithDataChannelOnlyConnects) {
6170 ASSERT_TRUE(CreatePeerConnectionWrappers());
6171 ConnectFakeSignaling();
6172 caller()->CreateDataChannel();
6173 caller()->CreateAndSetAndSignalOffer();
6174 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6175 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
6176 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6177 ASSERT_TRUE(caller()->data_observer()->IsOpen());
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006178}
6179
Harald Alvestrand2697ac12019-12-16 10:37:04 +01006180TEST_F(PeerConnectionIntegrationTestUnifiedPlan, DataChannelClosesWhenClosed) {
6181 ASSERT_TRUE(CreatePeerConnectionWrappers());
6182 ConnectFakeSignaling();
6183 caller()->CreateDataChannel();
6184 caller()->CreateAndSetAndSignalOffer();
6185 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6186 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6187 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6188 caller()->data_channel()->Close();
6189 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
6190}
6191
6192TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6193 DataChannelClosesWhenClosedReverse) {
6194 ASSERT_TRUE(CreatePeerConnectionWrappers());
6195 ConnectFakeSignaling();
6196 caller()->CreateDataChannel();
6197 caller()->CreateAndSetAndSignalOffer();
6198 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6199 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6200 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6201 callee()->data_channel()->Close();
6202 ASSERT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
6203}
6204
6205TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
6206 DataChannelClosesWhenPeerConnectionClosed) {
6207 ASSERT_TRUE(CreatePeerConnectionWrappers());
6208 ConnectFakeSignaling();
6209 caller()->CreateDataChannel();
6210 caller()->CreateAndSetAndSignalOffer();
6211 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
6212 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
6213 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
6214 caller()->pc()->Close();
6215 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
6216}
6217
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02006218#endif // HAVE_SCTP
6219
deadbeef1dcb1642017-03-29 21:08:16 -07006220} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01006221} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07006222
6223#endif // if !defined(THREAD_SANITIZER)