blob: dd06b65ffafd8f60c6c14f84df4d806c9ed0eed4 [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,
217 /*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,
607 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 Relloda13ea22019-06-01 12:23:43 +0300980 void OnIceCandidateError(const std::string& host_candidate,
981 const std::string& url,
982 int error_code,
983 const std::string& error_text) override {
984 error_event_ = cricket::IceCandidateErrorEvent(host_candidate, url,
985 error_code, error_text);
986 }
deadbeef1dcb1642017-03-29 21:08:16 -0700987 void OnDataChannel(
988 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100989 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700990 data_channel_ = data_channel;
991 data_observer_.reset(new MockDataChannelObserver(data_channel));
992 }
993
deadbeef1dcb1642017-03-29 21:08:16 -0700994 std::string debug_name_;
995
996 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -0700997 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
998 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -0700999
1000 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
1001 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
1002 peer_connection_factory_;
1003
Steve Antonede9ca52017-10-16 13:04:27 -07001004 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -07001005 // Needed to keep track of number of frames sent.
1006 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1007 // Needed to keep track of number of frames received.
1008 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1009 fake_video_renderers_;
1010 // Needed to ensure frames aren't received for removed tracks.
1011 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1012 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001013
1014 // For remote peer communication.
1015 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1016 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001017 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001018 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001019 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001020
Niels Möller5c7efe72018-05-11 10:34:46 +02001021 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001022 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001023 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1024 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001025 // |local_video_renderer_| attached to the first created local video track.
1026 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1027
Seth Hampson2f0d7022018-02-20 11:54:42 -08001028 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001029 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1030 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1031 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001032 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001033 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001034 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1035 std::unique_ptr<MockDataChannelObserver> data_observer_;
1036
1037 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1038
Steve Antonede9ca52017-10-16 13:04:27 -07001039 std::vector<PeerConnectionInterface::IceConnectionState>
1040 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001041 std::vector<PeerConnectionInterface::IceConnectionState>
1042 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001043 std::vector<PeerConnectionInterface::PeerConnectionState>
1044 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001045 std::vector<PeerConnectionInterface::IceGatheringState>
1046 ice_gathering_state_history_;
Alex Drake00c7ecf2019-08-06 10:54:47 -07001047 std::vector<cricket::CandidatePairChangeEvent>
1048 ice_candidate_pair_change_history_;
Eldar Rello5ab79e62019-10-09 18:29:44 +03001049 std::vector<PeerConnectionInterface::SignalingState>
1050 peer_connection_signaling_state_history_;
Qingsi Wang7685e862018-06-11 20:15:46 -07001051 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1052
deadbeef1dcb1642017-03-29 21:08:16 -07001053 rtc::AsyncInvoker invoker_;
1054
Seth Hampson2f0d7022018-02-20 11:54:42 -08001055 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001056};
1057
Elad Alon99c3fe52017-10-13 16:29:40 +02001058class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1059 public:
1060 virtual ~MockRtcEventLogOutput() = default;
1061 MOCK_CONST_METHOD0(IsActive, bool());
1062 MOCK_METHOD1(Write, bool(const std::string&));
1063};
1064
Seth Hampson2f0d7022018-02-20 11:54:42 -08001065// This helper object is used for both specifying how many audio/video frames
1066// are expected to be received for a caller/callee. It provides helper functions
1067// to specify these expectations. The object initially starts in a state of no
1068// expectations.
1069class MediaExpectations {
1070 public:
1071 enum ExpectFrames {
1072 kExpectSomeFrames,
1073 kExpectNoFrames,
1074 kNoExpectation,
1075 };
1076
1077 void ExpectBidirectionalAudioAndVideo() {
1078 ExpectBidirectionalAudio();
1079 ExpectBidirectionalVideo();
1080 }
1081
1082 void ExpectBidirectionalAudio() {
1083 CallerExpectsSomeAudio();
1084 CalleeExpectsSomeAudio();
1085 }
1086
1087 void ExpectNoAudio() {
1088 CallerExpectsNoAudio();
1089 CalleeExpectsNoAudio();
1090 }
1091
1092 void ExpectBidirectionalVideo() {
1093 CallerExpectsSomeVideo();
1094 CalleeExpectsSomeVideo();
1095 }
1096
1097 void ExpectNoVideo() {
1098 CallerExpectsNoVideo();
1099 CalleeExpectsNoVideo();
1100 }
1101
1102 void CallerExpectsSomeAudioAndVideo() {
1103 CallerExpectsSomeAudio();
1104 CallerExpectsSomeVideo();
1105 }
1106
1107 void CalleeExpectsSomeAudioAndVideo() {
1108 CalleeExpectsSomeAudio();
1109 CalleeExpectsSomeVideo();
1110 }
1111
1112 // Caller's audio functions.
1113 void CallerExpectsSomeAudio(
1114 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1115 caller_audio_expectation_ = kExpectSomeFrames;
1116 caller_audio_frames_expected_ = expected_audio_frames;
1117 }
1118
1119 void CallerExpectsNoAudio() {
1120 caller_audio_expectation_ = kExpectNoFrames;
1121 caller_audio_frames_expected_ = 0;
1122 }
1123
1124 // Caller's video functions.
1125 void CallerExpectsSomeVideo(
1126 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1127 caller_video_expectation_ = kExpectSomeFrames;
1128 caller_video_frames_expected_ = expected_video_frames;
1129 }
1130
1131 void CallerExpectsNoVideo() {
1132 caller_video_expectation_ = kExpectNoFrames;
1133 caller_video_frames_expected_ = 0;
1134 }
1135
1136 // Callee's audio functions.
1137 void CalleeExpectsSomeAudio(
1138 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1139 callee_audio_expectation_ = kExpectSomeFrames;
1140 callee_audio_frames_expected_ = expected_audio_frames;
1141 }
1142
1143 void CalleeExpectsNoAudio() {
1144 callee_audio_expectation_ = kExpectNoFrames;
1145 callee_audio_frames_expected_ = 0;
1146 }
1147
1148 // Callee's video functions.
1149 void CalleeExpectsSomeVideo(
1150 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1151 callee_video_expectation_ = kExpectSomeFrames;
1152 callee_video_frames_expected_ = expected_video_frames;
1153 }
1154
1155 void CalleeExpectsNoVideo() {
1156 callee_video_expectation_ = kExpectNoFrames;
1157 callee_video_frames_expected_ = 0;
1158 }
1159
1160 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1161 ExpectFrames caller_video_expectation_ = kNoExpectation;
1162 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1163 ExpectFrames callee_video_expectation_ = kNoExpectation;
1164 int caller_audio_frames_expected_ = 0;
1165 int caller_video_frames_expected_ = 0;
1166 int callee_audio_frames_expected_ = 0;
1167 int callee_video_frames_expected_ = 0;
1168};
1169
Qingsi Wang25ec8882019-11-15 12:33:05 -08001170class MockIceTransport : public webrtc::IceTransportInterface {
1171 public:
1172 MockIceTransport(const std::string& name, int component)
1173 : internal_(std::make_unique<cricket::FakeIceTransport>(
1174 name,
1175 component,
1176 nullptr /* network_thread */)) {}
1177 ~MockIceTransport() = default;
1178 cricket::IceTransportInternal* internal() { return internal_.get(); }
1179
1180 private:
1181 std::unique_ptr<cricket::FakeIceTransport> internal_;
1182};
1183
1184class MockIceTransportFactory : public IceTransportFactory {
1185 public:
1186 ~MockIceTransportFactory() override = default;
1187 rtc::scoped_refptr<IceTransportInterface> CreateIceTransport(
1188 const std::string& transport_name,
1189 int component,
1190 IceTransportInit init) {
1191 RecordIceTransportCreated();
1192 return new rtc::RefCountedObject<MockIceTransport>(transport_name,
1193 component);
1194 }
1195 MOCK_METHOD0(RecordIceTransportCreated, void());
1196};
1197
deadbeef1dcb1642017-03-29 21:08:16 -07001198// Tests two PeerConnections connecting to each other end-to-end, using a
1199// virtual network, fake A/V capture and fake encoder/decoders. The
1200// PeerConnections share the threads/socket servers, but use separate versions
1201// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001202class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001203 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001204 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1205 : sdp_semantics_(sdp_semantics),
1206 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001207 fss_(new rtc::FirewallSocketServer(ss_.get())),
1208 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001209 worker_thread_(rtc::Thread::Create()),
1210 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001211 network_thread_->SetName("PCNetworkThread", this);
1212 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001213 RTC_CHECK(network_thread_->Start());
1214 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001215 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001216 }
1217
Seth Hampson2f0d7022018-02-20 11:54:42 -08001218 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001219 // The PeerConnections should deleted before the TurnCustomizers.
1220 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1221 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1222 // that the TurnCustomizer outlives the life of the PeerConnection or else
1223 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001224 if (caller_) {
1225 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001226 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001227 }
1228 if (callee_) {
1229 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001230 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001231 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001232
1233 // If turn servers were created for the test they need to be destroyed on
1234 // the network thread.
1235 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1236 turn_servers_.clear();
1237 turn_customizers_.clear();
1238 });
deadbeef1dcb1642017-03-29 21:08:16 -07001239 }
1240
1241 bool SignalingStateStable() {
1242 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1243 }
1244
deadbeef71452802017-05-07 17:21:01 -07001245 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001246 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1247 // are connected. This is an important distinction. Once we have separate
1248 // ICE and DTLS state, this check needs to use the DTLS state.
1249 return (callee()->ice_connection_state() ==
1250 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1251 callee()->ice_connection_state() ==
1252 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1253 (caller()->ice_connection_state() ==
1254 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1255 caller()->ice_connection_state() ==
1256 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001257 }
1258
Qingsi Wang7685e862018-06-11 20:15:46 -07001259 // When |event_log_factory| is null, the default implementation of the event
1260 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001261 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1262 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001263 const PeerConnectionFactory::Options* options,
1264 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001265 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001266 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1267 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001268 RTCConfiguration modified_config;
1269 if (config) {
1270 modified_config = *config;
1271 }
Steve Anton3acffc32018-04-12 17:21:03 -07001272 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001273 if (!dependencies.cert_generator) {
1274 dependencies.cert_generator =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001275 std::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001276 }
1277 std::unique_ptr<PeerConnectionWrapper> client(
1278 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001279
Niels Möllerf06f9232018-08-07 12:32:18 +02001280 if (!client->Init(options, &modified_config, std::move(dependencies),
1281 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001282 std::move(event_log_factory),
1283 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001284 return nullptr;
1285 }
1286 return client;
1287 }
1288
Qingsi Wang7685e862018-06-11 20:15:46 -07001289 std::unique_ptr<PeerConnectionWrapper>
1290 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1291 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001292 const PeerConnectionFactory::Options* options,
1293 const RTCConfiguration* config,
1294 webrtc::PeerConnectionDependencies dependencies) {
1295 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1296 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001297 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001298 std::move(dependencies),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001299 std::move(event_log_factory),
1300 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001301 }
1302
deadbeef1dcb1642017-03-29 21:08:16 -07001303 bool CreatePeerConnectionWrappers() {
1304 return CreatePeerConnectionWrappersWithConfig(
1305 PeerConnectionInterface::RTCConfiguration(),
1306 PeerConnectionInterface::RTCConfiguration());
1307 }
1308
Steve Anton3acffc32018-04-12 17:21:03 -07001309 bool CreatePeerConnectionWrappersWithSdpSemantics(
1310 SdpSemantics caller_semantics,
1311 SdpSemantics callee_semantics) {
1312 // Can't specify the sdp_semantics in the passed-in configuration since it
1313 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1314 // stored in sdp_semantics_. So get around this by modifying the instance
1315 // variable before calling CreatePeerConnectionWrapper for the caller and
1316 // callee PeerConnections.
1317 SdpSemantics original_semantics = sdp_semantics_;
1318 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001319 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001320 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001321 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001322 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001323 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001324 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001325 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001326 sdp_semantics_ = original_semantics;
1327 return caller_ && callee_;
1328 }
1329
deadbeef1dcb1642017-03-29 21:08:16 -07001330 bool CreatePeerConnectionWrappersWithConfig(
1331 const PeerConnectionInterface::RTCConfiguration& caller_config,
1332 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001333 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001334 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001335 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1336 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001337 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001338 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001339 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1340 /*media_transport_factory=*/nullptr);
1341 return caller_ && callee_;
1342 }
1343
1344 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1345 const PeerConnectionInterface::RTCConfiguration& caller_config,
1346 const PeerConnectionInterface::RTCConfiguration& callee_config,
1347 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1348 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
1349 caller_ =
1350 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1351 webrtc::PeerConnectionDependencies(nullptr),
1352 nullptr, std::move(caller_factory));
1353 callee_ =
1354 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1355 webrtc::PeerConnectionDependencies(nullptr),
1356 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001357 return caller_ && callee_;
1358 }
1359
1360 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1361 const PeerConnectionInterface::RTCConfiguration& caller_config,
1362 webrtc::PeerConnectionDependencies caller_dependencies,
1363 const PeerConnectionInterface::RTCConfiguration& callee_config,
1364 webrtc::PeerConnectionDependencies callee_dependencies) {
1365 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001366 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001367 std::move(caller_dependencies), nullptr,
1368 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001369 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001370 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001371 std::move(callee_dependencies), nullptr,
1372 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001373 return caller_ && callee_;
1374 }
1375
1376 bool CreatePeerConnectionWrappersWithOptions(
1377 const PeerConnectionFactory::Options& caller_options,
1378 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001379 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001380 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001381 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1382 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001383 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001384 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001385 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1386 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001387 return caller_ && callee_;
1388 }
1389
1390 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1391 PeerConnectionInterface::RTCConfiguration default_config;
1392 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001393 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001394 webrtc::PeerConnectionDependencies(nullptr));
1395 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001396 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001397 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001398 return caller_ && callee_;
1399 }
1400
Seth Hampson2f0d7022018-02-20 11:54:42 -08001401 std::unique_ptr<PeerConnectionWrapper>
1402 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001403 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1404 new FakeRTCCertificateGenerator());
1405 cert_generator->use_alternate_key();
1406
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001407 webrtc::PeerConnectionDependencies dependencies(nullptr);
1408 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001409 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001410 std::move(dependencies), nullptr,
1411 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001412 }
1413
Seth Hampsonaed71642018-06-11 07:41:32 -07001414 cricket::TestTurnServer* CreateTurnServer(
1415 rtc::SocketAddress internal_address,
1416 rtc::SocketAddress external_address,
1417 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1418 const std::string& common_name = "test turn server") {
1419 rtc::Thread* thread = network_thread();
1420 std::unique_ptr<cricket::TestTurnServer> turn_server =
1421 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1422 RTC_FROM_HERE,
1423 [thread, internal_address, external_address, type, common_name] {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001424 return std::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001425 thread, internal_address, external_address, type,
1426 /*ignore_bad_certs=*/true, common_name);
1427 });
1428 turn_servers_.push_back(std::move(turn_server));
1429 // Interactions with the turn server should be done on the network thread.
1430 return turn_servers_.back().get();
1431 }
1432
1433 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1434 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1435 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1436 RTC_FROM_HERE,
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001437 [] { return std::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001438 turn_customizers_.push_back(std::move(turn_customizer));
1439 // Interactions with the turn customizer should be done on the network
1440 // thread.
1441 return turn_customizers_.back().get();
1442 }
1443
1444 // Checks that the function counters for a TestTurnCustomizer are greater than
1445 // 0.
1446 void ExpectTurnCustomizerCountersIncremented(
1447 cricket::TestTurnCustomizer* turn_customizer) {
1448 unsigned int allow_channel_data_counter =
1449 network_thread()->Invoke<unsigned int>(
1450 RTC_FROM_HERE, [turn_customizer] {
1451 return turn_customizer->allow_channel_data_cnt_;
1452 });
1453 EXPECT_GT(allow_channel_data_counter, 0u);
1454 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1455 RTC_FROM_HERE,
1456 [turn_customizer] { return turn_customizer->modify_cnt_; });
1457 EXPECT_GT(modify_counter, 0u);
1458 }
1459
deadbeef1dcb1642017-03-29 21:08:16 -07001460 // Once called, SDP blobs and ICE candidates will be automatically signaled
1461 // between PeerConnections.
1462 void ConnectFakeSignaling() {
1463 caller_->set_signaling_message_receiver(callee_.get());
1464 callee_->set_signaling_message_receiver(caller_.get());
1465 }
1466
Steve Antonede9ca52017-10-16 13:04:27 -07001467 // Once called, SDP blobs will be automatically signaled between
1468 // PeerConnections. Note that ICE candidates will not be signaled unless they
1469 // are in the exchanged SDP blobs.
1470 void ConnectFakeSignalingForSdpOnly() {
1471 ConnectFakeSignaling();
1472 SetSignalIceCandidates(false);
1473 }
1474
deadbeef1dcb1642017-03-29 21:08:16 -07001475 void SetSignalingDelayMs(int delay_ms) {
1476 caller_->set_signaling_delay_ms(delay_ms);
1477 callee_->set_signaling_delay_ms(delay_ms);
1478 }
1479
Steve Antonede9ca52017-10-16 13:04:27 -07001480 void SetSignalIceCandidates(bool signal) {
1481 caller_->set_signal_ice_candidates(signal);
1482 callee_->set_signal_ice_candidates(signal);
1483 }
1484
deadbeef1dcb1642017-03-29 21:08:16 -07001485 // Messages may get lost on the unreliable DataChannel, so we send multiple
1486 // times to avoid test flakiness.
1487 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1488 const std::string& data,
1489 int retries) {
1490 for (int i = 0; i < retries; ++i) {
1491 dc->Send(DataBuffer(data));
1492 }
1493 }
1494
1495 rtc::Thread* network_thread() { return network_thread_.get(); }
1496
1497 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1498
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001499 webrtc::MediaTransportPair* loopback_media_transports() {
1500 return &loopback_media_transports_;
1501 }
1502
deadbeef1dcb1642017-03-29 21:08:16 -07001503 PeerConnectionWrapper* caller() { return caller_.get(); }
1504
1505 // Set the |caller_| to the |wrapper| passed in and return the
1506 // original |caller_|.
1507 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1508 PeerConnectionWrapper* wrapper) {
1509 PeerConnectionWrapper* old = caller_.release();
1510 caller_.reset(wrapper);
1511 return old;
1512 }
1513
1514 PeerConnectionWrapper* callee() { return callee_.get(); }
1515
1516 // Set the |callee_| to the |wrapper| passed in and return the
1517 // original |callee_|.
1518 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1519 PeerConnectionWrapper* wrapper) {
1520 PeerConnectionWrapper* old = callee_.release();
1521 callee_.reset(wrapper);
1522 return old;
1523 }
1524
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001525 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1526 network_thread()->Invoke<void>(
1527 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1528 caller()->port_allocator(), caller_flags));
1529 network_thread()->Invoke<void>(
1530 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1531 callee()->port_allocator(), callee_flags));
1532 }
1533
Steve Antonede9ca52017-10-16 13:04:27 -07001534 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1535
Seth Hampson2f0d7022018-02-20 11:54:42 -08001536 // Expects the provided number of new frames to be received within
1537 // kMaxWaitForFramesMs. The new expected frames are specified in
1538 // |media_expectations|. Returns false if any of the expectations were
1539 // not met.
1540 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1541 // First initialize the expected frame counts based upon the current
1542 // frame count.
1543 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1544 if (media_expectations.caller_audio_expectation_ ==
1545 MediaExpectations::kExpectSomeFrames) {
1546 total_caller_audio_frames_expected +=
1547 media_expectations.caller_audio_frames_expected_;
1548 }
1549 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001550 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001551 if (media_expectations.caller_video_expectation_ ==
1552 MediaExpectations::kExpectSomeFrames) {
1553 total_caller_video_frames_expected +=
1554 media_expectations.caller_video_frames_expected_;
1555 }
1556 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1557 if (media_expectations.callee_audio_expectation_ ==
1558 MediaExpectations::kExpectSomeFrames) {
1559 total_callee_audio_frames_expected +=
1560 media_expectations.callee_audio_frames_expected_;
1561 }
1562 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001563 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001564 if (media_expectations.callee_video_expectation_ ==
1565 MediaExpectations::kExpectSomeFrames) {
1566 total_callee_video_frames_expected +=
1567 media_expectations.callee_video_frames_expected_;
1568 }
deadbeef1dcb1642017-03-29 21:08:16 -07001569
Seth Hampson2f0d7022018-02-20 11:54:42 -08001570 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001571 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001572 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001573 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001574 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001575 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001576 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001577 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001578 total_callee_video_frames_expected,
1579 kMaxWaitForFramesMs);
1580 bool expectations_correct =
1581 caller()->audio_frames_received() >=
1582 total_caller_audio_frames_expected &&
1583 caller()->min_video_frames_received_per_track() >=
1584 total_caller_video_frames_expected &&
1585 callee()->audio_frames_received() >=
1586 total_callee_audio_frames_expected &&
1587 callee()->min_video_frames_received_per_track() >=
1588 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001589
Seth Hampson2f0d7022018-02-20 11:54:42 -08001590 // After the combined wait, print out a more detailed message upon
1591 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001592 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001593 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001594 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001595 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001596 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001597 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001598 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001599 total_callee_video_frames_expected);
1600
1601 // We want to make sure nothing unexpected was received.
1602 if (media_expectations.caller_audio_expectation_ ==
1603 MediaExpectations::kExpectNoFrames) {
1604 EXPECT_EQ(caller()->audio_frames_received(),
1605 total_caller_audio_frames_expected);
1606 if (caller()->audio_frames_received() !=
1607 total_caller_audio_frames_expected) {
1608 expectations_correct = false;
1609 }
1610 }
1611 if (media_expectations.caller_video_expectation_ ==
1612 MediaExpectations::kExpectNoFrames) {
1613 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1614 total_caller_video_frames_expected);
1615 if (caller()->min_video_frames_received_per_track() !=
1616 total_caller_video_frames_expected) {
1617 expectations_correct = false;
1618 }
1619 }
1620 if (media_expectations.callee_audio_expectation_ ==
1621 MediaExpectations::kExpectNoFrames) {
1622 EXPECT_EQ(callee()->audio_frames_received(),
1623 total_callee_audio_frames_expected);
1624 if (callee()->audio_frames_received() !=
1625 total_callee_audio_frames_expected) {
1626 expectations_correct = false;
1627 }
1628 }
1629 if (media_expectations.callee_video_expectation_ ==
1630 MediaExpectations::kExpectNoFrames) {
1631 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1632 total_callee_video_frames_expected);
1633 if (callee()->min_video_frames_received_per_track() !=
1634 total_callee_video_frames_expected) {
1635 expectations_correct = false;
1636 }
1637 }
1638 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001639 }
1640
Steve Antond91969e2019-05-30 12:27:03 -07001641 void ClosePeerConnections() {
1642 caller()->pc()->Close();
1643 callee()->pc()->Close();
1644 }
1645
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001646 void TestNegotiatedCipherSuite(
1647 const PeerConnectionFactory::Options& caller_options,
1648 const PeerConnectionFactory::Options& callee_options,
1649 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001650 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1651 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001652 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001653 caller()->AddAudioVideoTracks();
1654 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001655 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001656 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001657 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001658 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001659 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00001660 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001661 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1662 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001663 }
1664
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001665 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1666 bool remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001667 bool aes_ctr_enabled,
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001668 int expected_cipher_suite) {
1669 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001670 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1671 local_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001672 caller_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1673 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001674 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001675 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1676 remote_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001677 callee_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1678 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001679 TestNegotiatedCipherSuite(caller_options, callee_options,
1680 expected_cipher_suite);
1681 }
1682
Seth Hampson2f0d7022018-02-20 11:54:42 -08001683 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001684 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001685
deadbeef1dcb1642017-03-29 21:08:16 -07001686 private:
1687 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001688 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001689 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001690 // |network_thread_| and |worker_thread_| are used by both
1691 // |caller_| and |callee_| so they must be destroyed
1692 // later.
1693 std::unique_ptr<rtc::Thread> network_thread_;
1694 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001695 // The turn servers and turn customizers should be accessed & deleted on the
1696 // network thread to avoid a race with the socket read/write that occurs
1697 // on the network thread.
1698 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1699 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001700 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001701 std::unique_ptr<PeerConnectionWrapper> caller_;
1702 std::unique_ptr<PeerConnectionWrapper> callee_;
1703};
1704
Seth Hampson2f0d7022018-02-20 11:54:42 -08001705class PeerConnectionIntegrationTest
1706 : public PeerConnectionIntegrationBaseTest,
1707 public ::testing::WithParamInterface<SdpSemantics> {
1708 protected:
1709 PeerConnectionIntegrationTest()
1710 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1711};
1712
1713class PeerConnectionIntegrationTestPlanB
1714 : public PeerConnectionIntegrationBaseTest {
1715 protected:
1716 PeerConnectionIntegrationTestPlanB()
1717 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1718};
1719
1720class PeerConnectionIntegrationTestUnifiedPlan
1721 : public PeerConnectionIntegrationBaseTest {
1722 protected:
1723 PeerConnectionIntegrationTestUnifiedPlan()
1724 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1725};
1726
deadbeef1dcb1642017-03-29 21:08:16 -07001727// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1728// includes testing that the callback is invoked if an observer is connected
1729// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001730TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001731 RtpReceiverObserverOnFirstPacketReceived) {
1732 ASSERT_TRUE(CreatePeerConnectionWrappers());
1733 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001734 caller()->AddAudioVideoTracks();
1735 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001736 // Start offer/answer exchange and wait for it to complete.
1737 caller()->CreateAndSetAndSignalOffer();
1738 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1739 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001740 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1741 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001742 // Wait for all "first packet received" callbacks to be fired.
1743 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001744 absl::c_all_of(caller()->rtp_receiver_observers(),
1745 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1746 return o->first_packet_received();
1747 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001748 kMaxWaitForFramesMs);
1749 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001750 absl::c_all_of(callee()->rtp_receiver_observers(),
1751 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1752 return o->first_packet_received();
1753 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001754 kMaxWaitForFramesMs);
1755 // If new observers are set after the first packet was already received, the
1756 // callback should still be invoked.
1757 caller()->ResetRtpReceiverObservers();
1758 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001759 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1760 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001761 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001762 absl::c_all_of(caller()->rtp_receiver_observers(),
1763 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1764 return o->first_packet_received();
1765 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001766 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001767 absl::c_all_of(callee()->rtp_receiver_observers(),
1768 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1769 return o->first_packet_received();
1770 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001771}
1772
1773class DummyDtmfObserver : public DtmfSenderObserverInterface {
1774 public:
1775 DummyDtmfObserver() : completed_(false) {}
1776
1777 // Implements DtmfSenderObserverInterface.
1778 void OnToneChange(const std::string& tone) override {
1779 tones_.push_back(tone);
1780 if (tone.empty()) {
1781 completed_ = true;
1782 }
1783 }
1784
1785 const std::vector<std::string>& tones() const { return tones_; }
1786 bool completed() const { return completed_; }
1787
1788 private:
1789 bool completed_;
1790 std::vector<std::string> tones_;
1791};
1792
1793// Assumes |sender| already has an audio track added and the offer/answer
1794// exchange is done.
1795void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1796 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001797 // We should be able to get a DTMF sender from the local sender.
1798 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1799 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1800 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001801 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001802 dtmf_sender->RegisterObserver(&observer);
1803
1804 // Test the DtmfSender object just created.
1805 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1806 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1807
1808 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1809 std::vector<std::string> tones = {"1", "a", ""};
1810 EXPECT_EQ(tones, observer.tones());
1811 dtmf_sender->UnregisterObserver();
1812 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1813}
1814
1815// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1816// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001817TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001818 ASSERT_TRUE(CreatePeerConnectionWrappers());
1819 ConnectFakeSignaling();
1820 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001821 caller()->AddAudioTrack();
1822 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001823 caller()->CreateAndSetAndSignalOffer();
1824 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001825 // DTLS must finish before the DTMF sender can be used reliably.
1826 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001827 TestDtmfFromSenderToReceiver(caller(), callee());
1828 TestDtmfFromSenderToReceiver(callee(), caller());
1829}
1830
1831// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1832// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001833TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001834 ASSERT_TRUE(CreatePeerConnectionWrappers());
1835 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001836
deadbeef1dcb1642017-03-29 21:08:16 -07001837 // Do normal offer/answer and wait for some frames to be received in each
1838 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001839 caller()->AddAudioVideoTracks();
1840 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001841 caller()->CreateAndSetAndSignalOffer();
1842 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001843 MediaExpectations media_expectations;
1844 media_expectations.ExpectBidirectionalAudioAndVideo();
1845 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001846 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1847 webrtc::kEnumCounterKeyProtocolDtls));
1848 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1849 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001850}
1851
1852// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001853TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001854 PeerConnectionInterface::RTCConfiguration sdes_config;
1855 sdes_config.enable_dtls_srtp.emplace(false);
1856 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1857 ConnectFakeSignaling();
1858
1859 // Do normal offer/answer and wait for some frames to be received in each
1860 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001861 caller()->AddAudioVideoTracks();
1862 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001863 caller()->CreateAndSetAndSignalOffer();
1864 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001865 MediaExpectations media_expectations;
1866 media_expectations.ExpectBidirectionalAudioAndVideo();
1867 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001868 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1869 webrtc::kEnumCounterKeyProtocolSdes));
1870 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1871 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001872}
1873
Steve Anton9a44b2d2019-07-12 12:58:30 -07001874// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1875// option to offer encrypted versions of all header extensions alongside the
1876// unencrypted versions.
1877TEST_P(PeerConnectionIntegrationTest,
1878 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1879 CryptoOptions crypto_options;
1880 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1881 PeerConnectionInterface::RTCConfiguration config;
1882 config.crypto_options = crypto_options;
1883 // Note: This allows offering >14 RTP header extensions.
1884 config.offer_extmap_allow_mixed = true;
1885 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1886 ConnectFakeSignaling();
1887
1888 // Do normal offer/answer and wait for some frames to be received in each
1889 // direction.
1890 caller()->AddAudioVideoTracks();
1891 callee()->AddAudioVideoTracks();
1892 caller()->CreateAndSetAndSignalOffer();
1893 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1894 MediaExpectations media_expectations;
1895 media_expectations.ExpectBidirectionalAudioAndVideo();
1896 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1897}
1898
Steve Anton8c0f7a72017-10-03 10:03:10 -07001899// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1900// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001901TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001902 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1903 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1904 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1905 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1906 return pc->GetRemoteAudioSSLCertificate();
1907 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001908 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1909 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1910 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1911 return pc->GetRemoteAudioSSLCertChain();
1912 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001913
1914 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1915 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1916
1917 // Configure each side with a known certificate so they can be compared later.
1918 PeerConnectionInterface::RTCConfiguration caller_config;
1919 caller_config.enable_dtls_srtp.emplace(true);
1920 caller_config.certificates.push_back(caller_cert);
1921 PeerConnectionInterface::RTCConfiguration callee_config;
1922 callee_config.enable_dtls_srtp.emplace(true);
1923 callee_config.certificates.push_back(callee_cert);
1924 ASSERT_TRUE(
1925 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1926 ConnectFakeSignaling();
1927
1928 // When first initialized, there should not be a remote SSL certificate (and
1929 // calling this method should not crash).
1930 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1931 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001932 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1933 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001934
Steve Anton15324772018-01-16 10:26:49 -08001935 caller()->AddAudioTrack();
1936 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001937 caller()->CreateAndSetAndSignalOffer();
1938 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1939 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1940
1941 // Once DTLS has been connected, each side should return the other's SSL
1942 // certificate when calling GetRemoteAudioSSLCertificate.
1943
1944 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1945 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001946 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001947 caller_remote_cert->ToPEMString());
1948
1949 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1950 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001951 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001952 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001953
1954 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1955 ASSERT_TRUE(caller_remote_cert_chain);
1956 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1957 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001958 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001959 remote_cert->ToPEMString());
1960
1961 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1962 ASSERT_TRUE(callee_remote_cert_chain);
1963 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1964 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001965 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001966 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001967}
1968
deadbeef1dcb1642017-03-29 21:08:16 -07001969// This test sets up a call between two parties with a source resolution of
1970// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001971TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001972 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1973 ASSERT_TRUE(CreatePeerConnectionWrappers());
1974 ConnectFakeSignaling();
1975
Niels Möller5c7efe72018-05-11 10:34:46 +02001976 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1977 webrtc::FakePeriodicVideoSource::Config config;
1978 config.width = 1280;
1979 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001980 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001981 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1982 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001983
1984 // Do normal offer/answer and wait for at least one frame to be received in
1985 // each direction.
1986 caller()->CreateAndSetAndSignalOffer();
1987 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1988 callee()->min_video_frames_received_per_track() > 0,
1989 kMaxWaitForFramesMs);
1990
1991 // Check rendered aspect ratio.
1992 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1993 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1994 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1995 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1996}
1997
1998// This test sets up an one-way call, with media only from caller to
1999// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002000TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07002001 ASSERT_TRUE(CreatePeerConnectionWrappers());
2002 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002003 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002004 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002005 MediaExpectations media_expectations;
2006 media_expectations.CalleeExpectsSomeAudioAndVideo();
2007 media_expectations.CallerExpectsNoAudio();
2008 media_expectations.CallerExpectsNoVideo();
2009 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002010}
2011
2012// This test sets up a audio call initially, with the callee rejecting video
2013// initially. Then later the callee decides to upgrade to audio/video, and
2014// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002015TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07002016 ASSERT_TRUE(CreatePeerConnectionWrappers());
2017 ConnectFakeSignaling();
2018 // Initially, offer an audio/video stream from the caller, but refuse to
2019 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08002020 caller()->AddAudioVideoTracks();
2021 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002022 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2023 PeerConnectionInterface::RTCOfferAnswerOptions options;
2024 options.offer_to_receive_video = 0;
2025 callee()->SetOfferAnswerOptions(options);
2026 } else {
2027 callee()->SetRemoteOfferHandler([this] {
2028 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2029 });
2030 }
deadbeef1dcb1642017-03-29 21:08:16 -07002031 // Do offer/answer and make sure audio is still received end-to-end.
2032 caller()->CreateAndSetAndSignalOffer();
2033 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002034 {
2035 MediaExpectations media_expectations;
2036 media_expectations.ExpectBidirectionalAudio();
2037 media_expectations.ExpectNoVideo();
2038 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2039 }
deadbeef1dcb1642017-03-29 21:08:16 -07002040 // Sanity check that the callee's description has a rejected video section.
2041 ASSERT_NE(nullptr, callee()->pc()->local_description());
2042 const ContentInfo* callee_video_content =
2043 GetFirstVideoContent(callee()->pc()->local_description()->description());
2044 ASSERT_NE(nullptr, callee_video_content);
2045 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002046
deadbeef1dcb1642017-03-29 21:08:16 -07002047 // Now negotiate with video and ensure negotiation succeeds, with video
2048 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002049 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002050 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2051 PeerConnectionInterface::RTCOfferAnswerOptions options;
2052 options.offer_to_receive_video = 1;
2053 callee()->SetOfferAnswerOptions(options);
2054 } else {
2055 callee()->SetRemoteOfferHandler(nullptr);
2056 caller()->SetRemoteOfferHandler([this] {
2057 // The caller creates a new transceiver to receive video on when receiving
2058 // the offer, but by default it is send only.
2059 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002060 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002061 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
2062 transceivers[2]->receiver()->media_type());
2063 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2064 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
2065 });
2066 }
deadbeef1dcb1642017-03-29 21:08:16 -07002067 callee()->CreateAndSetAndSignalOffer();
2068 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002069 {
2070 // Expect additional audio frames to be received after the upgrade.
2071 MediaExpectations media_expectations;
2072 media_expectations.ExpectBidirectionalAudioAndVideo();
2073 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2074 }
deadbeef1dcb1642017-03-29 21:08:16 -07002075}
2076
deadbeef4389b4d2017-09-07 09:07:36 -07002077// Simpler than the above test; just add an audio track to an established
2078// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002079TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002080 ASSERT_TRUE(CreatePeerConnectionWrappers());
2081 ConnectFakeSignaling();
2082 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002083 caller()->AddVideoTrack();
2084 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002085 caller()->CreateAndSetAndSignalOffer();
2086 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2087 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002088 caller()->AddAudioTrack();
2089 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002090 caller()->CreateAndSetAndSignalOffer();
2091 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2092 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002093 MediaExpectations media_expectations;
2094 media_expectations.ExpectBidirectionalAudioAndVideo();
2095 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002096}
2097
deadbeef1dcb1642017-03-29 21:08:16 -07002098// This test sets up a call that's transferred to a new caller with a different
2099// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002100TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002101 ASSERT_TRUE(CreatePeerConnectionWrappers());
2102 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002103 caller()->AddAudioVideoTracks();
2104 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002105 caller()->CreateAndSetAndSignalOffer();
2106 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2107
2108 // Keep the original peer around which will still send packets to the
2109 // receiving client. These SRTP packets will be dropped.
2110 std::unique_ptr<PeerConnectionWrapper> original_peer(
2111 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002112 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002113 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2114 // directly above.
2115 original_peer->pc()->Close();
2116
2117 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002118 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002119 caller()->CreateAndSetAndSignalOffer();
2120 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2121 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002122 MediaExpectations media_expectations;
2123 media_expectations.ExpectBidirectionalAudioAndVideo();
2124 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002125}
2126
2127// This test sets up a call that's transferred to a new callee with a different
2128// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002129TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
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 SetCalleePcWrapperAndReturnCurrent(
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 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002148 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2149 caller()->CreateAndSetAndSignalOffer();
2150 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2151 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002152 MediaExpectations media_expectations;
2153 media_expectations.ExpectBidirectionalAudioAndVideo();
2154 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002155}
2156
2157// This test sets up a non-bundled call and negotiates bundling at the same
2158// time as starting an ICE restart. When bundling is in effect in the restart,
2159// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002160TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002161 ASSERT_TRUE(CreatePeerConnectionWrappers());
2162 ConnectFakeSignaling();
2163
Steve Anton15324772018-01-16 10:26:49 -08002164 caller()->AddAudioVideoTracks();
2165 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002166 // Remove the bundle group from the SDP received by the callee.
2167 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2168 desc->RemoveGroupByName("BUNDLE");
2169 });
2170 caller()->CreateAndSetAndSignalOffer();
2171 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002172 {
2173 MediaExpectations media_expectations;
2174 media_expectations.ExpectBidirectionalAudioAndVideo();
2175 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2176 }
deadbeef1dcb1642017-03-29 21:08:16 -07002177 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2178 callee()->SetReceivedSdpMunger(nullptr);
2179 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2180 caller()->CreateAndSetAndSignalOffer();
2181 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2182
2183 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002184 {
2185 MediaExpectations media_expectations;
2186 media_expectations.ExpectBidirectionalAudioAndVideo();
2187 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2188 }
deadbeef1dcb1642017-03-29 21:08:16 -07002189}
2190
2191// Test CVO (Coordination of Video Orientation). If a video source is rotated
2192// and both peers support the CVO RTP header extension, the actual video frames
2193// don't need to be encoded in different resolutions, since the rotation is
2194// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002195TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002196 ASSERT_TRUE(CreatePeerConnectionWrappers());
2197 ConnectFakeSignaling();
2198 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002199 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002200 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002201 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002202 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2203
2204 // Wait for video frames to be received by both sides.
2205 caller()->CreateAndSetAndSignalOffer();
2206 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2207 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2208 callee()->min_video_frames_received_per_track() > 0,
2209 kMaxWaitForFramesMs);
2210
2211 // Ensure that the aspect ratio is unmodified.
2212 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2213 // not just assumed.
2214 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2215 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2216 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2217 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2218 // Ensure that the CVO bits were surfaced to the renderer.
2219 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2220 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2221}
2222
2223// Test that when the CVO extension isn't supported, video is rotated the
2224// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002225TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002226 ASSERT_TRUE(CreatePeerConnectionWrappers());
2227 ConnectFakeSignaling();
2228 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002229 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002230 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002231 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002232 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2233
2234 // Remove the CVO extension from the offered SDP.
2235 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2236 cricket::VideoContentDescription* video =
2237 GetFirstVideoContentDescription(desc);
2238 video->ClearRtpHeaderExtensions();
2239 });
2240 // Wait for video frames to be received by both sides.
2241 caller()->CreateAndSetAndSignalOffer();
2242 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2243 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2244 callee()->min_video_frames_received_per_track() > 0,
2245 kMaxWaitForFramesMs);
2246
2247 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2248 // rotation.
2249 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2250 // not just assumed.
2251 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2252 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2253 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2254 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2255 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2256 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2257 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2258}
2259
deadbeef1dcb1642017-03-29 21:08:16 -07002260// Test that if the answerer rejects the audio m= section, no audio is sent or
2261// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002262TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002263 ASSERT_TRUE(CreatePeerConnectionWrappers());
2264 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002265 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002266 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2267 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2268 // it will reject the audio m= section completely.
2269 PeerConnectionInterface::RTCOfferAnswerOptions options;
2270 options.offer_to_receive_audio = 0;
2271 callee()->SetOfferAnswerOptions(options);
2272 } else {
2273 // Stopping the audio RtpTransceiver will cause the media section to be
2274 // rejected in the answer.
2275 callee()->SetRemoteOfferHandler([this] {
2276 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2277 });
2278 }
Steve Anton15324772018-01-16 10:26:49 -08002279 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002280 // Do offer/answer and wait for successful end-to-end video frames.
2281 caller()->CreateAndSetAndSignalOffer();
2282 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002283 MediaExpectations media_expectations;
2284 media_expectations.ExpectBidirectionalVideo();
2285 media_expectations.ExpectNoAudio();
2286 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2287
deadbeef1dcb1642017-03-29 21:08:16 -07002288 // Sanity check that the callee's description has a rejected audio section.
2289 ASSERT_NE(nullptr, callee()->pc()->local_description());
2290 const ContentInfo* callee_audio_content =
2291 GetFirstAudioContent(callee()->pc()->local_description()->description());
2292 ASSERT_NE(nullptr, callee_audio_content);
2293 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002294 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2295 // The caller's transceiver should have stopped after receiving the answer.
2296 EXPECT_TRUE(caller()
2297 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2298 ->stopped());
2299 }
deadbeef1dcb1642017-03-29 21:08:16 -07002300}
2301
2302// Test that if the answerer rejects the video m= section, no video is sent or
2303// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002304TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002305 ASSERT_TRUE(CreatePeerConnectionWrappers());
2306 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002307 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002308 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2309 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2310 // it will reject the video m= section completely.
2311 PeerConnectionInterface::RTCOfferAnswerOptions options;
2312 options.offer_to_receive_video = 0;
2313 callee()->SetOfferAnswerOptions(options);
2314 } else {
2315 // Stopping the video RtpTransceiver will cause the media section to be
2316 // rejected in the answer.
2317 callee()->SetRemoteOfferHandler([this] {
2318 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2319 });
2320 }
Steve Anton15324772018-01-16 10:26:49 -08002321 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002322 // Do offer/answer and wait for successful end-to-end audio frames.
2323 caller()->CreateAndSetAndSignalOffer();
2324 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002325 MediaExpectations media_expectations;
2326 media_expectations.ExpectBidirectionalAudio();
2327 media_expectations.ExpectNoVideo();
2328 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2329
deadbeef1dcb1642017-03-29 21:08:16 -07002330 // Sanity check that the callee's description has a rejected video section.
2331 ASSERT_NE(nullptr, callee()->pc()->local_description());
2332 const ContentInfo* callee_video_content =
2333 GetFirstVideoContent(callee()->pc()->local_description()->description());
2334 ASSERT_NE(nullptr, callee_video_content);
2335 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002336 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2337 // The caller's transceiver should have stopped after receiving the answer.
2338 EXPECT_TRUE(caller()
2339 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2340 ->stopped());
2341 }
deadbeef1dcb1642017-03-29 21:08:16 -07002342}
2343
2344// Test that if the answerer rejects both audio and video m= sections, nothing
2345// bad happens.
2346// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2347// test anything but the fact that negotiation succeeds, which doesn't mean
2348// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002349TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002350 ASSERT_TRUE(CreatePeerConnectionWrappers());
2351 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002352 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002353 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2354 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2355 // will reject both audio and video m= sections.
2356 PeerConnectionInterface::RTCOfferAnswerOptions options;
2357 options.offer_to_receive_audio = 0;
2358 options.offer_to_receive_video = 0;
2359 callee()->SetOfferAnswerOptions(options);
2360 } else {
2361 callee()->SetRemoteOfferHandler([this] {
2362 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002363 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002364 transceiver->Stop();
2365 }
2366 });
2367 }
deadbeef1dcb1642017-03-29 21:08:16 -07002368 // Do offer/answer and wait for stable signaling state.
2369 caller()->CreateAndSetAndSignalOffer();
2370 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002371
deadbeef1dcb1642017-03-29 21:08:16 -07002372 // Sanity check that the callee's description has rejected m= sections.
2373 ASSERT_NE(nullptr, callee()->pc()->local_description());
2374 const ContentInfo* callee_audio_content =
2375 GetFirstAudioContent(callee()->pc()->local_description()->description());
2376 ASSERT_NE(nullptr, callee_audio_content);
2377 EXPECT_TRUE(callee_audio_content->rejected);
2378 const ContentInfo* callee_video_content =
2379 GetFirstVideoContent(callee()->pc()->local_description()->description());
2380 ASSERT_NE(nullptr, callee_video_content);
2381 EXPECT_TRUE(callee_video_content->rejected);
2382}
2383
2384// This test sets up an audio and video call between two parties. After the
2385// call runs for a while, the caller sends an updated offer with video being
2386// rejected. Once the re-negotiation is done, the video flow should stop and
2387// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002388TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002389 ASSERT_TRUE(CreatePeerConnectionWrappers());
2390 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002391 caller()->AddAudioVideoTracks();
2392 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002393 caller()->CreateAndSetAndSignalOffer();
2394 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002395 {
2396 MediaExpectations media_expectations;
2397 media_expectations.ExpectBidirectionalAudioAndVideo();
2398 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2399 }
deadbeef1dcb1642017-03-29 21:08:16 -07002400 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002401 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2402 caller()->SetGeneratedSdpMunger(
2403 [](cricket::SessionDescription* description) {
2404 for (cricket::ContentInfo& content : description->contents()) {
2405 if (cricket::IsVideoContent(&content)) {
2406 content.rejected = true;
2407 }
2408 }
2409 });
2410 } else {
2411 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2412 }
deadbeef1dcb1642017-03-29 21:08:16 -07002413 caller()->CreateAndSetAndSignalOffer();
2414 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2415
2416 // Sanity check that the caller's description has a rejected video section.
2417 ASSERT_NE(nullptr, caller()->pc()->local_description());
2418 const ContentInfo* caller_video_content =
2419 GetFirstVideoContent(caller()->pc()->local_description()->description());
2420 ASSERT_NE(nullptr, caller_video_content);
2421 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002422 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002423 {
2424 MediaExpectations media_expectations;
2425 media_expectations.ExpectBidirectionalAudio();
2426 media_expectations.ExpectNoVideo();
2427 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2428 }
deadbeef1dcb1642017-03-29 21:08:16 -07002429}
2430
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002431// Do one offer/answer with audio, another that disables it (rejecting the m=
2432// section), and another that re-enables it. Regression test for:
2433// bugs.webrtc.org/6023
2434TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2435 ASSERT_TRUE(CreatePeerConnectionWrappers());
2436 ConnectFakeSignaling();
2437
2438 // Add audio track, do normal offer/answer.
2439 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2440 caller()->CreateLocalAudioTrack();
2441 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2442 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2443 caller()->CreateAndSetAndSignalOffer();
2444 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2445
2446 // Remove audio track, and set offer_to_receive_audio to false to cause the
2447 // m= section to be completely disabled, not just "recvonly".
2448 caller()->pc()->RemoveTrack(sender);
2449 PeerConnectionInterface::RTCOfferAnswerOptions options;
2450 options.offer_to_receive_audio = 0;
2451 caller()->SetOfferAnswerOptions(options);
2452 caller()->CreateAndSetAndSignalOffer();
2453 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2454
2455 // Add the audio track again, expecting negotiation to succeed and frames to
2456 // flow.
2457 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2458 options.offer_to_receive_audio = 1;
2459 caller()->SetOfferAnswerOptions(options);
2460 caller()->CreateAndSetAndSignalOffer();
2461 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2462
2463 MediaExpectations media_expectations;
2464 media_expectations.CalleeExpectsSomeAudio();
2465 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2466}
2467
deadbeef1dcb1642017-03-29 21:08:16 -07002468// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2469// is needed to support legacy endpoints.
2470// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2471// add a test for an end-to-end test without MID signaling either (basically,
2472// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002473TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002474 ASSERT_TRUE(CreatePeerConnectionWrappers());
2475 ConnectFakeSignaling();
2476 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002477 caller()->AddAudioVideoTracks();
2478 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002479 // Remove SSRCs and MSIDs from the received offer SDP.
2480 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002481 caller()->CreateAndSetAndSignalOffer();
2482 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002483 MediaExpectations media_expectations;
2484 media_expectations.ExpectBidirectionalAudioAndVideo();
2485 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002486}
2487
Seth Hampson5897a6e2018-04-03 11:16:33 -07002488// Basic end-to-end test, without SSRC signaling. This means that the track
2489// was created properly and frames are delivered when the MSIDs are communicated
2490// with a=msid lines and no a=ssrc lines.
2491TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2492 EndToEndCallWithoutSsrcSignaling) {
2493 const char kStreamId[] = "streamId";
2494 ASSERT_TRUE(CreatePeerConnectionWrappers());
2495 ConnectFakeSignaling();
2496 // Add just audio tracks.
2497 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2498 callee()->AddAudioTrack();
2499
2500 // Remove SSRCs from the received offer SDP.
2501 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2502 caller()->CreateAndSetAndSignalOffer();
2503 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2504 MediaExpectations media_expectations;
2505 media_expectations.ExpectBidirectionalAudio();
2506 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2507}
2508
Steve Antondf527fd2018-04-27 15:52:03 -07002509// Tests that video flows between multiple video tracks when SSRCs are not
2510// signaled. This exercises the MID RTP header extension which is needed to
2511// demux the incoming video tracks.
2512TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2513 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2514 ASSERT_TRUE(CreatePeerConnectionWrappers());
2515 ConnectFakeSignaling();
2516 caller()->AddVideoTrack();
2517 caller()->AddVideoTrack();
2518 callee()->AddVideoTrack();
2519 callee()->AddVideoTrack();
2520
2521 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2522 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2523 caller()->CreateAndSetAndSignalOffer();
2524 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2525 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2526 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2527
2528 // Expect video to be received in both directions on both tracks.
2529 MediaExpectations media_expectations;
2530 media_expectations.ExpectBidirectionalVideo();
2531 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2532}
2533
Henrik Boström5b147782018-12-04 11:25:05 +01002534TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2535 ASSERT_TRUE(CreatePeerConnectionWrappers());
2536 ConnectFakeSignaling();
2537 caller()->AddAudioTrack();
2538 caller()->AddVideoTrack();
2539 caller()->CreateAndSetAndSignalOffer();
2540 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2541 auto callee_receivers = callee()->pc()->GetReceivers();
2542 ASSERT_EQ(2u, callee_receivers.size());
2543 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2544 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2545}
2546
2547TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2548 ASSERT_TRUE(CreatePeerConnectionWrappers());
2549 ConnectFakeSignaling();
2550 caller()->AddAudioTrack();
2551 caller()->AddVideoTrack();
2552 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2553 caller()->CreateAndSetAndSignalOffer();
2554 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2555 auto callee_receivers = callee()->pc()->GetReceivers();
2556 ASSERT_EQ(2u, callee_receivers.size());
2557 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2558 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2559 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2560 callee_receivers[1]->stream_ids()[0]);
2561 EXPECT_EQ(callee_receivers[0]->streams()[0],
2562 callee_receivers[1]->streams()[0]);
2563}
2564
deadbeef1dcb1642017-03-29 21:08:16 -07002565// Test that if two video tracks are sent (from caller to callee, in this test),
2566// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002567TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002568 ASSERT_TRUE(CreatePeerConnectionWrappers());
2569 ConnectFakeSignaling();
2570 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002571 caller()->AddAudioVideoTracks();
2572 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002573 caller()->CreateAndSetAndSignalOffer();
2574 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002575 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002576
2577 MediaExpectations media_expectations;
2578 media_expectations.CalleeExpectsSomeAudioAndVideo();
2579 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002580}
2581
2582static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2583 bool first = true;
2584 for (cricket::ContentInfo& content : desc->contents()) {
2585 if (first) {
2586 first = false;
2587 continue;
2588 }
2589 content.bundle_only = true;
2590 }
2591 first = true;
2592 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2593 if (first) {
2594 first = false;
2595 continue;
2596 }
2597 transport.description.ice_ufrag.clear();
2598 transport.description.ice_pwd.clear();
2599 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2600 transport.description.identity_fingerprint.reset(nullptr);
2601 }
2602}
2603
2604// Test that if applying a true "max bundle" offer, which uses ports of 0,
2605// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2606// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2607// successfully and media flows.
2608// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2609// TODO(deadbeef): Won't need this test once we start generating actual
2610// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002611TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002612 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2613 ASSERT_TRUE(CreatePeerConnectionWrappers());
2614 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002615 caller()->AddAudioVideoTracks();
2616 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002617 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2618 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2619 // but the first m= section.
2620 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2621 caller()->CreateAndSetAndSignalOffer();
2622 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002623 MediaExpectations media_expectations;
2624 media_expectations.ExpectBidirectionalAudioAndVideo();
2625 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002626}
2627
2628// Test that we can receive the audio output level from a remote audio track.
2629// TODO(deadbeef): Use a fake audio source and verify that the output level is
2630// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002631TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002632 ASSERT_TRUE(CreatePeerConnectionWrappers());
2633 ConnectFakeSignaling();
2634 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002635 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002636 caller()->CreateAndSetAndSignalOffer();
2637 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2638
2639 // Get the audio output level stats. Note that the level is not available
2640 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002641 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002642 kMaxWaitForFramesMs);
2643}
2644
2645// Test that an audio input level is reported.
2646// TODO(deadbeef): Use a fake audio source and verify that the input level is
2647// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002648TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002649 ASSERT_TRUE(CreatePeerConnectionWrappers());
2650 ConnectFakeSignaling();
2651 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002652 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002653 caller()->CreateAndSetAndSignalOffer();
2654 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2655
2656 // Get the audio input level stats. The level should be available very
2657 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002658 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002659 kMaxWaitForStatsMs);
2660}
2661
2662// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002663TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002664 ASSERT_TRUE(CreatePeerConnectionWrappers());
2665 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002666 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002667 // Do offer/answer, wait for the callee to receive some frames.
2668 caller()->CreateAndSetAndSignalOffer();
2669 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002670
2671 MediaExpectations media_expectations;
2672 media_expectations.CalleeExpectsSomeAudioAndVideo();
2673 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002674
2675 // Get a handle to the remote tracks created, so they can be used as GetStats
2676 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002677 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002678 // We received frames, so we definitely should have nonzero "received bytes"
2679 // stats at this point.
2680 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2681 0);
2682 }
deadbeef1dcb1642017-03-29 21:08:16 -07002683}
2684
2685// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002686TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002687 ASSERT_TRUE(CreatePeerConnectionWrappers());
2688 ConnectFakeSignaling();
2689 auto audio_track = caller()->CreateLocalAudioTrack();
2690 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002691 caller()->AddTrack(audio_track);
2692 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002693 // Do offer/answer, wait for the callee to receive some frames.
2694 caller()->CreateAndSetAndSignalOffer();
2695 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002696 MediaExpectations media_expectations;
2697 media_expectations.CalleeExpectsSomeAudioAndVideo();
2698 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002699
2700 // The callee received frames, so we definitely should have nonzero "sent
2701 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002702 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2703 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2704}
2705
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002706// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002707TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002708 ASSERT_TRUE(CreatePeerConnectionWrappers());
2709 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002710 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002711
Steve Anton15324772018-01-16 10:26:49 -08002712 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002713
2714 // Do offer/answer, wait for the callee to receive some frames.
2715 caller()->CreateAndSetAndSignalOffer();
2716 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2717
2718 // Get the remote audio track created on the receiver, so they can be used as
2719 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002720 auto receivers = callee()->pc()->GetReceivers();
2721 ASSERT_EQ(1u, receivers.size());
2722 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002723
2724 // Get the audio output level stats. Note that the level is not available
2725 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002726 EXPECT_TRUE_WAIT(
2727 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2728 0,
2729 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002730}
2731
Steve Antona41959e2018-11-28 11:15:33 -08002732// Test that the track ID is associated with all local and remote SSRC stats
2733// using the old GetStats() and more than 1 audio and more than 1 video track.
2734// This is a regression test for crbug.com/906988
2735TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2736 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2737 ASSERT_TRUE(CreatePeerConnectionWrappers());
2738 ConnectFakeSignaling();
2739 auto audio_sender_1 = caller()->AddAudioTrack();
2740 auto video_sender_1 = caller()->AddVideoTrack();
2741 auto audio_sender_2 = caller()->AddAudioTrack();
2742 auto video_sender_2 = caller()->AddVideoTrack();
2743 caller()->CreateAndSetAndSignalOffer();
2744 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2745
2746 MediaExpectations media_expectations;
2747 media_expectations.CalleeExpectsSomeAudioAndVideo();
2748 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2749
2750 std::vector<std::string> track_ids = {
2751 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2752 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2753
2754 auto caller_stats = caller()->OldGetStats();
2755 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2756 auto callee_stats = callee()->OldGetStats();
2757 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2758}
2759
Steve Antonffa6ce42018-11-30 09:26:08 -08002760// Test that the new GetStats() returns stats for all outgoing/incoming streams
2761// with the correct track IDs if there are more than one audio and more than one
2762// video senders/receivers.
2763TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2764 ASSERT_TRUE(CreatePeerConnectionWrappers());
2765 ConnectFakeSignaling();
2766 auto audio_sender_1 = caller()->AddAudioTrack();
2767 auto video_sender_1 = caller()->AddVideoTrack();
2768 auto audio_sender_2 = caller()->AddAudioTrack();
2769 auto video_sender_2 = caller()->AddVideoTrack();
2770 caller()->CreateAndSetAndSignalOffer();
2771 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2772
2773 MediaExpectations media_expectations;
2774 media_expectations.CalleeExpectsSomeAudioAndVideo();
2775 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2776
2777 std::vector<std::string> track_ids = {
2778 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2779 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2780
2781 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2782 caller()->NewGetStats();
2783 ASSERT_TRUE(caller_report);
2784 auto outbound_stream_stats =
2785 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2786 ASSERT_EQ(4u, outbound_stream_stats.size());
2787 std::vector<std::string> outbound_track_ids;
2788 for (const auto& stat : outbound_stream_stats) {
2789 ASSERT_TRUE(stat->bytes_sent.is_defined());
2790 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002791 if (*stat->kind == "video") {
2792 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
2793 EXPECT_GT(*stat->key_frames_encoded, 0u);
2794 ASSERT_TRUE(stat->frames_encoded.is_defined());
2795 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
2796 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002797 ASSERT_TRUE(stat->track_id.is_defined());
2798 const auto* track_stat =
2799 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2800 ASSERT_TRUE(track_stat);
2801 outbound_track_ids.push_back(*track_stat->track_identifier);
2802 }
2803 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2804
2805 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2806 callee()->NewGetStats();
2807 ASSERT_TRUE(callee_report);
2808 auto inbound_stream_stats =
2809 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2810 ASSERT_EQ(4u, inbound_stream_stats.size());
2811 std::vector<std::string> inbound_track_ids;
2812 for (const auto& stat : inbound_stream_stats) {
2813 ASSERT_TRUE(stat->bytes_received.is_defined());
2814 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002815 if (*stat->kind == "video") {
2816 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
2817 EXPECT_GT(*stat->key_frames_decoded, 0u);
2818 ASSERT_TRUE(stat->frames_decoded.is_defined());
2819 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
2820 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002821 ASSERT_TRUE(stat->track_id.is_defined());
2822 const auto* track_stat =
2823 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2824 ASSERT_TRUE(track_stat);
2825 inbound_track_ids.push_back(*track_stat->track_identifier);
2826 }
2827 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2828}
2829
2830// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002831// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2832// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002833TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002834 GetStatsForUnsignaledStreamWithNewStatsApi) {
2835 ASSERT_TRUE(CreatePeerConnectionWrappers());
2836 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002837 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002838 // Remove SSRCs and MSIDs from the received offer SDP.
2839 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2840 caller()->CreateAndSetAndSignalOffer();
2841 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002842 MediaExpectations media_expectations;
2843 media_expectations.CalleeExpectsSomeAudio(1);
2844 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002845
2846 // We received a frame, so we should have nonzero "bytes received" stats for
2847 // the unsignaled stream, if stats are working for it.
2848 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2849 callee()->NewGetStats();
2850 ASSERT_NE(nullptr, report);
2851 auto inbound_stream_stats =
2852 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2853 ASSERT_EQ(1U, inbound_stream_stats.size());
2854 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2855 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002856 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2857}
2858
Taylor Brandstettera4653442018-06-19 09:44:26 -07002859// Same as above but for the legacy stats implementation.
2860TEST_P(PeerConnectionIntegrationTest,
2861 GetStatsForUnsignaledStreamWithOldStatsApi) {
2862 ASSERT_TRUE(CreatePeerConnectionWrappers());
2863 ConnectFakeSignaling();
2864 caller()->AddAudioTrack();
2865 // Remove SSRCs and MSIDs from the received offer SDP.
2866 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2867 caller()->CreateAndSetAndSignalOffer();
2868 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2869
2870 // Note that, since the old stats implementation associates SSRCs with tracks
2871 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2872 // associated track ID. So we can't use the track "selector" argument.
2873 //
2874 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2875 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002876 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002877 kDefaultTimeout);
2878}
2879
zhihuangf8164932017-05-19 13:09:47 -07002880// Test that we can successfully get the media related stats (audio level
2881// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002882TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002883 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2884 ASSERT_TRUE(CreatePeerConnectionWrappers());
2885 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002886 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002887 // Remove SSRCs and MSIDs from the received offer SDP.
2888 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2889 caller()->CreateAndSetAndSignalOffer();
2890 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002891 MediaExpectations media_expectations;
2892 media_expectations.CalleeExpectsSomeAudio(1);
2893 media_expectations.CalleeExpectsSomeVideo(1);
2894 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002895
2896 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2897 callee()->NewGetStats();
2898 ASSERT_NE(nullptr, report);
2899
2900 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2901 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2902 ASSERT_GE(audio_index, 0);
2903 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002904}
2905
deadbeef4e2deab2017-09-20 13:56:21 -07002906// Helper for test below.
2907void ModifySsrcs(cricket::SessionDescription* desc) {
2908 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002909 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002910 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002911 for (uint32_t& ssrc : stream.ssrcs) {
2912 ssrc = rtc::CreateRandomId();
2913 }
2914 }
2915 }
2916}
2917
2918// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2919// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2920// This should result in two "RTCInboundRTPStreamStats", but only one
2921// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2922// being reset to 0 once the SSRC change occurs.
2923//
2924// Regression test for this bug:
2925// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2926//
2927// The bug causes the track stats to only represent one of the two streams:
2928// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2929// that the track stat counters would reset to 0 when the new stream is
2930// received, and a 50% chance that they'll stop updating (while
2931// "concealed_samples" continues increasing, due to silence being generated for
2932// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002933TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002934 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002935 ASSERT_TRUE(CreatePeerConnectionWrappers());
2936 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002937 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002938 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2939 // that doesn't signal SSRCs (from the callee's perspective).
2940 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2941 caller()->CreateAndSetAndSignalOffer();
2942 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2943 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002944 {
2945 MediaExpectations media_expectations;
2946 media_expectations.CalleeExpectsSomeAudio(50);
2947 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2948 }
deadbeef4e2deab2017-09-20 13:56:21 -07002949 // Some audio frames were received, so we should have nonzero "samples
2950 // received" for the track.
2951 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2952 callee()->NewGetStats();
2953 ASSERT_NE(nullptr, report);
2954 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2955 ASSERT_EQ(1U, track_stats.size());
2956 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2957 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2958 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2959
2960 // Create a new offer and munge it to cause the caller to use a new SSRC.
2961 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2962 caller()->CreateAndSetAndSignalOffer();
2963 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2964 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2965 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002966 {
2967 MediaExpectations media_expectations;
2968 media_expectations.CalleeExpectsSomeAudio(25);
2969 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2970 }
deadbeef4e2deab2017-09-20 13:56:21 -07002971
2972 report = callee()->NewGetStats();
2973 ASSERT_NE(nullptr, report);
2974 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2975 ASSERT_EQ(1U, track_stats.size());
2976 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2977 // The "total samples received" stat should only be greater than it was
2978 // before.
2979 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2980 // Right now, the new SSRC will cause the counters to reset to 0.
2981 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2982
2983 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002984 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002985 // good sign that we're seeing stats from the old stream that's no longer
2986 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002987 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002988 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2989 EXPECT_LT(*track_stats[0]->concealed_samples,
2990 *track_stats[0]->total_samples_received *
2991 kAcceptableConcealedSamplesPercentage);
2992
2993 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2994 // sanity check that the SSRC really changed.
2995 // TODO(deadbeef): This isn't working right now, because we're not returning
2996 // *any* stats for the inactive stream. Uncomment when the bug is completely
2997 // fixed.
2998 // auto inbound_stream_stats =
2999 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3000 // ASSERT_EQ(2U, inbound_stream_stats.size());
3001}
3002
deadbeef1dcb1642017-03-29 21:08:16 -07003003// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003004TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003005 PeerConnectionFactory::Options dtls_10_options;
3006 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3007 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3008 dtls_10_options));
3009 ConnectFakeSignaling();
3010 // Do normal offer/answer and wait for some frames to be received in each
3011 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003012 caller()->AddAudioVideoTracks();
3013 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003014 caller()->CreateAndSetAndSignalOffer();
3015 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003016 MediaExpectations media_expectations;
3017 media_expectations.ExpectBidirectionalAudioAndVideo();
3018 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003019}
3020
3021// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003022TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003023 PeerConnectionFactory::Options dtls_10_options;
3024 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3025 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3026 dtls_10_options));
3027 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003028 caller()->AddAudioVideoTracks();
3029 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003030 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003031 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003032 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003033 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003034 kDefaultTimeout);
3035 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003036 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003037 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00003038 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003039 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3040 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003041}
3042
3043// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003044TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003045 PeerConnectionFactory::Options dtls_12_options;
3046 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3047 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3048 dtls_12_options));
3049 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003050 caller()->AddAudioVideoTracks();
3051 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003052 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003053 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003054 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003055 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003056 kDefaultTimeout);
3057 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003058 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003059 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00003060 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003061 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3062 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003063}
3064
3065// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3066// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003067TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003068 PeerConnectionFactory::Options caller_options;
3069 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3070 PeerConnectionFactory::Options callee_options;
3071 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3072 ASSERT_TRUE(
3073 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3074 ConnectFakeSignaling();
3075 // Do normal offer/answer and wait for some frames to be received in each
3076 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003077 caller()->AddAudioVideoTracks();
3078 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003079 caller()->CreateAndSetAndSignalOffer();
3080 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003081 MediaExpectations media_expectations;
3082 media_expectations.ExpectBidirectionalAudioAndVideo();
3083 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003084}
3085
3086// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3087// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003088TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003089 PeerConnectionFactory::Options caller_options;
3090 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3091 PeerConnectionFactory::Options callee_options;
3092 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3093 ASSERT_TRUE(
3094 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3095 ConnectFakeSignaling();
3096 // Do normal offer/answer and wait for some frames to be received in each
3097 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003098 caller()->AddAudioVideoTracks();
3099 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003100 caller()->CreateAndSetAndSignalOffer();
3101 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003102 MediaExpectations media_expectations;
3103 media_expectations.ExpectBidirectionalAudioAndVideo();
3104 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003105}
3106
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003107// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3108// works as expected; the cipher should only be used if enabled by both sides.
3109TEST_P(PeerConnectionIntegrationTest,
3110 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3111 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003112 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003113 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003114 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3115 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003116 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3117 TestNegotiatedCipherSuite(caller_options, callee_options,
3118 expected_cipher_suite);
3119}
3120
3121TEST_P(PeerConnectionIntegrationTest,
3122 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3123 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003124 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3125 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003126 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003127 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003128 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3129 TestNegotiatedCipherSuite(caller_options, callee_options,
3130 expected_cipher_suite);
3131}
3132
3133TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3134 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003135 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003136 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003137 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003138 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3139 TestNegotiatedCipherSuite(caller_options, callee_options,
3140 expected_cipher_suite);
3141}
3142
deadbeef1dcb1642017-03-29 21:08:16 -07003143// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003144TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003145 bool local_gcm_enabled = false;
3146 bool remote_gcm_enabled = false;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003147 bool aes_ctr_enabled = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003148 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3149 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003150 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003151}
3152
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003153// Test that a GCM cipher is used if both ends support it and non-GCM is
3154// disabled.
3155TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenOnlyGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003156 bool local_gcm_enabled = true;
3157 bool remote_gcm_enabled = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003158 bool aes_ctr_enabled = false;
deadbeef1dcb1642017-03-29 21:08:16 -07003159 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3160 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003161 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003162}
3163
deadbeef7914b8c2017-04-21 03:23:33 -07003164// Verify that media can be transmitted end-to-end when GCM crypto suites are
3165// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3166// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3167// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003168TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003169 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003170 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003171 gcm_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher = false;
deadbeef7914b8c2017-04-21 03:23:33 -07003172 ASSERT_TRUE(
3173 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3174 ConnectFakeSignaling();
3175 // Do normal offer/answer and wait for some frames to be received in each
3176 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003177 caller()->AddAudioVideoTracks();
3178 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003179 caller()->CreateAndSetAndSignalOffer();
3180 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003181 MediaExpectations media_expectations;
3182 media_expectations.ExpectBidirectionalAudioAndVideo();
3183 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003184}
3185
deadbeef1dcb1642017-03-29 21:08:16 -07003186// This test sets up a call between two parties with audio, video and an RTP
3187// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003188TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003189 PeerConnectionInterface::RTCConfiguration rtc_config;
3190 rtc_config.enable_rtp_data_channel = true;
3191 rtc_config.enable_dtls_srtp = false;
3192 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003193 ConnectFakeSignaling();
3194 // Expect that data channel created on caller side will show up for callee as
3195 // well.
3196 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003197 caller()->AddAudioVideoTracks();
3198 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003199 caller()->CreateAndSetAndSignalOffer();
3200 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3201 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003202 MediaExpectations media_expectations;
3203 media_expectations.ExpectBidirectionalAudioAndVideo();
3204 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003205 ASSERT_NE(nullptr, caller()->data_channel());
3206 ASSERT_NE(nullptr, callee()->data_channel());
3207 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3208 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3209
3210 // Ensure data can be sent in both directions.
3211 std::string data = "hello world";
3212 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3213 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3214 kDefaultTimeout);
3215 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3216 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3217 kDefaultTimeout);
3218}
3219
3220// Ensure that an RTP data channel is signaled as closed for the caller when
3221// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003222TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003223 RtpDataChannelSignaledClosedInCalleeOffer) {
3224 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003225 PeerConnectionInterface::RTCConfiguration rtc_config;
3226 rtc_config.enable_rtp_data_channel = true;
3227 rtc_config.enable_dtls_srtp = false;
3228 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003229 ConnectFakeSignaling();
3230 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003231 caller()->AddAudioVideoTracks();
3232 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003233 caller()->CreateAndSetAndSignalOffer();
3234 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3235 ASSERT_NE(nullptr, caller()->data_channel());
3236 ASSERT_NE(nullptr, callee()->data_channel());
3237 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3238 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3239
3240 // Close the data channel on the callee, and do an updated offer/answer.
3241 callee()->data_channel()->Close();
3242 callee()->CreateAndSetAndSignalOffer();
3243 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3244 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3245 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3246}
3247
3248// Tests that data is buffered in an RTP data channel until an observer is
3249// registered for it.
3250//
3251// NOTE: RTP data channels can receive data before the underlying
3252// transport has detected that a channel is writable and thus data can be
3253// received before the data channel state changes to open. That is hard to test
3254// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003255TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003256 DataBufferedUntilRtpDataChannelObserverRegistered) {
3257 // Use fake clock and simulated network delay so that we predictably can wait
3258 // until an SCTP message has been delivered without "sleep()"ing.
3259 rtc::ScopedFakeClock fake_clock;
3260 // Some things use a time of "0" as a special value, so we need to start out
3261 // the fake clock at a nonzero time.
3262 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003263 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003264 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3265 virtual_socket_server()->UpdateDelayDistribution();
3266
Niels Möllerf06f9232018-08-07 12:32:18 +02003267 PeerConnectionInterface::RTCConfiguration rtc_config;
3268 rtc_config.enable_rtp_data_channel = true;
3269 rtc_config.enable_dtls_srtp = false;
3270 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003271 ConnectFakeSignaling();
3272 caller()->CreateDataChannel();
3273 caller()->CreateAndSetAndSignalOffer();
3274 ASSERT_TRUE(caller()->data_channel() != nullptr);
3275 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3276 kDefaultTimeout, fake_clock);
3277 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3278 kDefaultTimeout, fake_clock);
3279 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3280 callee()->data_channel()->state(), kDefaultTimeout,
3281 fake_clock);
3282
3283 // Unregister the observer which is normally automatically registered.
3284 callee()->data_channel()->UnregisterObserver();
3285 // Send data and advance fake clock until it should have been received.
3286 std::string data = "hello world";
3287 caller()->data_channel()->Send(DataBuffer(data));
3288 SIMULATED_WAIT(false, 50, fake_clock);
3289
3290 // Attach data channel and expect data to be received immediately. Note that
3291 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3292 // further, but data can be received even if the callback is asynchronous.
3293 MockDataChannelObserver new_observer(callee()->data_channel());
3294 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3295 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003296 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3297 // If this is not done a DCHECK can be hit in ports.cc, because a large
3298 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07003299 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07003300}
3301
3302// This test sets up a call between two parties with audio, video and but only
3303// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003304TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003305 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3306 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003307 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003308 rtc_config_1.enable_dtls_srtp = false;
3309 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3310 rtc_config_2.enable_dtls_srtp = false;
3311 rtc_config_2.enable_dtls_srtp = false;
3312 ASSERT_TRUE(
3313 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003314 ConnectFakeSignaling();
3315 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003316 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003317 caller()->AddAudioVideoTracks();
3318 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003319 caller()->CreateAndSetAndSignalOffer();
3320 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3321 // The caller should still have a data channel, but it should be closed, and
3322 // one should ever have been created for the callee.
3323 EXPECT_TRUE(caller()->data_channel() != nullptr);
3324 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3325 EXPECT_EQ(nullptr, callee()->data_channel());
3326}
3327
3328// This test sets up a call between two parties with audio, and video. When
3329// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003330TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003331 PeerConnectionInterface::RTCConfiguration rtc_config;
3332 rtc_config.enable_rtp_data_channel = true;
3333 rtc_config.enable_dtls_srtp = false;
3334 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003335 ConnectFakeSignaling();
3336 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003337 caller()->AddAudioVideoTracks();
3338 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003339 caller()->CreateAndSetAndSignalOffer();
3340 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3341 // Create data channel and do new offer and answer.
3342 caller()->CreateDataChannel();
3343 caller()->CreateAndSetAndSignalOffer();
3344 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3345 ASSERT_NE(nullptr, caller()->data_channel());
3346 ASSERT_NE(nullptr, callee()->data_channel());
3347 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3348 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3349 // Ensure data can be sent in both directions.
3350 std::string data = "hello world";
3351 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3352 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3353 kDefaultTimeout);
3354 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3355 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3356 kDefaultTimeout);
3357}
3358
3359#ifdef HAVE_SCTP
3360
3361// This test sets up a call between two parties with audio, video and an SCTP
3362// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003363TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003364 ASSERT_TRUE(CreatePeerConnectionWrappers());
3365 ConnectFakeSignaling();
3366 // Expect that data channel created on caller side will show up for callee as
3367 // well.
3368 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003369 caller()->AddAudioVideoTracks();
3370 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003371 caller()->CreateAndSetAndSignalOffer();
3372 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3373 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003374 MediaExpectations media_expectations;
3375 media_expectations.ExpectBidirectionalAudioAndVideo();
3376 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003377 // Caller data channel should already exist (it created one). Callee data
3378 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3379 ASSERT_NE(nullptr, caller()->data_channel());
3380 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3381 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3382 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3383
3384 // Ensure data can be sent in both directions.
3385 std::string data = "hello world";
3386 caller()->data_channel()->Send(DataBuffer(data));
3387 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3388 kDefaultTimeout);
3389 callee()->data_channel()->Send(DataBuffer(data));
3390 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3391 kDefaultTimeout);
3392}
3393
3394// Ensure that when the callee closes an SCTP data channel, the closing
3395// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003396TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003397 // Same procedure as above test.
3398 ASSERT_TRUE(CreatePeerConnectionWrappers());
3399 ConnectFakeSignaling();
3400 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003401 caller()->AddAudioVideoTracks();
3402 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003403 caller()->CreateAndSetAndSignalOffer();
3404 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3405 ASSERT_NE(nullptr, caller()->data_channel());
3406 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3407 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3408 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3409
3410 // Close the data channel on the callee side, and wait for it to reach the
3411 // "closed" state on both sides.
3412 callee()->data_channel()->Close();
3413 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3414 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3415}
3416
Seth Hampson2f0d7022018-02-20 11:54:42 -08003417TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003418 ASSERT_TRUE(CreatePeerConnectionWrappers());
3419 ConnectFakeSignaling();
3420 webrtc::DataChannelInit init;
3421 init.id = 53;
3422 init.maxRetransmits = 52;
3423 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003424 caller()->AddAudioVideoTracks();
3425 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003426 caller()->CreateAndSetAndSignalOffer();
3427 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003428 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3429 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003430 // Since "negotiated" is false, the "id" parameter should be ignored.
3431 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003432 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3433 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3434 EXPECT_FALSE(callee()->data_channel()->negotiated());
3435}
3436
deadbeef1dcb1642017-03-29 21:08:16 -07003437// Test usrsctp's ability to process unordered data stream, where data actually
3438// arrives out of order using simulated delays. Previously there have been some
3439// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003440TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003441 // Introduce random network delays.
3442 // Otherwise it's not a true "unordered" test.
3443 virtual_socket_server()->set_delay_mean(20);
3444 virtual_socket_server()->set_delay_stddev(5);
3445 virtual_socket_server()->UpdateDelayDistribution();
3446 // Normal procedure, but with unordered data channel config.
3447 ASSERT_TRUE(CreatePeerConnectionWrappers());
3448 ConnectFakeSignaling();
3449 webrtc::DataChannelInit init;
3450 init.ordered = false;
3451 caller()->CreateDataChannel(&init);
3452 caller()->CreateAndSetAndSignalOffer();
3453 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3454 ASSERT_NE(nullptr, caller()->data_channel());
3455 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3456 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3457 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3458
3459 static constexpr int kNumMessages = 100;
3460 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3461 static constexpr size_t kMaxMessageSize = 4096;
3462 // Create and send random messages.
3463 std::vector<std::string> sent_messages;
3464 for (int i = 0; i < kNumMessages; ++i) {
3465 size_t length =
3466 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3467 std::string message;
3468 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3469 caller()->data_channel()->Send(DataBuffer(message));
3470 callee()->data_channel()->Send(DataBuffer(message));
3471 sent_messages.push_back(message);
3472 }
3473
3474 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003475 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003476 caller()->data_observer()->received_message_count(),
3477 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003478 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003479 callee()->data_observer()->received_message_count(),
3480 kDefaultTimeout);
3481
3482 // Sort and compare to make sure none of the messages were corrupted.
3483 std::vector<std::string> caller_received_messages =
3484 caller()->data_observer()->messages();
3485 std::vector<std::string> callee_received_messages =
3486 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003487 absl::c_sort(sent_messages);
3488 absl::c_sort(caller_received_messages);
3489 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003490 EXPECT_EQ(sent_messages, caller_received_messages);
3491 EXPECT_EQ(sent_messages, callee_received_messages);
3492}
3493
3494// This test sets up a call between two parties with audio, and video. When
3495// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003496TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003497 ASSERT_TRUE(CreatePeerConnectionWrappers());
3498 ConnectFakeSignaling();
3499 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003500 caller()->AddAudioVideoTracks();
3501 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003502 caller()->CreateAndSetAndSignalOffer();
3503 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3504 // Create data channel and do new offer and answer.
3505 caller()->CreateDataChannel();
3506 caller()->CreateAndSetAndSignalOffer();
3507 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3508 // Caller data channel should already exist (it created one). Callee data
3509 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3510 ASSERT_NE(nullptr, caller()->data_channel());
3511 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3512 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3513 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3514 // Ensure data can be sent in both directions.
3515 std::string data = "hello world";
3516 caller()->data_channel()->Send(DataBuffer(data));
3517 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3518 kDefaultTimeout);
3519 callee()->data_channel()->Send(DataBuffer(data));
3520 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3521 kDefaultTimeout);
3522}
3523
deadbeef7914b8c2017-04-21 03:23:33 -07003524// Set up a connection initially just using SCTP data channels, later upgrading
3525// to audio/video, ensuring frames are received end-to-end. Effectively the
3526// inverse of the test above.
3527// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003528TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003529 ASSERT_TRUE(CreatePeerConnectionWrappers());
3530 ConnectFakeSignaling();
3531 // Do initial offer/answer with just data channel.
3532 caller()->CreateDataChannel();
3533 caller()->CreateAndSetAndSignalOffer();
3534 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3535 // Wait until data can be sent over the data channel.
3536 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3537 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3538 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3539
3540 // Do subsequent offer/answer with two-way audio and video. Audio and video
3541 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003542 caller()->AddAudioVideoTracks();
3543 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003544 caller()->CreateAndSetAndSignalOffer();
3545 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003546 MediaExpectations media_expectations;
3547 media_expectations.ExpectBidirectionalAudioAndVideo();
3548 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003549}
3550
deadbeef8b7e9ad2017-05-25 09:38:55 -07003551static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003552 cricket::SctpDataContentDescription* dcd_offer =
3553 GetFirstSctpDataContentDescription(desc);
Steve Antonb1c1de12017-12-21 15:14:30 -08003554 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003555 dcd_offer->set_use_sctpmap(false);
3556 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3557}
3558
3559// Test that the data channel works when a spec-compliant SCTP m= section is
3560// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3561// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003562TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003563 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3564 ASSERT_TRUE(CreatePeerConnectionWrappers());
3565 ConnectFakeSignaling();
3566 caller()->CreateDataChannel();
3567 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3568 caller()->CreateAndSetAndSignalOffer();
3569 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3570 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3571 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3572 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3573
3574 // Ensure data can be sent in both directions.
3575 std::string data = "hello world";
3576 caller()->data_channel()->Send(DataBuffer(data));
3577 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3578 kDefaultTimeout);
3579 callee()->data_channel()->Send(DataBuffer(data));
3580 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3581 kDefaultTimeout);
3582}
3583
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003584// Tests that the datagram transport to SCTP fallback works correctly when
3585// datagram transport negotiation fails.
3586TEST_P(PeerConnectionIntegrationTest,
3587 DatagramTransportDataChannelFallbackToSctp) {
3588 PeerConnectionInterface::RTCConfiguration rtc_config;
3589 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3590 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3591 rtc_config.use_datagram_transport_for_data_channels = true;
3592
3593 // Configure one endpoint to use datagram transport for data channels while
3594 // the other does not.
3595 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3596 rtc_config, RTCConfiguration(),
3597 loopback_media_transports()->first_factory(), nullptr));
3598 ConnectFakeSignaling();
3599
3600 // The caller offers a data channel using either datagram transport or SCTP.
3601 caller()->CreateDataChannel();
3602 caller()->AddAudioVideoTracks();
3603 callee()->AddAudioVideoTracks();
3604 caller()->CreateAndSetAndSignalOffer();
3605 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3606
3607 // Negotiation should fallback to SCTP, allowing the data channel to be
3608 // established.
3609 ASSERT_NE(nullptr, caller()->data_channel());
3610 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3611 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3612 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3613
3614 // Ensure data can be sent in both directions.
3615 std::string data = "hello world";
3616 caller()->data_channel()->Send(DataBuffer(data));
3617 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3618 kDefaultTimeout);
3619 callee()->data_channel()->Send(DataBuffer(data));
3620 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3621 kDefaultTimeout);
3622
3623 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3624 MediaExpectations media_expectations;
3625 media_expectations.ExpectBidirectionalAudioAndVideo();
3626 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3627}
3628
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07003629// Tests that the data channel transport works correctly when datagram transport
3630// negotiation succeeds and does not fall back to SCTP.
3631TEST_P(PeerConnectionIntegrationTest,
3632 DatagramTransportDataChannelDoesNotFallbackToSctp) {
3633 PeerConnectionInterface::RTCConfiguration rtc_config;
3634 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3635 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3636 rtc_config.use_datagram_transport_for_data_channels = true;
3637
3638 // Configure one endpoint to use datagram transport for data channels while
3639 // the other does not.
3640 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3641 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3642 loopback_media_transports()->second_factory()));
3643 ConnectFakeSignaling();
3644
3645 // The caller offers a data channel using either datagram transport or SCTP.
3646 caller()->CreateDataChannel();
3647 caller()->AddAudioVideoTracks();
3648 callee()->AddAudioVideoTracks();
3649 caller()->CreateAndSetAndSignalOffer();
3650 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3651
3652 // Ensure that the data channel transport is ready.
3653 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3654 loopback_media_transports()->FlushAsyncInvokes();
3655
3656 // Negotiation should succeed, allowing the data channel to be established.
3657 ASSERT_NE(nullptr, caller()->data_channel());
3658 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3659 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3660 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3661
3662 // Ensure data can be sent in both directions.
3663 std::string data = "hello world";
3664 caller()->data_channel()->Send(DataBuffer(data));
3665 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3666 kDefaultTimeout);
3667 callee()->data_channel()->Send(DataBuffer(data));
3668 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3669 kDefaultTimeout);
3670
3671 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3672 MediaExpectations media_expectations;
3673 media_expectations.ExpectBidirectionalAudioAndVideo();
3674 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3675}
3676
Bjorn A Mellem8e1343a2019-09-30 15:12:47 -07003677TEST_P(PeerConnectionIntegrationTest,
3678 DatagramTransportDataChannelWithMediaOnCaller) {
3679 // Configure the caller to attempt use of datagram transport for media and
3680 // data channels.
3681 PeerConnectionInterface::RTCConfiguration offerer_config;
3682 offerer_config.rtcp_mux_policy =
3683 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3684 offerer_config.bundle_policy =
3685 PeerConnectionInterface::kBundlePolicyMaxBundle;
3686 offerer_config.use_datagram_transport_for_data_channels = true;
3687 offerer_config.use_datagram_transport = true;
3688
3689 // Configure the callee to only use datagram transport for data channels.
3690 PeerConnectionInterface::RTCConfiguration answerer_config;
3691 answerer_config.rtcp_mux_policy =
3692 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3693 answerer_config.bundle_policy =
3694 PeerConnectionInterface::kBundlePolicyMaxBundle;
3695 answerer_config.use_datagram_transport_for_data_channels = true;
3696
3697 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3698 offerer_config, answerer_config,
3699 loopback_media_transports()->first_factory(),
3700 loopback_media_transports()->second_factory()));
3701 ConnectFakeSignaling();
3702
3703 // Offer both media and data.
3704 caller()->AddAudioVideoTracks();
3705 callee()->AddAudioVideoTracks();
3706 caller()->CreateDataChannel();
3707 caller()->CreateAndSetAndSignalOffer();
3708 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3709
3710 // Ensure that the data channel transport is ready.
3711 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3712 loopback_media_transports()->FlushAsyncInvokes();
3713
3714 ASSERT_NE(nullptr, caller()->data_channel());
3715 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3716 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3717 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3718
3719 // Both endpoints should agree to use datagram transport for data channels.
3720 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
3721 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
3722
3723 // Ensure data can be sent in both directions.
3724 std::string data = "hello world";
3725 caller()->data_channel()->Send(DataBuffer(data));
3726 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3727 kDefaultTimeout);
3728 callee()->data_channel()->Send(DataBuffer(data));
3729 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3730 kDefaultTimeout);
3731
3732 // Media flow should not be impacted.
3733 MediaExpectations media_expectations;
3734 media_expectations.ExpectBidirectionalAudioAndVideo();
3735 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3736}
3737
3738TEST_P(PeerConnectionIntegrationTest,
3739 DatagramTransportMediaWithDataChannelOnCaller) {
3740 // Configure the caller to attempt use of datagram transport for media and
3741 // data channels.
3742 PeerConnectionInterface::RTCConfiguration offerer_config;
3743 offerer_config.rtcp_mux_policy =
3744 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3745 offerer_config.bundle_policy =
3746 PeerConnectionInterface::kBundlePolicyMaxBundle;
3747 offerer_config.use_datagram_transport_for_data_channels = true;
3748 offerer_config.use_datagram_transport = true;
3749
3750 // Configure the callee to only use datagram transport for media.
3751 PeerConnectionInterface::RTCConfiguration answerer_config;
3752 answerer_config.rtcp_mux_policy =
3753 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3754 answerer_config.bundle_policy =
3755 PeerConnectionInterface::kBundlePolicyMaxBundle;
3756 answerer_config.use_datagram_transport = true;
3757
3758 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3759 offerer_config, answerer_config,
3760 loopback_media_transports()->first_factory(),
3761 loopback_media_transports()->second_factory()));
3762 ConnectFakeSignaling();
3763
3764 // Offer both media and data.
3765 caller()->AddAudioVideoTracks();
3766 callee()->AddAudioVideoTracks();
3767 caller()->CreateDataChannel();
3768 caller()->CreateAndSetAndSignalOffer();
3769 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3770
3771 // Ensure that the data channel transport is ready.
3772 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3773 loopback_media_transports()->FlushAsyncInvokes();
3774
3775 ASSERT_NE(nullptr, caller()->data_channel());
3776 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3777 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3778 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3779
3780 // Both endpoints should agree to use SCTP for data channels.
3781 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
3782 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
3783
3784 // Ensure data can be sent in both directions.
3785 std::string data = "hello world";
3786 caller()->data_channel()->Send(DataBuffer(data));
3787 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3788 kDefaultTimeout);
3789 callee()->data_channel()->Send(DataBuffer(data));
3790 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3791 kDefaultTimeout);
3792
3793 // Media flow should not be impacted.
3794 MediaExpectations media_expectations;
3795 media_expectations.ExpectBidirectionalAudioAndVideo();
3796 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3797}
3798
3799TEST_P(PeerConnectionIntegrationTest,
3800 DatagramTransportDataChannelWithMediaOnCallee) {
3801 // Configure the caller to attempt use of datagram transport for data
3802 // channels.
3803 PeerConnectionInterface::RTCConfiguration offerer_config;
3804 offerer_config.rtcp_mux_policy =
3805 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3806 offerer_config.bundle_policy =
3807 PeerConnectionInterface::kBundlePolicyMaxBundle;
3808 offerer_config.use_datagram_transport_for_data_channels = true;
3809
3810 // Configure the callee to use datagram transport for data channels and media.
3811 PeerConnectionInterface::RTCConfiguration answerer_config;
3812 answerer_config.rtcp_mux_policy =
3813 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3814 answerer_config.bundle_policy =
3815 PeerConnectionInterface::kBundlePolicyMaxBundle;
3816 answerer_config.use_datagram_transport_for_data_channels = true;
3817 answerer_config.use_datagram_transport = true;
3818
3819 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3820 offerer_config, answerer_config,
3821 loopback_media_transports()->first_factory(),
3822 loopback_media_transports()->second_factory()));
3823 ConnectFakeSignaling();
3824
3825 // Offer both media and data.
3826 caller()->AddAudioVideoTracks();
3827 callee()->AddAudioVideoTracks();
3828 caller()->CreateDataChannel();
3829 caller()->CreateAndSetAndSignalOffer();
3830 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3831
3832 // Ensure that the data channel transport is ready.
3833 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3834 loopback_media_transports()->FlushAsyncInvokes();
3835
3836 ASSERT_NE(nullptr, caller()->data_channel());
3837 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3838 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3839 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3840
3841 // Both endpoints should agree to use datagram transport for data channels.
3842 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
3843 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
3844
3845 // Ensure data can be sent in both directions.
3846 std::string data = "hello world";
3847 caller()->data_channel()->Send(DataBuffer(data));
3848 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3849 kDefaultTimeout);
3850 callee()->data_channel()->Send(DataBuffer(data));
3851 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3852 kDefaultTimeout);
3853
3854 // Media flow should not be impacted.
3855 MediaExpectations media_expectations;
3856 media_expectations.ExpectBidirectionalAudioAndVideo();
3857 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3858}
3859
3860TEST_P(PeerConnectionIntegrationTest,
3861 DatagramTransportMediaWithDataChannelOnCallee) {
3862 // Configure the caller to attempt use of datagram transport for media.
3863 PeerConnectionInterface::RTCConfiguration offerer_config;
3864 offerer_config.rtcp_mux_policy =
3865 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3866 offerer_config.bundle_policy =
3867 PeerConnectionInterface::kBundlePolicyMaxBundle;
3868 offerer_config.use_datagram_transport = true;
3869
3870 // Configure the callee to only use datagram transport for media and data
3871 // channels.
3872 PeerConnectionInterface::RTCConfiguration answerer_config;
3873 answerer_config.rtcp_mux_policy =
3874 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3875 answerer_config.bundle_policy =
3876 PeerConnectionInterface::kBundlePolicyMaxBundle;
3877 answerer_config.use_datagram_transport = true;
3878 answerer_config.use_datagram_transport_for_data_channels = true;
3879
3880 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3881 offerer_config, answerer_config,
3882 loopback_media_transports()->first_factory(),
3883 loopback_media_transports()->second_factory()));
3884 ConnectFakeSignaling();
3885
3886 // Offer both media and data.
3887 caller()->AddAudioVideoTracks();
3888 callee()->AddAudioVideoTracks();
3889 caller()->CreateDataChannel();
3890 caller()->CreateAndSetAndSignalOffer();
3891 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3892
3893 // Ensure that the data channel transport is ready.
3894 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3895 loopback_media_transports()->FlushAsyncInvokes();
3896
3897 ASSERT_NE(nullptr, caller()->data_channel());
3898 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3899 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3900 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3901
3902 // Both endpoints should agree to use SCTP for data channels.
3903 EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
3904 EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
3905
3906 // Ensure data can be sent in both directions.
3907 std::string data = "hello world";
3908 caller()->data_channel()->Send(DataBuffer(data));
3909 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3910 kDefaultTimeout);
3911 callee()->data_channel()->Send(DataBuffer(data));
3912 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3913 kDefaultTimeout);
3914
3915 // Media flow should not be impacted.
3916 MediaExpectations media_expectations;
3917 media_expectations.ExpectBidirectionalAudioAndVideo();
3918 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3919}
3920
3921TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelAndMedia) {
3922 // Configure the caller to use datagram transport for data channels and media.
3923 PeerConnectionInterface::RTCConfiguration offerer_config;
3924 offerer_config.rtcp_mux_policy =
3925 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3926 offerer_config.bundle_policy =
3927 PeerConnectionInterface::kBundlePolicyMaxBundle;
3928 offerer_config.use_datagram_transport_for_data_channels = true;
3929 offerer_config.use_datagram_transport = true;
3930
3931 // Configure the callee to use datagram transport for data channels and media.
3932 PeerConnectionInterface::RTCConfiguration answerer_config;
3933 answerer_config.rtcp_mux_policy =
3934 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3935 answerer_config.bundle_policy =
3936 PeerConnectionInterface::kBundlePolicyMaxBundle;
3937 answerer_config.use_datagram_transport_for_data_channels = true;
3938 answerer_config.use_datagram_transport = true;
3939
3940 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3941 offerer_config, answerer_config,
3942 loopback_media_transports()->first_factory(),
3943 loopback_media_transports()->second_factory()));
3944 ConnectFakeSignaling();
3945
3946 // Offer both media and data.
3947 caller()->AddAudioVideoTracks();
3948 callee()->AddAudioVideoTracks();
3949 caller()->CreateDataChannel();
3950 caller()->CreateAndSetAndSignalOffer();
3951 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3952
3953 // Ensure that the data channel transport is ready.
3954 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3955 loopback_media_transports()->FlushAsyncInvokes();
3956
3957 ASSERT_NE(nullptr, caller()->data_channel());
3958 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3959 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3960 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3961
3962 // Both endpoints should agree to use datagram transport for data channels.
3963 EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
3964 EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
3965
3966 // Ensure data can be sent in both directions.
3967 std::string data = "hello world";
3968 caller()->data_channel()->Send(DataBuffer(data));
3969 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3970 kDefaultTimeout);
3971 callee()->data_channel()->Send(DataBuffer(data));
3972 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3973 kDefaultTimeout);
3974
3975 // Media flow should not be impacted.
3976 MediaExpectations media_expectations;
3977 media_expectations.ExpectBidirectionalAudioAndVideo();
3978 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3979}
3980
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07003981// Tests that data channels use SCTP instead of datagram transport if datagram
3982// transport is configured in receive-only mode on the caller.
3983TEST_P(PeerConnectionIntegrationTest,
3984 DatagramTransportDataChannelReceiveOnlyOnCallerUsesSctp) {
3985 PeerConnectionInterface::RTCConfiguration rtc_config;
3986 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3987 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3988 rtc_config.use_datagram_transport_for_data_channels = true;
3989 rtc_config.use_datagram_transport_for_data_channels_receive_only = true;
3990
3991 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3992 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3993 loopback_media_transports()->second_factory()));
3994 ConnectFakeSignaling();
3995
3996 // The caller should offer a data channel using SCTP.
3997 caller()->CreateDataChannel();
3998 caller()->AddAudioVideoTracks();
3999 callee()->AddAudioVideoTracks();
4000 caller()->CreateAndSetAndSignalOffer();
4001 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4002
4003 ASSERT_NE(nullptr, caller()->data_channel());
4004 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4005 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4006 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4007
4008 // SCTP transports should be present, since they are in use.
4009 EXPECT_NE(caller()->pc()->GetSctpTransport(), nullptr);
4010 EXPECT_NE(callee()->pc()->GetSctpTransport(), nullptr);
4011
4012 // Ensure data can be sent in both directions.
4013 std::string data = "hello world";
4014 caller()->data_channel()->Send(DataBuffer(data));
4015 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4016 kDefaultTimeout);
4017 callee()->data_channel()->Send(DataBuffer(data));
4018 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4019 kDefaultTimeout);
4020}
4021
deadbeef1dcb1642017-03-29 21:08:16 -07004022#endif // HAVE_SCTP
4023
Bjorn A Mellem7da4e562019-09-26 11:02:11 -07004024// Tests that a callee configured for receive-only use of datagram transport
4025// data channels accepts them on incoming calls.
4026TEST_P(PeerConnectionIntegrationTest,
4027 DatagramTransportDataChannelReceiveOnlyOnCallee) {
4028 PeerConnectionInterface::RTCConfiguration offerer_config;
4029 offerer_config.rtcp_mux_policy =
4030 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4031 offerer_config.bundle_policy =
4032 PeerConnectionInterface::kBundlePolicyMaxBundle;
4033 offerer_config.use_datagram_transport_for_data_channels = true;
4034
4035 PeerConnectionInterface::RTCConfiguration answerer_config;
4036 answerer_config.rtcp_mux_policy =
4037 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4038 answerer_config.bundle_policy =
4039 PeerConnectionInterface::kBundlePolicyMaxBundle;
4040 answerer_config.use_datagram_transport_for_data_channels = true;
4041 answerer_config.use_datagram_transport_for_data_channels_receive_only = true;
4042
4043 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4044 offerer_config, answerer_config,
4045 loopback_media_transports()->first_factory(),
4046 loopback_media_transports()->second_factory()));
4047 ConnectFakeSignaling();
4048
4049 caller()->CreateDataChannel();
4050 caller()->CreateAndSetAndSignalOffer();
4051 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4052
4053 // Ensure that the data channel transport is ready.
4054 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4055 loopback_media_transports()->FlushAsyncInvokes();
4056
4057 ASSERT_NE(nullptr, caller()->data_channel());
4058 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4059 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4060 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4061
4062 // SCTP transports should not be present, since datagram transport is used.
4063 EXPECT_EQ(caller()->pc()->GetSctpTransport(), nullptr);
4064 EXPECT_EQ(callee()->pc()->GetSctpTransport(), nullptr);
4065
4066 // Ensure data can be sent in both directions.
4067 std::string data = "hello world";
4068 caller()->data_channel()->Send(DataBuffer(data));
4069 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4070 kDefaultTimeout);
4071 callee()->data_channel()->Send(DataBuffer(data));
4072 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4073 kDefaultTimeout);
4074}
4075
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004076// This test sets up a call between two parties with a datagram transport data
4077// channel.
4078TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelEndToEnd) {
4079 PeerConnectionInterface::RTCConfiguration rtc_config;
4080 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4081 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4082 rtc_config.use_datagram_transport_for_data_channels = true;
4083 rtc_config.enable_dtls_srtp = false;
4084 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4085 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4086 loopback_media_transports()->second_factory()));
4087 ConnectFakeSignaling();
4088
4089 // Expect that data channel created on caller side will show up for callee as
4090 // well.
4091 caller()->CreateDataChannel();
4092 caller()->CreateAndSetAndSignalOffer();
4093 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4094
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004095 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004096 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4097 loopback_media_transports()->FlushAsyncInvokes();
4098
4099 // Caller data channel should already exist (it created one). Callee data
4100 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4101 ASSERT_NE(nullptr, caller()->data_channel());
4102 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4103 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4104 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4105
4106 // Ensure data can be sent in both directions.
4107 std::string data = "hello world";
4108 caller()->data_channel()->Send(DataBuffer(data));
4109 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4110 kDefaultTimeout);
4111 callee()->data_channel()->Send(DataBuffer(data));
4112 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4113 kDefaultTimeout);
4114}
4115
Bjorn A Mellembc3eebc2019-09-23 14:53:54 -07004116// Tests that 'zero-rtt' data channel transports (which are ready-to-send as
4117// soon as they're created) work correctly.
4118TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelZeroRtt) {
4119 PeerConnectionInterface::RTCConfiguration rtc_config;
4120 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4121 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4122 rtc_config.use_datagram_transport_for_data_channels = true;
4123 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
4124 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4125 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4126 loopback_media_transports()->second_factory()));
4127 ConnectFakeSignaling();
4128
4129 // Ensure that the callee's media transport is ready-to-send immediately.
4130 // Note that only the callee can become writable in zero RTTs. The caller
4131 // must wait for the callee's answer.
4132 loopback_media_transports()->SetSecondStateAfterConnect(
4133 webrtc::MediaTransportState::kWritable);
4134 loopback_media_transports()->FlushAsyncInvokes();
4135
4136 // Expect that data channel created on caller side will show up for callee as
4137 // well.
4138 caller()->CreateDataChannel();
4139 caller()->CreateAndSetAndSignalOffer();
4140 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4141
4142 loopback_media_transports()->SetFirstState(
4143 webrtc::MediaTransportState::kWritable);
4144 loopback_media_transports()->FlushAsyncInvokes();
4145
4146 // Caller data channel should already exist (it created one). Callee data
4147 // channel may not exist yet, since negotiation happens in-band, not in SDP.
4148 ASSERT_NE(nullptr, caller()->data_channel());
4149 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4150 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4151 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4152
4153 // Ensure data can be sent in both directions.
4154 std::string data = "hello world";
4155 caller()->data_channel()->Send(DataBuffer(data));
4156 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
4157 kDefaultTimeout);
4158 callee()->data_channel()->Send(DataBuffer(data));
4159 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
4160 kDefaultTimeout);
4161}
4162
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004163// Ensures that when the callee closes a datagram transport data channel, the
4164// closing procedure results in the data channel being closed for the caller
4165// as well.
4166TEST_P(PeerConnectionIntegrationTest,
4167 DatagramTransportDataChannelCalleeCloses) {
4168 PeerConnectionInterface::RTCConfiguration rtc_config;
4169 rtc_config.use_datagram_transport_for_data_channels = true;
4170 rtc_config.enable_dtls_srtp = false;
4171 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4172 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4173 loopback_media_transports()->second_factory()));
4174 ConnectFakeSignaling();
4175
4176 // Create a data channel on the caller and signal it to the callee.
4177 caller()->CreateDataChannel();
4178 caller()->CreateAndSetAndSignalOffer();
4179 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4180
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004181 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004182 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4183 loopback_media_transports()->FlushAsyncInvokes();
4184
4185 // Data channels exist and open on both ends of the connection.
4186 ASSERT_NE(nullptr, caller()->data_channel());
4187 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4188 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
4189 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4190
4191 // Close the data channel on the callee side, and wait for it to reach the
4192 // "closed" state on both sides.
4193 callee()->data_channel()->Close();
4194 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
4195 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
4196}
4197
4198// Tests that datagram transport data channels can do in-band negotiation.
4199TEST_P(PeerConnectionIntegrationTest,
4200 DatagramTransportDataChannelConfigSentToOtherSide) {
4201 PeerConnectionInterface::RTCConfiguration rtc_config;
4202 rtc_config.use_datagram_transport_for_data_channels = true;
4203 rtc_config.enable_dtls_srtp = false;
4204 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4205 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4206 loopback_media_transports()->second_factory()));
4207 ConnectFakeSignaling();
4208
4209 // Create a data channel with a non-default configuration and signal it to the
4210 // callee.
4211 webrtc::DataChannelInit init;
4212 init.id = 53;
4213 init.maxRetransmits = 52;
4214 caller()->CreateDataChannel("data-channel", &init);
4215 caller()->CreateAndSetAndSignalOffer();
4216 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4217
Bjorn A Mellemfc604aa2019-09-24 14:59:21 -07004218 // Ensure that the data channel transport is ready.
Bjorn A Mellemb689af42019-08-21 10:44:59 -07004219 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4220 loopback_media_transports()->FlushAsyncInvokes();
4221
4222 // Ensure that the data channel exists on the callee with the correct
4223 // configuration.
4224 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
4225 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
4226 // Since "negotiate" is false, the "id" parameter is ignored.
4227 EXPECT_NE(init.id, callee()->data_channel()->id());
4228 EXPECT_EQ("data-channel", callee()->data_channel()->label());
4229 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
4230 EXPECT_FALSE(callee()->data_channel()->negotiated());
4231}
4232
4233TEST_P(PeerConnectionIntegrationTest,
4234 DatagramTransportDataChannelRejectedWithNoFallback) {
4235 PeerConnectionInterface::RTCConfiguration offerer_config;
4236 offerer_config.rtcp_mux_policy =
4237 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4238 offerer_config.bundle_policy =
4239 PeerConnectionInterface::kBundlePolicyMaxBundle;
4240 offerer_config.use_datagram_transport_for_data_channels = true;
4241 // Disabling DTLS precludes a fallback to SCTP.
4242 offerer_config.enable_dtls_srtp = false;
4243
4244 PeerConnectionInterface::RTCConfiguration answerer_config;
4245 answerer_config.rtcp_mux_policy =
4246 PeerConnectionInterface::kRtcpMuxPolicyRequire;
4247 answerer_config.bundle_policy =
4248 PeerConnectionInterface::kBundlePolicyMaxBundle;
4249 // Both endpoints must disable DTLS or SetRemoteDescription will fail.
4250 answerer_config.enable_dtls_srtp = false;
4251
4252 // Configure one endpoint to use datagram transport for data channels while
4253 // the other does not.
4254 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4255 offerer_config, answerer_config,
4256 loopback_media_transports()->first_factory(), nullptr));
4257 ConnectFakeSignaling();
4258
4259 // The caller offers a data channel using either datagram transport or SCTP.
4260 caller()->CreateDataChannel();
4261 caller()->AddAudioVideoTracks();
4262 callee()->AddAudioVideoTracks();
4263 caller()->CreateAndSetAndSignalOffer();
4264 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4265
4266 // Caller data channel should already exist (it created one). Callee data
4267 // channel should not exist, since negotiation happens in-band, not in SDP.
4268 EXPECT_NE(nullptr, caller()->data_channel());
4269 EXPECT_EQ(nullptr, callee()->data_channel());
4270
4271 // The caller's data channel should close when the datagram transport is
4272 // rejected.
4273 EXPECT_FALSE(caller()->data_observer()->IsOpen());
4274
4275 // Media flow should not be impacted by the failed data channel.
4276 MediaExpectations media_expectations;
4277 media_expectations.ExpectBidirectionalAudioAndVideo();
4278 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4279}
4280
deadbeef1dcb1642017-03-29 21:08:16 -07004281// Test that the ICE connection and gathering states eventually reach
4282// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08004283TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07004284 ASSERT_TRUE(CreatePeerConnectionWrappers());
4285 ConnectFakeSignaling();
4286 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08004287 caller()->AddAudioVideoTracks();
4288 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004289 caller()->CreateAndSetAndSignalOffer();
4290 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4291 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4292 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
4293 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4294 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
4295 // After the best candidate pair is selected and all candidates are signaled,
4296 // the ICE connection state should reach "complete".
4297 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
4298 // answerer/"callee" by default) only reaches "connected". When this is
4299 // fixed, this test should be updated.
4300 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4301 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00004302 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4303 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07004304}
4305
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004306constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
4307 cricket::PORTALLOCATOR_DISABLE_RELAY |
4308 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004309
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004310// Use a mock resolver to resolve the hostname back to the original IP on both
4311// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004312TEST_P(PeerConnectionIntegrationTest,
4313 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004314 auto caller_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004315 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004316 auto callee_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004317 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004318 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
4319 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004320
4321 // This also verifies that the injected AsyncResolverFactory is used by
4322 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004323 EXPECT_CALL(*caller_resolver_factory, Create())
4324 .WillOnce(Return(&caller_async_resolver));
4325 webrtc::PeerConnectionDependencies caller_deps(nullptr);
4326 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
4327
4328 EXPECT_CALL(*callee_resolver_factory, Create())
4329 .WillOnce(Return(&callee_async_resolver));
4330 webrtc::PeerConnectionDependencies callee_deps(nullptr);
4331 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
4332
4333 PeerConnectionInterface::RTCConfiguration config;
4334 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4335 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4336
4337 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4338 config, std::move(caller_deps), config, std::move(callee_deps)));
4339
4340 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
4341 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
4342
4343 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07004344 caller()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004345 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wangecd30542019-05-22 14:34:56 -07004346 callee()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004347 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004348
4349 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004350
4351 ConnectFakeSignaling();
4352 caller()->AddAudioVideoTracks();
4353 callee()->AddAudioVideoTracks();
4354 caller()->CreateAndSetAndSignalOffer();
4355 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4356 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4357 caller()->ice_connection_state(), kDefaultTimeout);
4358 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4359 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08004360
4361 EXPECT_EQ(1, webrtc::metrics::NumEvents(
4362 "WebRTC.PeerConnection.CandidatePairType_UDP",
4363 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004364}
4365
Steve Antonede9ca52017-10-16 13:04:27 -07004366// Test that firewalling the ICE connection causes the clients to identify the
4367// disconnected state and then removing the firewall causes them to reconnect.
4368class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004369 : public PeerConnectionIntegrationBaseTest,
4370 public ::testing::WithParamInterface<
4371 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07004372 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004373 PeerConnectionIntegrationIceStatesTest()
4374 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
4375 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07004376 }
4377
4378 void StartStunServer(const SocketAddress& server_address) {
4379 stun_server_.reset(
4380 cricket::TestStunServer::Create(network_thread(), server_address));
4381 }
4382
4383 bool TestIPv6() {
4384 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
4385 }
4386
4387 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004388 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
4389 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07004390 }
4391
4392 std::vector<SocketAddress> CallerAddresses() {
4393 std::vector<SocketAddress> addresses;
4394 addresses.push_back(SocketAddress("1.1.1.1", 0));
4395 if (TestIPv6()) {
4396 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
4397 }
4398 return addresses;
4399 }
4400
4401 std::vector<SocketAddress> CalleeAddresses() {
4402 std::vector<SocketAddress> addresses;
4403 addresses.push_back(SocketAddress("2.2.2.2", 0));
4404 if (TestIPv6()) {
4405 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
4406 }
4407 return addresses;
4408 }
4409
4410 void SetUpNetworkInterfaces() {
4411 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07004412 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
4413 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07004414
4415 // Add network addresses for test.
4416 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004417 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004418 }
4419 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004420 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004421 }
4422 }
4423
4424 private:
4425 uint32_t port_allocator_flags_;
4426 std::unique_ptr<cricket::TestStunServer> stun_server_;
4427};
4428
4429// Tests that the PeerConnection goes through all the ICE gathering/connection
4430// states over the duration of the call. This includes Disconnected and Failed
4431// states, induced by putting a firewall between the peers and waiting for them
4432// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08004433TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004434 rtc::ScopedFakeClock fake_clock;
4435 // Some things use a time of "0" as a special value, so we need to start out
4436 // the fake clock at a nonzero time.
4437 fake_clock.AdvanceTime(TimeDelta::seconds(1));
Steve Antonede9ca52017-10-16 13:04:27 -07004438
4439 const SocketAddress kStunServerAddress =
4440 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
4441 StartStunServer(kStunServerAddress);
4442
4443 PeerConnectionInterface::RTCConfiguration config;
4444 PeerConnectionInterface::IceServer ice_stun_server;
4445 ice_stun_server.urls.push_back(
4446 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4447 kStunServerAddress.PortAsString());
4448 config.servers.push_back(ice_stun_server);
4449
4450 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4451 ConnectFakeSignaling();
4452 SetPortAllocatorFlags();
4453 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004454 caller()->AddAudioVideoTracks();
4455 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004456
4457 // Initial state before anything happens.
4458 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4459 caller()->ice_gathering_state());
4460 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4461 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004462 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4463 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004464
4465 // Start the call by creating the offer, setting it as the local description,
4466 // then sending it to the peer who will respond with an answer. This happens
4467 // asynchronously so that we can watch the states as it runs in the
4468 // background.
4469 caller()->CreateAndSetAndSignalOffer();
4470
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004471 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
4472 caller()->ice_connection_state());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004473 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004474 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004475
4476 // Verify that the observer was notified of the intermediate transitions.
4477 EXPECT_THAT(caller()->ice_connection_state_history(),
4478 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4479 PeerConnectionInterface::kIceConnectionConnected,
4480 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004481 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4482 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4483 PeerConnectionInterface::kIceConnectionConnected,
4484 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004485 EXPECT_THAT(
4486 caller()->peer_connection_state_history(),
4487 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004488 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004489 EXPECT_THAT(caller()->ice_gathering_state_history(),
4490 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4491 PeerConnectionInterface::kIceGatheringComplete));
4492
4493 // Block connections to/from the caller and wait for ICE to become
4494 // disconnected.
4495 for (const auto& caller_address : CallerAddresses()) {
4496 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4497 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004498 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004499 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4500 caller()->ice_connection_state(), kDefaultTimeout,
4501 fake_clock);
4502 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4503 caller()->standardized_ice_connection_state(),
4504 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004505
4506 // Let ICE re-establish by removing the firewall rules.
4507 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004508 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004509 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4510 caller()->ice_connection_state(), kDefaultTimeout,
4511 fake_clock);
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004512 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004513 caller()->standardized_ice_connection_state(),
4514 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004515
4516 // According to RFC7675, if there is no response within 30 seconds then the
4517 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004518 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004519 constexpr int kConsentTimeout = 30000;
4520 for (const auto& caller_address : CallerAddresses()) {
4521 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4522 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004523 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004524 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4525 caller()->ice_connection_state(), kConsentTimeout,
4526 fake_clock);
4527 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4528 caller()->standardized_ice_connection_state(),
4529 kConsentTimeout, fake_clock);
4530
4531 // We need to manually close the peerconnections before the fake clock goes
4532 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4533 // return to using non-faked time.
4534 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4535 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
4536}
4537
4538// Tests that if the connection doesn't get set up properly we eventually reach
4539// the "failed" iceConnectionState.
4540TEST_P(PeerConnectionIntegrationIceStatesTest, IceStateSetupFailure) {
4541 rtc::ScopedFakeClock fake_clock;
4542 // Some things use a time of "0" as a special value, so we need to start out
4543 // the fake clock at a nonzero time.
4544 fake_clock.AdvanceTime(TimeDelta::seconds(1));
4545
4546 // Block connections to/from the caller and wait for ICE to become
4547 // disconnected.
4548 for (const auto& caller_address : CallerAddresses()) {
4549 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4550 }
4551
4552 ASSERT_TRUE(CreatePeerConnectionWrappers());
4553 ConnectFakeSignaling();
4554 SetPortAllocatorFlags();
4555 SetUpNetworkInterfaces();
4556 caller()->AddAudioVideoTracks();
4557 caller()->CreateAndSetAndSignalOffer();
4558
4559 // According to RFC7675, if there is no response within 30 seconds then the
4560 // peer should consider the other side to have rejected the connection. This
4561 // is signaled by the state transitioning to "failed".
4562 constexpr int kConsentTimeout = 30000;
4563 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4564 caller()->standardized_ice_connection_state(),
4565 kConsentTimeout, fake_clock);
4566
4567 // We need to manually close the peerconnections before the fake clock goes
4568 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4569 // return to using non-faked time.
4570 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4571 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
Steve Antonede9ca52017-10-16 13:04:27 -07004572}
4573
4574// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4575// and that the statistics in the metric observers are updated correctly.
4576TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4577 ASSERT_TRUE(CreatePeerConnectionWrappers());
4578 ConnectFakeSignaling();
4579 SetPortAllocatorFlags();
4580 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004581 caller()->AddAudioVideoTracks();
4582 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004583 caller()->CreateAndSetAndSignalOffer();
4584
4585 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4586
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004587 // TODO(bugs.webrtc.org/9456): Fix it.
4588 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4589 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4590 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4591 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004592 if (TestIPv6()) {
4593 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4594 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004595 EXPECT_EQ(0, num_best_ipv4);
4596 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004597 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004598 EXPECT_EQ(1, num_best_ipv4);
4599 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004600 }
4601
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004602 EXPECT_EQ(0, webrtc::metrics::NumEvents(
4603 "WebRTC.PeerConnection.CandidatePairType_UDP",
4604 webrtc::kIceCandidatePairHostHost));
4605 EXPECT_EQ(1, webrtc::metrics::NumEvents(
4606 "WebRTC.PeerConnection.CandidatePairType_UDP",
4607 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004608}
4609
4610constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4611 cricket::PORTALLOCATOR_DISABLE_STUN |
4612 cricket::PORTALLOCATOR_DISABLE_RELAY;
4613constexpr uint32_t kFlagsIPv6NoStun =
4614 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4615 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4616constexpr uint32_t kFlagsIPv4Stun =
4617 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4618
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004619INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004620 PeerConnectionIntegrationTest,
4621 PeerConnectionIntegrationIceStatesTest,
4622 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4623 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4624 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4625 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004626
deadbeef1dcb1642017-03-29 21:08:16 -07004627// This test sets up a call between two parties with audio and video.
4628// During the call, the caller restarts ICE and the test verifies that
4629// new ICE candidates are generated and audio and video still can flow, and the
4630// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004631TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004632 ASSERT_TRUE(CreatePeerConnectionWrappers());
4633 ConnectFakeSignaling();
4634 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004635 caller()->AddAudioVideoTracks();
4636 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004637 caller()->CreateAndSetAndSignalOffer();
4638 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4639 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4640 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004641 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4642 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004643
4644 // To verify that the ICE restart actually occurs, get
4645 // ufrag/password/candidates before and after restart.
4646 // Create an SDP string of the first audio candidate for both clients.
4647 const webrtc::IceCandidateCollection* audio_candidates_caller =
4648 caller()->pc()->local_description()->candidates(0);
4649 const webrtc::IceCandidateCollection* audio_candidates_callee =
4650 callee()->pc()->local_description()->candidates(0);
4651 ASSERT_GT(audio_candidates_caller->count(), 0u);
4652 ASSERT_GT(audio_candidates_callee->count(), 0u);
4653 std::string caller_candidate_pre_restart;
4654 ASSERT_TRUE(
4655 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4656 std::string callee_candidate_pre_restart;
4657 ASSERT_TRUE(
4658 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4659 const cricket::SessionDescription* desc =
4660 caller()->pc()->local_description()->description();
4661 std::string caller_ufrag_pre_restart =
4662 desc->transport_infos()[0].description.ice_ufrag;
4663 desc = callee()->pc()->local_description()->description();
4664 std::string callee_ufrag_pre_restart =
4665 desc->transport_infos()[0].description.ice_ufrag;
4666
Alex Drake00c7ecf2019-08-06 10:54:47 -07004667 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004668 // Have the caller initiate an ICE restart.
4669 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4670 caller()->CreateAndSetAndSignalOffer();
4671 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4672 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4673 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004674 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004675 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4676
4677 // Grab the ufrags/candidates again.
4678 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4679 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4680 ASSERT_GT(audio_candidates_caller->count(), 0u);
4681 ASSERT_GT(audio_candidates_callee->count(), 0u);
4682 std::string caller_candidate_post_restart;
4683 ASSERT_TRUE(
4684 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4685 std::string callee_candidate_post_restart;
4686 ASSERT_TRUE(
4687 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4688 desc = caller()->pc()->local_description()->description();
4689 std::string caller_ufrag_post_restart =
4690 desc->transport_infos()[0].description.ice_ufrag;
4691 desc = callee()->pc()->local_description()->description();
4692 std::string callee_ufrag_post_restart =
4693 desc->transport_infos()[0].description.ice_ufrag;
4694 // Sanity check that an ICE restart was actually negotiated in SDP.
4695 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4696 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4697 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4698 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07004699 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004700
4701 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004702 MediaExpectations media_expectations;
4703 media_expectations.ExpectBidirectionalAudioAndVideo();
4704 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004705}
4706
4707// Verify that audio/video can be received end-to-end when ICE renomination is
4708// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004709TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004710 PeerConnectionInterface::RTCConfiguration config;
4711 config.enable_ice_renomination = true;
4712 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4713 ConnectFakeSignaling();
4714 // Do normal offer/answer and wait for some frames to be received in each
4715 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004716 caller()->AddAudioVideoTracks();
4717 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004718 caller()->CreateAndSetAndSignalOffer();
4719 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4720 // Sanity check that ICE renomination was actually negotiated.
4721 const cricket::SessionDescription* desc =
4722 caller()->pc()->local_description()->description();
4723 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004724 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004725 }
4726 desc = callee()->pc()->local_description()->description();
4727 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004728 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004729 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004730 MediaExpectations media_expectations;
4731 media_expectations.ExpectBidirectionalAudioAndVideo();
4732 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004733}
4734
Steve Anton6f25b092017-10-23 09:39:20 -07004735// With a max bundle policy and RTCP muxing, adding a new media description to
4736// the connection should not affect ICE at all because the new media will use
4737// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004738TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004739 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004740 PeerConnectionInterface::RTCConfiguration config;
4741 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4742 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4743 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4744 config, PeerConnectionInterface::RTCConfiguration()));
4745 ConnectFakeSignaling();
4746
Steve Anton15324772018-01-16 10:26:49 -08004747 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004748 caller()->CreateAndSetAndSignalOffer();
4749 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004750 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4751 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004752
4753 caller()->clear_ice_connection_state_history();
4754
Steve Anton15324772018-01-16 10:26:49 -08004755 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004756 caller()->CreateAndSetAndSignalOffer();
4757 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4758
4759 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4760}
4761
deadbeef1dcb1642017-03-29 21:08:16 -07004762// This test sets up a call between two parties with audio and video. It then
4763// renegotiates setting the video m-line to "port 0", then later renegotiates
4764// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004765TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004766 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4767 ASSERT_TRUE(CreatePeerConnectionWrappers());
4768 ConnectFakeSignaling();
4769
4770 // Do initial negotiation, only sending media from the caller. Will result in
4771 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004772 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004773 caller()->CreateAndSetAndSignalOffer();
4774 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4775
4776 // Negotiate again, disabling the video "m=" section (the callee will set the
4777 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004778 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4779 PeerConnectionInterface::RTCOfferAnswerOptions options;
4780 options.offer_to_receive_video = 0;
4781 callee()->SetOfferAnswerOptions(options);
4782 } else {
4783 callee()->SetRemoteOfferHandler([this] {
4784 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4785 });
4786 }
deadbeef1dcb1642017-03-29 21:08:16 -07004787 caller()->CreateAndSetAndSignalOffer();
4788 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4789 // Sanity check that video "m=" section was actually rejected.
4790 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4791 callee()->pc()->local_description()->description());
4792 ASSERT_NE(nullptr, answer_video_content);
4793 ASSERT_TRUE(answer_video_content->rejected);
4794
4795 // Enable video and do negotiation again, making sure video is received
4796 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004797 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4798 PeerConnectionInterface::RTCOfferAnswerOptions options;
4799 options.offer_to_receive_video = 1;
4800 callee()->SetOfferAnswerOptions(options);
4801 } else {
4802 // The caller's transceiver is stopped, so we need to add another track.
4803 auto caller_transceiver =
4804 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4805 EXPECT_TRUE(caller_transceiver->stopped());
4806 caller()->AddVideoTrack();
4807 }
4808 callee()->AddVideoTrack();
4809 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004810 caller()->CreateAndSetAndSignalOffer();
4811 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004812
deadbeef1dcb1642017-03-29 21:08:16 -07004813 // Verify the caller receives frames from the newly added stream, and the
4814 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004815 MediaExpectations media_expectations;
4816 media_expectations.CalleeExpectsSomeAudio();
4817 media_expectations.ExpectBidirectionalVideo();
4818 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004819}
4820
deadbeef1dcb1642017-03-29 21:08:16 -07004821// This tests that if we negotiate after calling CreateSender but before we
4822// have a track, then set a track later, frames from the newly-set track are
4823// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004824TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004825 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4826 ASSERT_TRUE(CreatePeerConnectionWrappers());
4827 ConnectFakeSignaling();
4828 auto caller_audio_sender =
4829 caller()->pc()->CreateSender("audio", "caller_stream");
4830 auto caller_video_sender =
4831 caller()->pc()->CreateSender("video", "caller_stream");
4832 auto callee_audio_sender =
4833 callee()->pc()->CreateSender("audio", "callee_stream");
4834 auto callee_video_sender =
4835 callee()->pc()->CreateSender("video", "callee_stream");
4836 caller()->CreateAndSetAndSignalOffer();
4837 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4838 // Wait for ICE to complete, without any tracks being set.
4839 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4840 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4841 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4842 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4843 // Now set the tracks, and expect frames to immediately start flowing.
4844 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4845 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4846 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4847 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004848 MediaExpectations media_expectations;
4849 media_expectations.ExpectBidirectionalAudioAndVideo();
4850 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4851}
4852
4853// This tests that if we negotiate after calling AddTransceiver but before we
4854// have a track, then set a track later, frames from the newly-set tracks are
4855// received end-to-end.
4856TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4857 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4858 ASSERT_TRUE(CreatePeerConnectionWrappers());
4859 ConnectFakeSignaling();
4860 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4861 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4862 auto caller_audio_sender = audio_result.MoveValue()->sender();
4863 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4864 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4865 auto caller_video_sender = video_result.MoveValue()->sender();
4866 callee()->SetRemoteOfferHandler([this] {
4867 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4868 callee()->pc()->GetTransceivers()[0]->SetDirection(
4869 RtpTransceiverDirection::kSendRecv);
4870 callee()->pc()->GetTransceivers()[1]->SetDirection(
4871 RtpTransceiverDirection::kSendRecv);
4872 });
4873 caller()->CreateAndSetAndSignalOffer();
4874 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4875 // Wait for ICE to complete, without any tracks being set.
4876 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4877 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4878 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4879 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4880 // Now set the tracks, and expect frames to immediately start flowing.
4881 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4882 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4883 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4884 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4885 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4886 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4887 MediaExpectations media_expectations;
4888 media_expectations.ExpectBidirectionalAudioAndVideo();
4889 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004890}
4891
4892// This test verifies that a remote video track can be added via AddStream,
4893// and sent end-to-end. For this particular test, it's simply echoed back
4894// from the caller to the callee, rather than being forwarded to a third
4895// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004896TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004897 ASSERT_TRUE(CreatePeerConnectionWrappers());
4898 ConnectFakeSignaling();
4899 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004900 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004901 caller()->CreateAndSetAndSignalOffer();
4902 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004903 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004904
4905 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4906 // time).
4907 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4908 callee()->CreateAndSetAndSignalOffer();
4909 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4910
Seth Hampson2f0d7022018-02-20 11:54:42 -08004911 MediaExpectations media_expectations;
4912 media_expectations.ExpectBidirectionalVideo();
4913 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004914}
4915
4916// Test that we achieve the expected end-to-end connection time, using a
4917// fake clock and simulated latency on the media and signaling paths.
4918// We use a TURN<->TURN connection because this is usually the quickest to
4919// set up initially, especially when we're confident the connection will work
4920// and can start sending media before we get a STUN response.
4921//
4922// With various optimizations enabled, here are the network delays we expect to
4923// be on the critical path:
4924// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4925// signaling answer (with DTLS fingerprint).
4926// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4927// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4928// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004929TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004930 rtc::ScopedFakeClock fake_clock;
4931 // Some things use a time of "0" as a special value, so we need to start out
4932 // the fake clock at a nonzero time.
4933 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02004934 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07004935
4936 static constexpr int media_hop_delay_ms = 50;
4937 static constexpr int signaling_trip_delay_ms = 500;
4938 // For explanation of these values, see comment above.
4939 static constexpr int required_media_hops = 9;
4940 static constexpr int required_signaling_trips = 2;
4941 // For internal delays (such as posting an event asychronously).
4942 static constexpr int allowed_internal_delay_ms = 20;
4943 static constexpr int total_connection_time_ms =
4944 media_hop_delay_ms * required_media_hops +
4945 signaling_trip_delay_ms * required_signaling_trips +
4946 allowed_internal_delay_ms;
4947
4948 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4949 3478};
4950 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4951 0};
4952 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4953 3478};
4954 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4955 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004956 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4957 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004958
Seth Hampsonaed71642018-06-11 07:41:32 -07004959 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4960 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004961 // Bypass permission check on received packets so media can be sent before
4962 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004963 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4964 turn_server_1->set_enable_permission_checks(false);
4965 });
4966 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4967 turn_server_2->set_enable_permission_checks(false);
4968 });
deadbeef1dcb1642017-03-29 21:08:16 -07004969
4970 PeerConnectionInterface::RTCConfiguration client_1_config;
4971 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4972 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4973 ice_server_1.username = "test";
4974 ice_server_1.password = "test";
4975 client_1_config.servers.push_back(ice_server_1);
4976 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4977 client_1_config.presume_writable_when_fully_relayed = true;
4978
4979 PeerConnectionInterface::RTCConfiguration client_2_config;
4980 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4981 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4982 ice_server_2.username = "test";
4983 ice_server_2.password = "test";
4984 client_2_config.servers.push_back(ice_server_2);
4985 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4986 client_2_config.presume_writable_when_fully_relayed = true;
4987
4988 ASSERT_TRUE(
4989 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4990 // Set up the simulated delays.
4991 SetSignalingDelayMs(signaling_trip_delay_ms);
4992 ConnectFakeSignaling();
4993 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4994 virtual_socket_server()->UpdateDelayDistribution();
4995
4996 // Set "offer to receive audio/video" without adding any tracks, so we just
4997 // set up ICE/DTLS with no media.
4998 PeerConnectionInterface::RTCOfferAnswerOptions options;
4999 options.offer_to_receive_audio = 1;
5000 options.offer_to_receive_video = 1;
5001 caller()->SetOfferAnswerOptions(options);
5002 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07005003 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
5004 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07005005 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
5006 // If this is not done a DCHECK can be hit in ports.cc, because a large
5007 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07005008 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07005009}
5010
Jonas Orelandbdcee282017-10-10 14:01:40 +02005011// Verify that a TurnCustomizer passed in through RTCConfiguration
5012// is actually used by the underlying TURN candidate pair.
5013// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005014TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02005015 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
5016 3478};
5017 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
5018 0};
5019 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
5020 3478};
5021 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
5022 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07005023 CreateTurnServer(turn_server_1_internal_address,
5024 turn_server_1_external_address);
5025 CreateTurnServer(turn_server_2_internal_address,
5026 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005027
5028 PeerConnectionInterface::RTCConfiguration client_1_config;
5029 webrtc::PeerConnectionInterface::IceServer ice_server_1;
5030 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
5031 ice_server_1.username = "test";
5032 ice_server_1.password = "test";
5033 client_1_config.servers.push_back(ice_server_1);
5034 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005035 auto* customizer1 = CreateTurnCustomizer();
5036 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005037
5038 PeerConnectionInterface::RTCConfiguration client_2_config;
5039 webrtc::PeerConnectionInterface::IceServer ice_server_2;
5040 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
5041 ice_server_2.username = "test";
5042 ice_server_2.password = "test";
5043 client_2_config.servers.push_back(ice_server_2);
5044 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07005045 auto* customizer2 = CreateTurnCustomizer();
5046 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02005047
5048 ASSERT_TRUE(
5049 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5050 ConnectFakeSignaling();
5051
5052 // Set "offer to receive audio/video" without adding any tracks, so we just
5053 // set up ICE/DTLS with no media.
5054 PeerConnectionInterface::RTCOfferAnswerOptions options;
5055 options.offer_to_receive_audio = 1;
5056 options.offer_to_receive_video = 1;
5057 caller()->SetOfferAnswerOptions(options);
5058 caller()->CreateAndSetAndSignalOffer();
5059 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5060
Seth Hampsonaed71642018-06-11 07:41:32 -07005061 ExpectTurnCustomizerCountersIncremented(customizer1);
5062 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02005063}
5064
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005065// Verifies that you can use TCP instead of UDP to connect to a TURN server and
5066// send media between the caller and the callee.
5067TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
5068 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5069 3478};
5070 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5071
5072 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07005073 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5074 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07005075
5076 webrtc::PeerConnectionInterface::IceServer ice_server;
5077 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
5078 ice_server.username = "test";
5079 ice_server.password = "test";
5080
5081 PeerConnectionInterface::RTCConfiguration client_1_config;
5082 client_1_config.servers.push_back(ice_server);
5083 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5084
5085 PeerConnectionInterface::RTCConfiguration client_2_config;
5086 client_2_config.servers.push_back(ice_server);
5087 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5088
5089 ASSERT_TRUE(
5090 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
5091
5092 // Do normal offer/answer and wait for ICE to complete.
5093 ConnectFakeSignaling();
5094 caller()->AddAudioVideoTracks();
5095 callee()->AddAudioVideoTracks();
5096 caller()->CreateAndSetAndSignalOffer();
5097 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5098 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5099 callee()->ice_connection_state(), kMaxWaitForFramesMs);
5100
5101 MediaExpectations media_expectations;
5102 media_expectations.ExpectBidirectionalAudioAndVideo();
5103 EXPECT_TRUE(ExpectNewFrames(media_expectations));
5104}
5105
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005106// Verify that a SSLCertificateVerifier passed in through
5107// PeerConnectionDependencies is actually used by the underlying SSL
5108// implementation to determine whether a certificate presented by the TURN
5109// server is accepted by the client. Note that openssladapter_unittest.cc
5110// contains more detailed, lower-level tests.
5111TEST_P(PeerConnectionIntegrationTest,
5112 SSLCertificateVerifierUsedForTurnConnections) {
5113 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5114 3478};
5115 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5116
5117 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5118 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005119 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5120 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005121
5122 webrtc::PeerConnectionInterface::IceServer ice_server;
5123 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5124 ice_server.username = "test";
5125 ice_server.password = "test";
5126
5127 PeerConnectionInterface::RTCConfiguration client_1_config;
5128 client_1_config.servers.push_back(ice_server);
5129 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5130
5131 PeerConnectionInterface::RTCConfiguration client_2_config;
5132 client_2_config.servers.push_back(ice_server);
5133 // Setting the type to kRelay forces the connection to go through a TURN
5134 // server.
5135 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5136
5137 // Get a copy to the pointer so we can verify calls later.
5138 rtc::TestCertificateVerifier* client_1_cert_verifier =
5139 new rtc::TestCertificateVerifier();
5140 client_1_cert_verifier->verify_certificate_ = true;
5141 rtc::TestCertificateVerifier* client_2_cert_verifier =
5142 new rtc::TestCertificateVerifier();
5143 client_2_cert_verifier->verify_certificate_ = true;
5144
5145 // Create the dependencies with the test certificate verifier.
5146 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5147 client_1_deps.tls_cert_verifier =
5148 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5149 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5150 client_2_deps.tls_cert_verifier =
5151 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5152
5153 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5154 client_1_config, std::move(client_1_deps), client_2_config,
5155 std::move(client_2_deps)));
5156 ConnectFakeSignaling();
5157
5158 // Set "offer to receive audio/video" without adding any tracks, so we just
5159 // set up ICE/DTLS with no media.
5160 PeerConnectionInterface::RTCOfferAnswerOptions options;
5161 options.offer_to_receive_audio = 1;
5162 options.offer_to_receive_video = 1;
5163 caller()->SetOfferAnswerOptions(options);
5164 caller()->CreateAndSetAndSignalOffer();
5165 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5166
5167 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5168 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005169}
5170
5171TEST_P(PeerConnectionIntegrationTest,
5172 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
5173 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5174 3478};
5175 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5176
5177 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
5178 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07005179 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
5180 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005181
5182 webrtc::PeerConnectionInterface::IceServer ice_server;
5183 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
5184 ice_server.username = "test";
5185 ice_server.password = "test";
5186
5187 PeerConnectionInterface::RTCConfiguration client_1_config;
5188 client_1_config.servers.push_back(ice_server);
5189 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
5190
5191 PeerConnectionInterface::RTCConfiguration client_2_config;
5192 client_2_config.servers.push_back(ice_server);
5193 // Setting the type to kRelay forces the connection to go through a TURN
5194 // server.
5195 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
5196
5197 // Get a copy to the pointer so we can verify calls later.
5198 rtc::TestCertificateVerifier* client_1_cert_verifier =
5199 new rtc::TestCertificateVerifier();
5200 client_1_cert_verifier->verify_certificate_ = false;
5201 rtc::TestCertificateVerifier* client_2_cert_verifier =
5202 new rtc::TestCertificateVerifier();
5203 client_2_cert_verifier->verify_certificate_ = false;
5204
5205 // Create the dependencies with the test certificate verifier.
5206 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
5207 client_1_deps.tls_cert_verifier =
5208 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
5209 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
5210 client_2_deps.tls_cert_verifier =
5211 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
5212
5213 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
5214 client_1_config, std::move(client_1_deps), client_2_config,
5215 std::move(client_2_deps)));
5216 ConnectFakeSignaling();
5217
5218 // Set "offer to receive audio/video" without adding any tracks, so we just
5219 // set up ICE/DTLS with no media.
5220 PeerConnectionInterface::RTCOfferAnswerOptions options;
5221 options.offer_to_receive_audio = 1;
5222 options.offer_to_receive_video = 1;
5223 caller()->SetOfferAnswerOptions(options);
5224 caller()->CreateAndSetAndSignalOffer();
5225 bool wait_res = true;
5226 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
5227 // properly, should be able to just wait for a state of "failed" instead of
5228 // waiting a fixed 10 seconds.
5229 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
5230 ASSERT_FALSE(wait_res);
5231
5232 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
5233 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005234}
5235
Qingsi Wang25ec8882019-11-15 12:33:05 -08005236// Test that the injected ICE transport factory is used to create ICE transports
5237// for WebRTC connections.
5238TEST_P(PeerConnectionIntegrationTest, IceTransportFactoryUsedForConnections) {
5239 PeerConnectionInterface::RTCConfiguration default_config;
5240 PeerConnectionDependencies dependencies(nullptr);
5241 auto ice_transport_factory = std::make_unique<MockIceTransportFactory>();
5242 EXPECT_CALL(*ice_transport_factory, RecordIceTransportCreated()).Times(1);
5243 dependencies.ice_transport_factory = std::move(ice_transport_factory);
5244 auto wrapper =
5245 CreatePeerConnectionWrapper("Caller", nullptr, &default_config,
5246 std::move(dependencies), nullptr, nullptr);
5247 ASSERT_TRUE(wrapper);
5248 wrapper->CreateDataChannel();
5249 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5250 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5251 wrapper->pc()->SetLocalDescription(observer,
5252 wrapper->CreateOfferAndWait().release());
5253}
5254
deadbeefc964d0b2017-04-03 10:03:35 -07005255// Test that audio and video flow end-to-end when codec names don't use the
5256// expected casing, given that they're supposed to be case insensitive. To test
5257// this, all but one codec is removed from each media description, and its
5258// casing is changed.
5259//
5260// In the past, this has regressed and caused crashes/black video, due to the
5261// fact that code at some layers was doing case-insensitive comparisons and
5262// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005263TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07005264 ASSERT_TRUE(CreatePeerConnectionWrappers());
5265 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005266 caller()->AddAudioVideoTracks();
5267 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07005268
5269 // Remove all but one audio/video codec (opus and VP8), and change the
5270 // casing of the caller's generated offer.
5271 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
5272 cricket::AudioContentDescription* audio =
5273 GetFirstAudioContentDescription(description);
5274 ASSERT_NE(nullptr, audio);
5275 auto audio_codecs = audio->codecs();
5276 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
5277 [](const cricket::AudioCodec& codec) {
5278 return codec.name != "opus";
5279 }),
5280 audio_codecs.end());
5281 ASSERT_EQ(1u, audio_codecs.size());
5282 audio_codecs[0].name = "OpUs";
5283 audio->set_codecs(audio_codecs);
5284
5285 cricket::VideoContentDescription* video =
5286 GetFirstVideoContentDescription(description);
5287 ASSERT_NE(nullptr, video);
5288 auto video_codecs = video->codecs();
5289 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
5290 [](const cricket::VideoCodec& codec) {
5291 return codec.name != "VP8";
5292 }),
5293 video_codecs.end());
5294 ASSERT_EQ(1u, video_codecs.size());
5295 video_codecs[0].name = "vP8";
5296 video->set_codecs(video_codecs);
5297 });
5298
5299 caller()->CreateAndSetAndSignalOffer();
5300 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5301
5302 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005303 MediaExpectations media_expectations;
5304 media_expectations.ExpectBidirectionalAudioAndVideo();
5305 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07005306}
5307
Jonas Oreland49ac5952018-09-26 16:04:32 +02005308TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07005309 ASSERT_TRUE(CreatePeerConnectionWrappers());
5310 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005311 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07005312 caller()->CreateAndSetAndSignalOffer();
5313 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07005314 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005315 MediaExpectations media_expectations;
5316 media_expectations.CalleeExpectsSomeAudio(1);
5317 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02005318 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07005319 auto receiver = callee()->pc()->GetReceivers()[0];
5320 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005321 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07005322 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
5323 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02005324 sources[0].source_id());
5325 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
5326}
5327
5328TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
5329 ASSERT_TRUE(CreatePeerConnectionWrappers());
5330 ConnectFakeSignaling();
5331 caller()->AddVideoTrack();
5332 caller()->CreateAndSetAndSignalOffer();
5333 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5334 // Wait for one video frame to be received by the callee.
5335 MediaExpectations media_expectations;
5336 media_expectations.CalleeExpectsSomeVideo(1);
5337 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5338 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
5339 auto receiver = callee()->pc()->GetReceivers()[0];
5340 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
5341 auto sources = receiver->GetSources();
5342 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02005343 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005344 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
5345 sources[0].source_id());
5346 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07005347}
5348
deadbeef2f425aa2017-04-14 10:41:32 -07005349// Test that if a track is removed and added again with a different stream ID,
5350// the new stream ID is successfully communicated in SDP and media continues to
5351// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005352// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
5353// it will not reuse a transceiver that has already been sending. After creating
5354// a new transceiver it tries to create an offer with two senders of the same
5355// track ids and it fails.
5356TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07005357 ASSERT_TRUE(CreatePeerConnectionWrappers());
5358 ConnectFakeSignaling();
5359
deadbeef2f425aa2017-04-14 10:41:32 -07005360 // Add track using stream 1, do offer/answer.
5361 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
5362 caller()->CreateLocalAudioTrack();
5363 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07005364 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07005365 caller()->CreateAndSetAndSignalOffer();
5366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005367 {
5368 MediaExpectations media_expectations;
5369 media_expectations.CalleeExpectsSomeAudio(1);
5370 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5371 }
deadbeef2f425aa2017-04-14 10:41:32 -07005372 // Remove the sender, and create a new one with the new stream.
5373 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07005374 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07005375 caller()->CreateAndSetAndSignalOffer();
5376 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5377 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005378 {
5379 MediaExpectations media_expectations;
5380 media_expectations.CalleeExpectsSomeAudio();
5381 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5382 }
deadbeef2f425aa2017-04-14 10:41:32 -07005383}
5384
Seth Hampson2f0d7022018-02-20 11:54:42 -08005385TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02005386 ASSERT_TRUE(CreatePeerConnectionWrappers());
5387 ConnectFakeSignaling();
5388
Mirko Bonadei317a1f02019-09-17 17:06:18 +02005389 auto output = std::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005390 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
5391 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02005392 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01005393 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
5394 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02005395
Steve Anton15324772018-01-16 10:26:49 -08005396 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02005397 caller()->CreateAndSetAndSignalOffer();
5398 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5399}
5400
Steve Antonede9ca52017-10-16 13:04:27 -07005401// Test that if candidates are only signaled by applying full session
5402// descriptions (instead of using AddIceCandidate), the peers can connect to
5403// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005404TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07005405 ASSERT_TRUE(CreatePeerConnectionWrappers());
5406 // Each side will signal the session descriptions but not candidates.
5407 ConnectFakeSignalingForSdpOnly();
5408
5409 // Add audio video track and exchange the initial offer/answer with media
5410 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08005411 caller()->AddAudioVideoTracks();
5412 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07005413 caller()->CreateAndSetAndSignalOffer();
5414
5415 // Wait for all candidates to be gathered on both the caller and callee.
5416 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5417 caller()->ice_gathering_state(), kDefaultTimeout);
5418 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5419 callee()->ice_gathering_state(), kDefaultTimeout);
5420
5421 // The candidates will now be included in the session description, so
5422 // signaling them will start the ICE connection.
5423 caller()->CreateAndSetAndSignalOffer();
5424 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5425
5426 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005427 MediaExpectations media_expectations;
5428 media_expectations.ExpectBidirectionalAudioAndVideo();
5429 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07005430}
5431
henrika5f6bf242017-11-01 11:06:56 +01005432// Test that SetAudioPlayout can be used to disable audio playout from the
5433// start, then later enable it. This may be useful, for example, if the caller
5434// needs to play a local ringtone until some event occurs, after which it
5435// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005436TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01005437 ASSERT_TRUE(CreatePeerConnectionWrappers());
5438 ConnectFakeSignaling();
5439
5440 // Set up audio-only call where audio playout is disabled on caller's side.
5441 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08005442 caller()->AddAudioTrack();
5443 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005444 caller()->CreateAndSetAndSignalOffer();
5445 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5446
5447 // Pump messages for a second.
5448 WAIT(false, 1000);
5449 // Since audio playout is disabled, the caller shouldn't have received
5450 // anything (at the playout level, at least).
5451 EXPECT_EQ(0, caller()->audio_frames_received());
5452 // As a sanity check, make sure the callee (for which playout isn't disabled)
5453 // did still see frames on its audio level.
5454 ASSERT_GT(callee()->audio_frames_received(), 0);
5455
5456 // Enable playout again, and ensure audio starts flowing.
5457 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005458 MediaExpectations media_expectations;
5459 media_expectations.ExpectBidirectionalAudio();
5460 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01005461}
5462
5463double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5464 auto report = pc->NewGetStats();
5465 auto track_stats_list =
5466 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5467 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5468 for (const auto* track_stats : track_stats_list) {
5469 if (track_stats->remote_source.is_defined() &&
5470 *track_stats->remote_source) {
5471 remote_track_stats = track_stats;
5472 break;
5473 }
5474 }
5475
5476 if (!remote_track_stats->total_audio_energy.is_defined()) {
5477 return 0.0;
5478 }
5479 return *remote_track_stats->total_audio_energy;
5480}
5481
5482// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5483// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005484TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005485 DisableAudioPlayoutStillGeneratesAudioStats) {
5486 ASSERT_TRUE(CreatePeerConnectionWrappers());
5487 ConnectFakeSignaling();
5488
5489 // Set up audio-only call where playout is disabled but audio-processing is
5490 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005491 caller()->AddAudioTrack();
5492 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005493 caller()->pc()->SetAudioPlayout(false);
5494
5495 caller()->CreateAndSetAndSignalOffer();
5496 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5497
5498 // Wait for the callee to receive audio stats.
5499 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5500}
5501
henrika4f167df2017-11-01 14:45:55 +01005502// Test that SetAudioRecording can be used to disable audio recording from the
5503// start, then later enable it. This may be useful, for example, if the caller
5504// wants to ensure that no audio resources are active before a certain state
5505// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005506TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005507 ASSERT_TRUE(CreatePeerConnectionWrappers());
5508 ConnectFakeSignaling();
5509
5510 // Set up audio-only call where audio recording is disabled on caller's side.
5511 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005512 caller()->AddAudioTrack();
5513 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005514 caller()->CreateAndSetAndSignalOffer();
5515 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5516
5517 // Pump messages for a second.
5518 WAIT(false, 1000);
5519 // Since caller has disabled audio recording, the callee shouldn't have
5520 // received anything.
5521 EXPECT_EQ(0, callee()->audio_frames_received());
5522 // As a sanity check, make sure the caller did still see frames on its
5523 // audio level since audio recording is enabled on the calle side.
5524 ASSERT_GT(caller()->audio_frames_received(), 0);
5525
5526 // Enable audio recording again, and ensure audio starts flowing.
5527 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005528 MediaExpectations media_expectations;
5529 media_expectations.ExpectBidirectionalAudio();
5530 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005531}
5532
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005533// Test that after closing PeerConnections, they stop sending any packets (ICE,
5534// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005535TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005536 // Set up audio/video/data, wait for some frames to be received.
5537 ASSERT_TRUE(CreatePeerConnectionWrappers());
5538 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005539 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005540#ifdef HAVE_SCTP
5541 caller()->CreateDataChannel();
5542#endif
5543 caller()->CreateAndSetAndSignalOffer();
5544 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005545 MediaExpectations media_expectations;
5546 media_expectations.CalleeExpectsSomeAudioAndVideo();
5547 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005548 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005549 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005550 // Pump messages for a second, and ensure no new packets end up sent.
5551 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5552 WAIT(false, 1000);
5553 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5554 EXPECT_EQ(sent_packets_a, sent_packets_b);
5555}
5556
Steve Anton7eca0932018-03-30 15:18:41 -07005557// Test that transport stats are generated by the RTCStatsCollector for a
5558// connection that only involves data channels. This is a regression test for
5559// crbug.com/826972.
5560#ifdef HAVE_SCTP
5561TEST_P(PeerConnectionIntegrationTest,
5562 TransportStatsReportedForDataChannelOnlyConnection) {
5563 ASSERT_TRUE(CreatePeerConnectionWrappers());
5564 ConnectFakeSignaling();
5565 caller()->CreateDataChannel();
5566
5567 caller()->CreateAndSetAndSignalOffer();
5568 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5569 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5570
5571 auto caller_report = caller()->NewGetStats();
5572 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5573 auto callee_report = callee()->NewGetStats();
5574 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5575}
5576#endif // HAVE_SCTP
5577
Qingsi Wang7685e862018-06-11 20:15:46 -07005578TEST_P(PeerConnectionIntegrationTest,
5579 IceEventsGeneratedAndLoggedInRtcEventLog) {
5580 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5581 ConnectFakeSignaling();
5582 PeerConnectionInterface::RTCOfferAnswerOptions options;
5583 options.offer_to_receive_audio = 1;
5584 caller()->SetOfferAnswerOptions(options);
5585 caller()->CreateAndSetAndSignalOffer();
5586 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5587 ASSERT_NE(nullptr, caller()->event_log_factory());
5588 ASSERT_NE(nullptr, callee()->event_log_factory());
5589 webrtc::FakeRtcEventLog* caller_event_log =
5590 static_cast<webrtc::FakeRtcEventLog*>(
5591 caller()->event_log_factory()->last_log_created());
5592 webrtc::FakeRtcEventLog* callee_event_log =
5593 static_cast<webrtc::FakeRtcEventLog*>(
5594 callee()->event_log_factory()->last_log_created());
5595 ASSERT_NE(nullptr, caller_event_log);
5596 ASSERT_NE(nullptr, callee_event_log);
5597 int caller_ice_config_count = caller_event_log->GetEventCount(
5598 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5599 int caller_ice_event_count = caller_event_log->GetEventCount(
5600 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5601 int callee_ice_config_count = callee_event_log->GetEventCount(
5602 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5603 int callee_ice_event_count = callee_event_log->GetEventCount(
5604 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5605 EXPECT_LT(0, caller_ice_config_count);
5606 EXPECT_LT(0, caller_ice_event_count);
5607 EXPECT_LT(0, callee_ice_config_count);
5608 EXPECT_LT(0, callee_ice_event_count);
5609}
5610
Qingsi Wangc129c352019-04-18 10:41:58 -07005611TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005612 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5613 3478};
5614 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5615
5616 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5617
5618 webrtc::PeerConnectionInterface::IceServer ice_server;
5619 ice_server.urls.push_back("turn:88.88.88.0:3478");
5620 ice_server.username = "test";
5621 ice_server.password = "test";
5622
5623 PeerConnectionInterface::RTCConfiguration caller_config;
5624 caller_config.servers.push_back(ice_server);
5625 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5626 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005627 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005628
5629 PeerConnectionInterface::RTCConfiguration callee_config;
5630 callee_config.servers.push_back(ice_server);
5631 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5632 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005633 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005634
5635 ASSERT_TRUE(
5636 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5637
5638 // Do normal offer/answer and wait for ICE to complete.
5639 ConnectFakeSignaling();
5640 caller()->AddAudioVideoTracks();
5641 callee()->AddAudioVideoTracks();
5642 caller()->CreateAndSetAndSignalOffer();
5643 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5644 // Since we are doing continual gathering, the ICE transport does not reach
5645 // kIceGatheringComplete (see
5646 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5647 // kIceConnectionComplete.
5648 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5649 caller()->ice_connection_state(), kDefaultTimeout);
5650 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5651 callee()->ice_connection_state(), kDefaultTimeout);
5652 // Note that we cannot use the metric
5653 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5654 // metric is only populated when we reach kIceConnectionComplete in the
5655 // current implementation.
5656 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5657 caller()->last_candidate_gathered().type());
5658 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5659 callee()->last_candidate_gathered().type());
5660
5661 // Loosen the caller's candidate filter.
5662 caller_config = caller()->pc()->GetConfiguration();
5663 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5664 caller()->pc()->SetConfiguration(caller_config);
5665 // We should have gathered a new host candidate.
5666 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5667 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5668
5669 // Loosen the callee's candidate filter.
5670 callee_config = callee()->pc()->GetConfiguration();
5671 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5672 callee()->pc()->SetConfiguration(callee_config);
5673 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5674 callee()->last_candidate_gathered().type(), kDefaultTimeout);
5675}
5676
Eldar Relloda13ea22019-06-01 12:23:43 +03005677TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03005678 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5679 3478};
5680 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5681
5682 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5683
5684 webrtc::PeerConnectionInterface::IceServer ice_server;
5685 ice_server.urls.push_back("turn:88.88.88.0:3478");
5686 ice_server.username = "test";
5687 ice_server.password = "123";
5688
5689 PeerConnectionInterface::RTCConfiguration caller_config;
5690 caller_config.servers.push_back(ice_server);
5691 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5692 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5693
5694 PeerConnectionInterface::RTCConfiguration callee_config;
5695 callee_config.servers.push_back(ice_server);
5696 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5697 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5698
5699 ASSERT_TRUE(
5700 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5701
5702 // Do normal offer/answer and wait for ICE to complete.
5703 ConnectFakeSignaling();
5704 caller()->AddAudioVideoTracks();
5705 callee()->AddAudioVideoTracks();
5706 caller()->CreateAndSetAndSignalOffer();
5707 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5708 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5709 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5710 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
5711 EXPECT_NE(std::string::npos,
5712 caller()->error_event().host_candidate.find(":"));
5713}
5714
Eldar Rello5ab79e62019-10-09 18:29:44 +03005715TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5716 AudioKeepsFlowingAfterImplicitRollback) {
5717 PeerConnectionInterface::RTCConfiguration config;
5718 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5719 config.enable_implicit_rollback = true;
5720 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5721 ConnectFakeSignaling();
5722 caller()->AddAudioTrack();
5723 callee()->AddAudioTrack();
5724 caller()->CreateAndSetAndSignalOffer();
5725 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5726 MediaExpectations media_expectations;
5727 media_expectations.ExpectBidirectionalAudio();
5728 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5729 SetSignalIceCandidates(false); // Workaround candidate outrace sdp.
5730 caller()->AddVideoTrack();
5731 callee()->AddVideoTrack();
5732 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5733 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5734 callee()->pc()->SetLocalDescription(observer,
5735 callee()->CreateOfferAndWait().release());
5736 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
5737 caller()->CreateAndSetAndSignalOffer(); // Implicit rollback.
5738 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5739 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5740}
5741
5742TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5743 ImplicitRollbackVisitsStableState) {
5744 RTCConfiguration config;
5745 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5746 config.enable_implicit_rollback = true;
5747
5748 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5749
5750 rtc::scoped_refptr<MockSetSessionDescriptionObserver> sld_observer(
5751 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5752 callee()->pc()->SetLocalDescription(sld_observer,
5753 callee()->CreateOfferAndWait().release());
5754 EXPECT_TRUE_WAIT(sld_observer->called(), kDefaultTimeout);
5755 EXPECT_EQ(sld_observer->error(), "");
5756
5757 rtc::scoped_refptr<MockSetSessionDescriptionObserver> srd_observer(
5758 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5759 callee()->pc()->SetRemoteDescription(
5760 srd_observer, caller()->CreateOfferAndWait().release());
5761 EXPECT_TRUE_WAIT(srd_observer->called(), kDefaultTimeout);
5762 EXPECT_EQ(srd_observer->error(), "");
5763
5764 EXPECT_THAT(callee()->peer_connection_signaling_state_history(),
5765 ElementsAre(PeerConnectionInterface::kHaveLocalOffer,
5766 PeerConnectionInterface::kStable,
5767 PeerConnectionInterface::kHaveRemoteOffer));
5768}
5769
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005770INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5771 PeerConnectionIntegrationTest,
5772 Values(SdpSemantics::kPlanB,
5773 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005774
Steve Anton74255ff2018-01-24 18:32:57 -08005775// Tests that verify interoperability between Plan B and Unified Plan
5776// PeerConnections.
5777class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08005778 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08005779 public ::testing::WithParamInterface<
5780 std::tuple<SdpSemantics, SdpSemantics>> {
5781 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08005782 // Setting the SdpSemantics for the base test to kDefault does not matter
5783 // because we specify not to use the test semantics when creating
5784 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08005785 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07005786 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08005787 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08005788 callee_semantics_(std::get<1>(GetParam())) {}
5789
5790 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07005791 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5792 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08005793 }
5794
5795 const SdpSemantics caller_semantics_;
5796 const SdpSemantics callee_semantics_;
5797};
5798
5799TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5800 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5801 ConnectFakeSignaling();
5802
5803 caller()->CreateAndSetAndSignalOffer();
5804 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5805}
5806
5807TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
5808 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5809 ConnectFakeSignaling();
5810 auto audio_sender = caller()->AddAudioTrack();
5811
5812 caller()->CreateAndSetAndSignalOffer();
5813 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5814
5815 // Verify that one audio receiver has been created on the remote and that it
5816 // has the same track ID as the sending track.
5817 auto receivers = callee()->pc()->GetReceivers();
5818 ASSERT_EQ(1u, receivers.size());
5819 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
5820 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
5821
Seth Hampson2f0d7022018-02-20 11:54:42 -08005822 MediaExpectations media_expectations;
5823 media_expectations.CalleeExpectsSomeAudio();
5824 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005825}
5826
5827TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
5828 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5829 ConnectFakeSignaling();
5830 auto video_sender = caller()->AddVideoTrack();
5831 auto audio_sender = caller()->AddAudioTrack();
5832
5833 caller()->CreateAndSetAndSignalOffer();
5834 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5835
5836 // Verify that one audio and one video receiver have been created on the
5837 // remote and that they have the same track IDs as the sending tracks.
5838 auto audio_receivers =
5839 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5840 ASSERT_EQ(1u, audio_receivers.size());
5841 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5842 auto video_receivers =
5843 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5844 ASSERT_EQ(1u, video_receivers.size());
5845 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5846
Seth Hampson2f0d7022018-02-20 11:54:42 -08005847 MediaExpectations media_expectations;
5848 media_expectations.CalleeExpectsSomeAudioAndVideo();
5849 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005850}
5851
5852TEST_P(PeerConnectionIntegrationInteropTest,
5853 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5854 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5855 ConnectFakeSignaling();
5856 caller()->AddAudioVideoTracks();
5857 callee()->AddAudioVideoTracks();
5858
5859 caller()->CreateAndSetAndSignalOffer();
5860 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5861
Seth Hampson2f0d7022018-02-20 11:54:42 -08005862 MediaExpectations media_expectations;
5863 media_expectations.ExpectBidirectionalAudioAndVideo();
5864 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005865}
5866
5867TEST_P(PeerConnectionIntegrationInteropTest,
5868 ReverseRolesOneAudioLocalToOneVideoRemote) {
5869 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5870 ConnectFakeSignaling();
5871 caller()->AddAudioTrack();
5872 callee()->AddVideoTrack();
5873
5874 caller()->CreateAndSetAndSignalOffer();
5875 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5876
5877 // Verify that only the audio track has been negotiated.
5878 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5879 // Might also check that the callee's NegotiationNeeded flag is set.
5880
5881 // Reverse roles.
5882 callee()->CreateAndSetAndSignalOffer();
5883 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5884
Seth Hampson2f0d7022018-02-20 11:54:42 -08005885 MediaExpectations media_expectations;
5886 media_expectations.CallerExpectsSomeVideo();
5887 media_expectations.CalleeExpectsSomeAudio();
5888 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005889}
5890
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005891INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07005892 PeerConnectionIntegrationTest,
5893 PeerConnectionIntegrationInteropTest,
5894 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5895 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5896
5897// Test that if the Unified Plan side offers two video tracks then the Plan B
5898// side will only see the first one and ignore the second.
5899TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005900 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5901 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005902 ConnectFakeSignaling();
5903 auto first_sender = caller()->AddVideoTrack();
5904 caller()->AddVideoTrack();
5905
5906 caller()->CreateAndSetAndSignalOffer();
5907 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5908
5909 // Verify that there is only one receiver and it corresponds to the first
5910 // added track.
5911 auto receivers = callee()->pc()->GetReceivers();
5912 ASSERT_EQ(1u, receivers.size());
5913 EXPECT_TRUE(receivers[0]->track()->enabled());
5914 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5915
Seth Hampson2f0d7022018-02-20 11:54:42 -08005916 MediaExpectations media_expectations;
5917 media_expectations.CalleeExpectsSomeVideo();
5918 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005919}
5920
Steve Anton2bed3972019-01-04 17:04:30 -08005921// Test that if the initial offer tagged BUNDLE section is rejected due to its
5922// associated RtpTransceiver being stopped and another transceiver is added,
5923// then renegotiation causes the callee to receive the new video track without
5924// error.
5925// This is a regression test for bugs.webrtc.org/9954
5926TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5927 ReOfferWithStoppedBundleTaggedTransceiver) {
5928 RTCConfiguration config;
5929 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5930 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5931 ConnectFakeSignaling();
5932 auto audio_transceiver_or_error =
5933 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5934 ASSERT_TRUE(audio_transceiver_or_error.ok());
5935 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5936
5937 caller()->CreateAndSetAndSignalOffer();
5938 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5939 {
5940 MediaExpectations media_expectations;
5941 media_expectations.CalleeExpectsSomeAudio();
5942 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5943 }
5944
5945 audio_transceiver->Stop();
5946 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5947
5948 caller()->CreateAndSetAndSignalOffer();
5949 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5950 {
5951 MediaExpectations media_expectations;
5952 media_expectations.CalleeExpectsSomeVideo();
5953 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5954 }
5955}
5956
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005957#ifdef HAVE_SCTP
5958
5959TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5960 EndToEndCallWithBundledSctpDataChannel) {
5961 ASSERT_TRUE(CreatePeerConnectionWrappers());
5962 ConnectFakeSignaling();
5963 caller()->CreateDataChannel();
5964 caller()->AddAudioVideoTracks();
5965 callee()->AddAudioVideoTracks();
5966 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
5967 caller()->CreateAndSetAndSignalOffer();
5968 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5969 // Ensure that media and data are multiplexed on the same DTLS transport.
5970 // This only works on Unified Plan, because transports are not exposed in plan
5971 // B.
5972 auto sctp_info = caller()->pc()->GetSctpTransport()->Information();
5973 EXPECT_EQ(sctp_info.dtls_transport(),
5974 caller()->pc()->GetSenders()[0]->dtls_transport());
5975}
5976
5977#endif // HAVE_SCTP
5978
deadbeef1dcb1642017-03-29 21:08:16 -07005979} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01005980} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07005981
5982#endif // if !defined(THREAD_SANITIZER)