blob: 88de3a434cc9c234e7fd40fcec6035815eca694f [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
Taylor Brandstetterd3ef4992020-10-15 18:22:57 -070017#include <algorithm>
deadbeef1dcb1642017-03-29 21:08:16 -070018#include <functional>
19#include <list>
20#include <map>
21#include <memory>
22#include <utility>
23#include <vector>
24
Steve Anton64b626b2019-01-28 17:25:26 -080025#include "absl/algorithm/container.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "api/media_stream_interface.h"
27#include "api/peer_connection_interface.h"
28#include "api/peer_connection_proxy.h"
Danil Chapovalov9da25bd2019-06-20 10:19:42 +020029#include "api/rtc_event_log/rtc_event_log_factory.h"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "api/rtp_receiver_interface.h"
Danil Chapovalov9da25bd2019-06-20 10:19:42 +020031#include "api/task_queue/default_task_queue_factory.h"
Erik Språngceb44952020-09-22 11:36:35 +020032#include "api/transport/field_trial_based_config.h"
Steve Anton10542f22019-01-11 09:11:00 -080033#include "api/uma_metrics.h"
Anders Carlsson67537952018-05-03 11:28:29 +020034#include "api/video_codecs/sdp_video_format.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070035#include "call/call.h"
36#include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
Steve Anton10542f22019-01-11 09:11:00 -080037#include "media/engine/fake_webrtc_video_engine.h"
38#include "media/engine/webrtc_media_engine.h"
Danil Chapovalov9da25bd2019-06-20 10:19:42 +020039#include "media/engine/webrtc_media_engine_defaults.h"
Per Åhgrencc73ed32020-04-26 23:56:17 +020040#include "modules/audio_processing/test/audio_processing_builder_for_testing.h"
Qingsi Wang25ec8882019-11-15 12:33:05 -080041#include "p2p/base/fake_ice_transport.h"
Steve Anton10542f22019-01-11 09:11:00 -080042#include "p2p/base/mock_async_resolver.h"
43#include "p2p/base/p2p_constants.h"
44#include "p2p/base/port_interface.h"
45#include "p2p/base/test_stun_server.h"
46#include "p2p/base/test_turn_customizer.h"
47#include "p2p/base/test_turn_server.h"
48#include "p2p/client/basic_port_allocator.h"
49#include "pc/dtmf_sender.h"
50#include "pc/local_audio_source.h"
51#include "pc/media_session.h"
52#include "pc/peer_connection.h"
53#include "pc/peer_connection_factory.h"
54#include "pc/rtp_media_utils.h"
55#include "pc/session_description.h"
56#include "pc/test/fake_audio_capture_module.h"
57#include "pc/test/fake_periodic_video_track_source.h"
58#include "pc/test/fake_rtc_certificate_generator.h"
59#include "pc/test/fake_video_track_renderer.h"
60#include "pc/test/mock_peer_connection_observers.h"
Jonas Olssonb75d9e92019-02-22 10:33:29 +010061#include "rtc_base/fake_clock.h"
Qingsi Wangecd30542019-05-22 14:34:56 -070062#include "rtc_base/fake_mdns_responder.h"
Steve Anton10542f22019-01-11 09:11:00 -080063#include "rtc_base/fake_network.h"
64#include "rtc_base/firewall_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020065#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020066#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080067#include "rtc_base/test_certificate_verifier.h"
68#include "rtc_base/time_utils.h"
69#include "rtc_base/virtual_socket_server.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020070#include "system_wrappers/include/metrics.h"
Qingsi Wangc129c352019-04-18 10:41:58 -070071#include "test/field_trial.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020072#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070073
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010074namespace webrtc {
75namespace {
76
77using ::cricket::ContentInfo;
78using ::cricket::StreamParams;
79using ::rtc::SocketAddress;
80using ::testing::_;
Seth Hampson2f0d7022018-02-20 11:54:42 -080081using ::testing::Combine;
Steve Anton64b626b2019-01-28 17:25:26 -080082using ::testing::Contains;
Mirko Bonadeie46f5db2019-03-26 20:14:46 +010083using ::testing::DoAll;
Steve Antonede9ca52017-10-16 13:04:27 -070084using ::testing::ElementsAre;
Qingsi Wang1dac6d82018-12-12 15:28:47 -080085using ::testing::NiceMock;
Steve Anton64b626b2019-01-28 17:25:26 -080086using ::testing::Return;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070087using ::testing::SetArgPointee;
Steve Antonffa6ce42018-11-30 09:26:08 -080088using ::testing::UnorderedElementsAreArray;
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010089using ::testing::Values;
Steve Anton74255ff2018-01-24 18:32:57 -080090using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -070091
92static const int kDefaultTimeout = 10000;
93static const int kMaxWaitForStatsMs = 3000;
94static const int kMaxWaitForActivationMs = 5000;
95static const int kMaxWaitForFramesMs = 10000;
96// Default number of audio/video frames to wait for before considering a test
97// successful.
98static const int kDefaultExpectedAudioFrameCount = 3;
99static const int kDefaultExpectedVideoFrameCount = 3;
100
deadbeef1dcb1642017-03-29 21:08:16 -0700101static const char kDataChannelLabel[] = "data_channel";
102
103// SRTP cipher name negotiated by the tests. This must be updated if the
104// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700105static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700106static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
107
Steve Antonede9ca52017-10-16 13:04:27 -0700108static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
109
deadbeef1dcb1642017-03-29 21:08:16 -0700110// Helper function for constructing offer/answer options to initiate an ICE
111// restart.
112PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
113 PeerConnectionInterface::RTCOfferAnswerOptions options;
114 options.ice_restart = true;
115 return options;
116}
117
deadbeefd8ad7882017-04-18 16:01:17 -0700118// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
119// attribute from received SDP, simulating a legacy endpoint.
120void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
121 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800122 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700123 }
124 desc->set_msid_supported(false);
Henrik Boström5b147782018-12-04 11:25:05 +0100125 desc->set_msid_signaling(0);
deadbeefd8ad7882017-04-18 16:01:17 -0700126}
127
Seth Hampson5897a6e2018-04-03 11:16:33 -0700128// Removes all stream information besides the stream ids, simulating an
129// endpoint that only signals a=msid lines to convey stream_ids.
130void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
131 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700132 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700133 std::vector<std::string> stream_ids;
134 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700135 const StreamParams& first_stream =
136 content.media_description()->streams()[0];
137 track_id = first_stream.id;
138 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700139 }
140 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700141 StreamParams new_stream;
142 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700143 new_stream.set_stream_ids(stream_ids);
144 content.media_description()->AddStream(new_stream);
145 }
146}
147
zhihuangf8164932017-05-19 13:09:47 -0700148int FindFirstMediaStatsIndexByKind(
149 const std::string& kind,
150 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
151 media_stats_vec) {
152 for (size_t i = 0; i < media_stats_vec.size(); i++) {
153 if (media_stats_vec[i]->kind.ValueToString() == kind) {
154 return i;
155 }
156 }
157 return -1;
158}
159
deadbeef1dcb1642017-03-29 21:08:16 -0700160class SignalingMessageReceiver {
161 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800162 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700163 virtual void ReceiveIceMessage(const std::string& sdp_mid,
164 int sdp_mline_index,
165 const std::string& msg) = 0;
166
167 protected:
168 SignalingMessageReceiver() {}
169 virtual ~SignalingMessageReceiver() {}
170};
171
172class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
173 public:
174 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
175 : expected_media_type_(media_type) {}
176
177 void OnFirstPacketReceived(cricket::MediaType media_type) override {
178 ASSERT_EQ(expected_media_type_, media_type);
179 first_packet_received_ = true;
180 }
181
182 bool first_packet_received() const { return first_packet_received_; }
183
184 virtual ~MockRtpReceiverObserver() {}
185
186 private:
187 bool first_packet_received_ = false;
188 cricket::MediaType expected_media_type_;
189};
190
191// Helper class that wraps a peer connection, observes it, and can accept
192// signaling messages from another wrapper.
193//
194// Uses a fake network, fake A/V capture, and optionally fake
195// encoders/decoders, though they aren't used by default since they don't
196// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700197// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800198// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700199class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800200 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700201 public:
202 // Different factory methods for convenience.
203 // TODO(deadbeef): Could use the pattern of:
204 //
205 // PeerConnectionWrapper =
206 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
207 //
208 // To reduce some code duplication.
209 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
210 const std::string& debug_name,
211 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
212 rtc::Thread* network_thread,
213 rtc::Thread* worker_thread) {
214 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700215 webrtc::PeerConnectionDependencies dependencies(nullptr);
216 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200217 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800218 worker_thread, nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +0200219 /*reset_encoder_factory=*/false,
220 /*reset_decoder_factory=*/false)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700221 delete client;
222 return nullptr;
223 }
224 return client;
225 }
226
deadbeef2f425aa2017-04-14 10:41:32 -0700227 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
228 return peer_connection_factory_.get();
229 }
230
deadbeef1dcb1642017-03-29 21:08:16 -0700231 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
232
233 // If a signaling message receiver is set (via ConnectFakeSignaling), this
234 // will set the whole offer/answer exchange in motion. Just need to wait for
235 // the signaling state to reach "stable".
236 void CreateAndSetAndSignalOffer() {
Eldar Rello5ab79e62019-10-09 18:29:44 +0300237 auto offer = CreateOfferAndWait();
deadbeef1dcb1642017-03-29 21:08:16 -0700238 ASSERT_NE(nullptr, offer);
239 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
240 }
241
242 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
243 // when a remote offer is received (via fake signaling) and an answer is
244 // generated. By default, uses default options.
245 void SetOfferAnswerOptions(
246 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
247 offer_answer_options_ = options;
248 }
249
250 // Set a callback to be invoked when SDP is received via the fake signaling
251 // channel, which provides an opportunity to munge (modify) the SDP. This is
252 // used to test SDP being applied that a PeerConnection would normally not
253 // generate, but a non-JSEP endpoint might.
254 void SetReceivedSdpMunger(
255 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100256 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700257 }
258
deadbeefc964d0b2017-04-03 10:03:35 -0700259 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700260 // generated.
261 void SetGeneratedSdpMunger(
262 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100263 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700264 }
265
Seth Hampson2f0d7022018-02-20 11:54:42 -0800266 // Set a callback to be invoked when a remote offer is received via the fake
267 // signaling channel. This provides an opportunity to change the
268 // PeerConnection state before an answer is created and sent to the caller.
269 void SetRemoteOfferHandler(std::function<void()> handler) {
270 remote_offer_handler_ = std::move(handler);
271 }
272
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800273 void SetRemoteAsyncResolver(rtc::MockAsyncResolver* resolver) {
274 remote_async_resolver_ = resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700275 }
276
Steve Antonede9ca52017-10-16 13:04:27 -0700277 // Every ICE connection state in order that has been seen by the observer.
278 std::vector<PeerConnectionInterface::IceConnectionState>
279 ice_connection_state_history() const {
280 return ice_connection_state_history_;
281 }
Steve Anton6f25b092017-10-23 09:39:20 -0700282 void clear_ice_connection_state_history() {
283 ice_connection_state_history_.clear();
284 }
Steve Antonede9ca52017-10-16 13:04:27 -0700285
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100286 // Every standardized ICE connection state in order that has been seen by the
287 // observer.
288 std::vector<PeerConnectionInterface::IceConnectionState>
289 standardized_ice_connection_state_history() const {
290 return standardized_ice_connection_state_history_;
291 }
292
Jonas Olsson635474e2018-10-18 15:58:17 +0200293 // Every PeerConnection state in order that has been seen by the observer.
294 std::vector<PeerConnectionInterface::PeerConnectionState>
295 peer_connection_state_history() const {
296 return peer_connection_state_history_;
297 }
298
Steve Antonede9ca52017-10-16 13:04:27 -0700299 // Every ICE gathering state in order that has been seen by the observer.
300 std::vector<PeerConnectionInterface::IceGatheringState>
301 ice_gathering_state_history() const {
302 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700303 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700304 std::vector<cricket::CandidatePairChangeEvent>
305 ice_candidate_pair_change_history() const {
306 return ice_candidate_pair_change_history_;
307 }
deadbeef1dcb1642017-03-29 21:08:16 -0700308
Eldar Rello5ab79e62019-10-09 18:29:44 +0300309 // Every PeerConnection signaling state in order that has been seen by the
310 // observer.
311 std::vector<PeerConnectionInterface::SignalingState>
312 peer_connection_signaling_state_history() const {
313 return peer_connection_signaling_state_history_;
314 }
315
Steve Anton15324772018-01-16 10:26:49 -0800316 void AddAudioVideoTracks() {
317 AddAudioTrack();
318 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700319 }
320
Steve Anton74255ff2018-01-24 18:32:57 -0800321 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
322 return AddTrack(CreateLocalAudioTrack());
323 }
deadbeef1dcb1642017-03-29 21:08:16 -0700324
Steve Anton74255ff2018-01-24 18:32:57 -0800325 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
326 return AddTrack(CreateLocalVideoTrack());
327 }
deadbeef1dcb1642017-03-29 21:08:16 -0700328
329 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200330 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700331 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200332 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700333 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200334 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700335 // TODO(perkj): Test audio source when it is implemented. Currently audio
336 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700337 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700338 source);
339 }
340
341 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200342 webrtc::FakePeriodicVideoSource::Config config;
343 config.timestamp_offset_ms = rtc::TimeMillis();
344 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700345 }
346
347 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200348 CreateLocalVideoTrackWithConfig(
349 webrtc::FakePeriodicVideoSource::Config config) {
350 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700351 }
352
353 rtc::scoped_refptr<webrtc::VideoTrackInterface>
354 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200355 webrtc::FakePeriodicVideoSource::Config config;
356 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200357 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200358 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700359 }
360
Steve Anton74255ff2018-01-24 18:32:57 -0800361 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
362 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800363 const std::vector<std::string>& stream_ids = {}) {
364 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800365 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800366 return result.MoveValue();
367 }
368
369 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
370 cricket::MediaType media_type) {
371 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +0100372 for (const auto& receiver : pc()->GetReceivers()) {
Steve Anton74255ff2018-01-24 18:32:57 -0800373 if (receiver->media_type() == media_type) {
374 receivers.push_back(receiver);
375 }
376 }
377 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700378 }
379
Seth Hampson2f0d7022018-02-20 11:54:42 -0800380 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
381 cricket::MediaType media_type) {
382 for (auto transceiver : pc()->GetTransceivers()) {
383 if (transceiver->receiver()->media_type() == media_type) {
384 return transceiver;
385 }
386 }
387 return nullptr;
388 }
389
deadbeef1dcb1642017-03-29 21:08:16 -0700390 bool SignalingStateStable() {
391 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
392 }
393
394 void CreateDataChannel() { CreateDataChannel(nullptr); }
395
396 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700397 CreateDataChannel(kDataChannelLabel, init);
398 }
399
400 void CreateDataChannel(const std::string& label,
401 const webrtc::DataChannelInit* init) {
402 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700403 ASSERT_TRUE(data_channel_.get() != nullptr);
404 data_observer_.reset(new MockDataChannelObserver(data_channel_));
405 }
406
407 DataChannelInterface* data_channel() { return data_channel_; }
408 const MockDataChannelObserver* data_observer() const {
409 return data_observer_.get();
410 }
411
412 int audio_frames_received() const {
413 return fake_audio_capture_module_->frames_received();
414 }
415
416 // Takes minimum of video frames received for each track.
417 //
418 // Can be used like:
419 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
420 //
421 // To ensure that all video tracks received at least a certain number of
422 // frames.
423 int min_video_frames_received_per_track() const {
424 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200425 if (fake_video_renderers_.empty()) {
426 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700427 }
deadbeef1dcb1642017-03-29 21:08:16 -0700428
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200429 for (const auto& pair : fake_video_renderers_) {
430 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700431 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200432 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700433 }
434
435 // Returns a MockStatsObserver in a state after stats gathering finished,
436 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700437 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700438 webrtc::MediaStreamTrackInterface* track) {
439 rtc::scoped_refptr<MockStatsObserver> observer(
440 new rtc::RefCountedObject<MockStatsObserver>());
441 EXPECT_TRUE(peer_connection_->GetStats(
442 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
443 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
444 return observer;
445 }
446
447 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700448 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
449 return OldGetStatsForTrack(nullptr);
450 }
451
452 // Synchronously gets stats and returns them. If it times out, fails the test
453 // and returns null.
454 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
455 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
456 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
457 peer_connection_->GetStats(callback);
458 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
459 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700460 }
461
462 int rendered_width() {
463 EXPECT_FALSE(fake_video_renderers_.empty());
464 return fake_video_renderers_.empty()
465 ? 0
466 : fake_video_renderers_.begin()->second->width();
467 }
468
469 int rendered_height() {
470 EXPECT_FALSE(fake_video_renderers_.empty());
471 return fake_video_renderers_.empty()
472 ? 0
473 : fake_video_renderers_.begin()->second->height();
474 }
475
476 double rendered_aspect_ratio() {
477 if (rendered_height() == 0) {
478 return 0.0;
479 }
480 return static_cast<double>(rendered_width()) / rendered_height();
481 }
482
483 webrtc::VideoRotation rendered_rotation() {
484 EXPECT_FALSE(fake_video_renderers_.empty());
485 return fake_video_renderers_.empty()
486 ? webrtc::kVideoRotation_0
487 : fake_video_renderers_.begin()->second->rotation();
488 }
489
490 int local_rendered_width() {
491 return local_video_renderer_ ? local_video_renderer_->width() : 0;
492 }
493
494 int local_rendered_height() {
495 return local_video_renderer_ ? local_video_renderer_->height() : 0;
496 }
497
498 double local_rendered_aspect_ratio() {
499 if (local_rendered_height() == 0) {
500 return 0.0;
501 }
502 return static_cast<double>(local_rendered_width()) /
503 local_rendered_height();
504 }
505
506 size_t number_of_remote_streams() {
507 if (!pc()) {
508 return 0;
509 }
510 return pc()->remote_streams()->count();
511 }
512
513 StreamCollectionInterface* remote_streams() const {
514 if (!pc()) {
515 ADD_FAILURE();
516 return nullptr;
517 }
518 return pc()->remote_streams();
519 }
520
521 StreamCollectionInterface* local_streams() {
522 if (!pc()) {
523 ADD_FAILURE();
524 return nullptr;
525 }
526 return pc()->local_streams();
527 }
528
529 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
530 return pc()->signaling_state();
531 }
532
533 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
534 return pc()->ice_connection_state();
535 }
536
Jonas Olsson7a6739e2019-01-15 16:31:55 +0100537 webrtc::PeerConnectionInterface::IceConnectionState
538 standardized_ice_connection_state() {
539 return pc()->standardized_ice_connection_state();
540 }
541
deadbeef1dcb1642017-03-29 21:08:16 -0700542 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
543 return pc()->ice_gathering_state();
544 }
545
546 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
547 // GetReceivers. They're updated automatically when a remote offer/answer
548 // from the fake signaling channel is applied, or when
549 // ResetRtpReceiverObservers below is called.
550 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
551 rtp_receiver_observers() {
552 return rtp_receiver_observers_;
553 }
554
555 void ResetRtpReceiverObservers() {
556 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100557 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
558 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700559 std::unique_ptr<MockRtpReceiverObserver> observer(
560 new MockRtpReceiverObserver(receiver->media_type()));
561 receiver->SetObserver(observer.get());
562 rtp_receiver_observers_.push_back(std::move(observer));
563 }
564 }
565
Qingsi Wangecd30542019-05-22 14:34:56 -0700566 rtc::FakeNetworkManager* network_manager() const {
Steve Antonede9ca52017-10-16 13:04:27 -0700567 return fake_network_manager_.get();
568 }
569 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
570
Qingsi Wang7685e862018-06-11 20:15:46 -0700571 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
572 return event_log_factory_;
573 }
574
Qingsi Wangc129c352019-04-18 10:41:58 -0700575 const cricket::Candidate& last_candidate_gathered() const {
576 return last_candidate_gathered_;
577 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300578 const cricket::IceCandidateErrorEvent& error_event() const {
579 return error_event_;
580 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700581
Qingsi Wangecd30542019-05-22 14:34:56 -0700582 // Sets the mDNS responder for the owned fake network manager and keeps a
583 // reference to the responder.
584 void SetMdnsResponder(
585 std::unique_ptr<webrtc::FakeMdnsResponder> mdns_responder) {
586 RTC_DCHECK(mdns_responder != nullptr);
587 mdns_responder_ = mdns_responder.get();
588 network_manager()->set_mdns_responder(std::move(mdns_responder));
589 }
590
Eldar Rello5ab79e62019-10-09 18:29:44 +0300591 // Returns null on failure.
592 std::unique_ptr<SessionDescriptionInterface> CreateOfferAndWait() {
593 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
594 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
595 pc()->CreateOffer(observer, offer_answer_options_);
596 return WaitForDescriptionFromObserver(observer);
597 }
Eldar Rellod9ebe012020-03-18 20:41:45 +0200598 bool Rollback() {
599 return SetRemoteDescription(
600 webrtc::CreateSessionDescription(SdpType::kRollback, ""));
601 }
Eldar Rello5ab79e62019-10-09 18:29:44 +0300602
deadbeef1dcb1642017-03-29 21:08:16 -0700603 private:
604 explicit PeerConnectionWrapper(const std::string& debug_name)
605 : debug_name_(debug_name) {}
606
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800607 bool Init(
608 const PeerConnectionFactory::Options* options,
609 const PeerConnectionInterface::RTCConfiguration* config,
610 webrtc::PeerConnectionDependencies dependencies,
611 rtc::Thread* network_thread,
612 rtc::Thread* worker_thread,
613 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron3e983682020-03-29 22:17:00 +0200614 bool reset_encoder_factory,
615 bool reset_decoder_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700616 // There's an error in this test code if Init ends up being called twice.
617 RTC_DCHECK(!peer_connection_);
618 RTC_DCHECK(!peer_connection_factory_);
619
620 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700621 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700622
623 std::unique_ptr<cricket::PortAllocator> port_allocator(
624 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700625 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700626 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
627 if (!fake_audio_capture_module_) {
628 return false;
629 }
deadbeef1dcb1642017-03-29 21:08:16 -0700630 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700631
632 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
633 pc_factory_dependencies.network_thread = network_thread;
634 pc_factory_dependencies.worker_thread = worker_thread;
635 pc_factory_dependencies.signaling_thread = signaling_thread;
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200636 pc_factory_dependencies.task_queue_factory =
637 webrtc::CreateDefaultTaskQueueFactory();
Erik Språngceb44952020-09-22 11:36:35 +0200638 pc_factory_dependencies.trials = std::make_unique<FieldTrialBasedConfig>();
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200639 cricket::MediaEngineDependencies media_deps;
640 media_deps.task_queue_factory =
641 pc_factory_dependencies.task_queue_factory.get();
642 media_deps.adm = fake_audio_capture_module_;
643 webrtc::SetMediaEngineDefaults(&media_deps);
Johannes Kron3e983682020-03-29 22:17:00 +0200644
645 if (reset_encoder_factory) {
646 media_deps.video_encoder_factory.reset();
647 }
648 if (reset_decoder_factory) {
649 media_deps.video_decoder_factory.reset();
650 }
651
Per Åhgrencc73ed32020-04-26 23:56:17 +0200652 if (!media_deps.audio_processing) {
653 // If the standard Creation method for APM returns a null pointer, instead
654 // use the builder for testing to create an APM object.
655 media_deps.audio_processing = AudioProcessingBuilderForTesting().Create();
656 }
657
Erik Språngceb44952020-09-22 11:36:35 +0200658 media_deps.trials = pc_factory_dependencies.trials.get();
659
Qingsi Wang7685e862018-06-11 20:15:46 -0700660 pc_factory_dependencies.media_engine =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200661 cricket::CreateMediaEngine(std::move(media_deps));
Qingsi Wang7685e862018-06-11 20:15:46 -0700662 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
663 if (event_log_factory) {
664 event_log_factory_ = event_log_factory.get();
665 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
666 } else {
667 pc_factory_dependencies.event_log_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200668 std::make_unique<webrtc::RtcEventLogFactory>(
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200669 pc_factory_dependencies.task_queue_factory.get());
Qingsi Wang7685e862018-06-11 20:15:46 -0700670 }
671 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
672 std::move(pc_factory_dependencies));
673
deadbeef1dcb1642017-03-29 21:08:16 -0700674 if (!peer_connection_factory_) {
675 return false;
676 }
677 if (options) {
678 peer_connection_factory_->SetOptions(*options);
679 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800680 if (config) {
681 sdp_semantics_ = config->sdp_semantics;
682 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700683
684 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200685 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700686 return peer_connection_.get() != nullptr;
687 }
688
689 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700690 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700691 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700692 PeerConnectionInterface::RTCConfiguration modified_config;
693 // If |config| is null, this will result in a default configuration being
694 // used.
695 if (config) {
696 modified_config = *config;
697 }
698 // Disable resolution adaptation; we don't want it interfering with the
699 // test results.
700 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
701 // ratios and not specific resolutions, is this even necessary?
702 modified_config.set_cpu_adaptation(false);
703
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700704 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700705 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700706 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700707 }
708
709 void set_signaling_message_receiver(
710 SignalingMessageReceiver* signaling_message_receiver) {
711 signaling_message_receiver_ = signaling_message_receiver;
712 }
713
714 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
715
Steve Antonede9ca52017-10-16 13:04:27 -0700716 void set_signal_ice_candidates(bool signal) {
717 signal_ice_candidates_ = signal;
718 }
719
deadbeef1dcb1642017-03-29 21:08:16 -0700720 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200721 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700722 // Set max frame rate to 10fps to reduce the risk of test flakiness.
723 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200724 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700725
Niels Möller5c7efe72018-05-11 10:34:46 +0200726 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200727 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
728 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700729 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200730 peer_connection_factory_->CreateVideoTrack(
731 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700732 if (!local_video_renderer_) {
733 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
734 }
735 return track;
736 }
737
738 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100739 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800740 std::unique_ptr<SessionDescriptionInterface> desc =
741 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700742 if (received_sdp_munger_) {
743 received_sdp_munger_(desc->description());
744 }
745
746 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
747 // Setting a remote description may have changed the number of receivers,
748 // so reset the receiver observers.
749 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800750 if (remote_offer_handler_) {
751 remote_offer_handler_();
752 }
deadbeef1dcb1642017-03-29 21:08:16 -0700753 auto answer = CreateAnswer();
754 ASSERT_NE(nullptr, answer);
755 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
756 }
757
758 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100759 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800760 std::unique_ptr<SessionDescriptionInterface> desc =
761 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700762 if (received_sdp_munger_) {
763 received_sdp_munger_(desc->description());
764 }
765
766 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
767 // Set the RtpReceiverObserver after receivers are created.
768 ResetRtpReceiverObservers();
769 }
770
771 // Returns null on failure.
deadbeef1dcb1642017-03-29 21:08:16 -0700772 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
773 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
774 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
775 pc()->CreateAnswer(observer, offer_answer_options_);
776 return WaitForDescriptionFromObserver(observer);
777 }
778
779 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100780 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700781 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
782 if (!observer->result()) {
783 return nullptr;
784 }
785 auto description = observer->MoveDescription();
786 if (generated_sdp_munger_) {
787 generated_sdp_munger_(description->description());
788 }
789 return description;
790 }
791
792 // Setting the local description and sending the SDP message over the fake
793 // signaling channel are combined into the same method because the SDP
794 // message needs to be sent as soon as SetLocalDescription finishes, without
795 // waiting for the observer to be called. This ensures that ICE candidates
796 // don't outrace the description.
797 bool SetLocalDescriptionAndSendSdpMessage(
798 std::unique_ptr<SessionDescriptionInterface> desc) {
799 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
800 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100801 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800802 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700803 std::string sdp;
804 EXPECT_TRUE(desc->ToString(&sdp));
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700805 RTC_LOG(LS_INFO) << debug_name_ << ": local SDP contents=\n" << sdp;
deadbeef1dcb1642017-03-29 21:08:16 -0700806 pc()->SetLocalDescription(observer, desc.release());
Harald Alvestrand6060df52020-08-11 09:54:02 +0200807 RemoveUnusedVideoRenderers();
deadbeef1dcb1642017-03-29 21:08:16 -0700808 // As mentioned above, we need to send the message immediately after
809 // SetLocalDescription.
810 SendSdpMessage(type, sdp);
811 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
812 return true;
813 }
814
815 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
816 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
817 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100818 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700819 pc()->SetRemoteDescription(observer, desc.release());
Harald Alvestrand6060df52020-08-11 09:54:02 +0200820 RemoveUnusedVideoRenderers();
deadbeef1dcb1642017-03-29 21:08:16 -0700821 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
822 return observer->result();
823 }
824
Seth Hampson2f0d7022018-02-20 11:54:42 -0800825 // This is a work around to remove unused fake_video_renderers from
826 // transceivers that have either stopped or are no longer receiving.
827 void RemoveUnusedVideoRenderers() {
Harald Alvestrand6060df52020-08-11 09:54:02 +0200828 if (sdp_semantics_ != SdpSemantics::kUnifiedPlan) {
829 return;
830 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800831 auto transceivers = pc()->GetTransceivers();
Harald Alvestrand6060df52020-08-11 09:54:02 +0200832 std::set<std::string> active_renderers;
Seth Hampson2f0d7022018-02-20 11:54:42 -0800833 for (auto& transceiver : transceivers) {
Harald Alvestrand6060df52020-08-11 09:54:02 +0200834 // Note - we don't check for direction here. This function is called
835 // before direction is set, and in that case, we should not remove
836 // the renderer.
837 if (transceiver->receiver()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
838 active_renderers.insert(transceiver->receiver()->track()->id());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800839 }
Harald Alvestrand6060df52020-08-11 09:54:02 +0200840 }
841 for (auto it = fake_video_renderers_.begin();
842 it != fake_video_renderers_.end();) {
843 // Remove fake video renderers belonging to any non-active transceivers.
844 if (!active_renderers.count(it->first)) {
845 it = fake_video_renderers_.erase(it);
846 } else {
847 it++;
Seth Hampson2f0d7022018-02-20 11:54:42 -0800848 }
849 }
850 }
851
deadbeef1dcb1642017-03-29 21:08:16 -0700852 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
853 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800854 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700855 if (signaling_delay_ms_ == 0) {
856 RelaySdpMessageIfReceiverExists(type, msg);
857 } else {
858 invoker_.AsyncInvokeDelayed<void>(
859 RTC_FROM_HERE, rtc::Thread::Current(),
860 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
861 this, type, msg),
862 signaling_delay_ms_);
863 }
864 }
865
Steve Antona3a92c22017-12-07 10:27:41 -0800866 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700867 if (signaling_message_receiver_) {
868 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
869 }
870 }
871
872 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
873 // default).
874 void SendIceMessage(const std::string& sdp_mid,
875 int sdp_mline_index,
876 const std::string& msg) {
877 if (signaling_delay_ms_ == 0) {
878 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
879 } else {
880 invoker_.AsyncInvokeDelayed<void>(
881 RTC_FROM_HERE, rtc::Thread::Current(),
882 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
883 this, sdp_mid, sdp_mline_index, msg),
884 signaling_delay_ms_);
885 }
886 }
887
888 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
889 int sdp_mline_index,
890 const std::string& msg) {
891 if (signaling_message_receiver_) {
892 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
893 msg);
894 }
895 }
896
897 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800898 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
899 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700900 HandleIncomingOffer(msg);
901 } else {
902 HandleIncomingAnswer(msg);
903 }
904 }
905
906 void ReceiveIceMessage(const std::string& sdp_mid,
907 int sdp_mline_index,
908 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100909 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700910 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
911 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
912 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
913 }
914
915 // PeerConnectionObserver callbacks.
916 void OnSignalingChange(
917 webrtc::PeerConnectionInterface::SignalingState new_state) override {
918 EXPECT_EQ(pc()->signaling_state(), new_state);
Eldar Rello5ab79e62019-10-09 18:29:44 +0300919 peer_connection_signaling_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700920 }
Steve Anton15324772018-01-16 10:26:49 -0800921 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
922 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
923 streams) override {
924 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
925 rtc::scoped_refptr<VideoTrackInterface> video_track(
926 static_cast<VideoTrackInterface*>(receiver->track().get()));
927 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700928 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800929 fake_video_renderers_[video_track->id()] =
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200930 std::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700931 }
932 }
Steve Anton15324772018-01-16 10:26:49 -0800933 void OnRemoveTrack(
934 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
935 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
936 auto it = fake_video_renderers_.find(receiver->track()->id());
Harald Alvestrand6060df52020-08-11 09:54:02 +0200937 if (it != fake_video_renderers_.end()) {
938 fake_video_renderers_.erase(it);
939 } else {
940 RTC_LOG(LS_ERROR) << "OnRemoveTrack called for non-active renderer";
941 }
Steve Anton15324772018-01-16 10:26:49 -0800942 }
943 }
deadbeef1dcb1642017-03-29 21:08:16 -0700944 void OnRenegotiationNeeded() override {}
945 void OnIceConnectionChange(
946 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
947 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700948 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700949 }
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100950 void OnStandardizedIceConnectionChange(
951 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
952 standardized_ice_connection_state_history_.push_back(new_state);
953 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200954 void OnConnectionChange(
955 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
956 peer_connection_state_history_.push_back(new_state);
957 }
958
deadbeef1dcb1642017-03-29 21:08:16 -0700959 void OnIceGatheringChange(
960 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700961 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700962 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700963 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700964
965 void OnIceSelectedCandidatePairChanged(
966 const cricket::CandidatePairChangeEvent& event) {
967 ice_candidate_pair_change_history_.push_back(event);
968 }
Alex Drake43faee02019-08-12 16:27:34 -0700969
deadbeef1dcb1642017-03-29 21:08:16 -0700970 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100971 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700972
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800973 if (remote_async_resolver_) {
974 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800975 if (local_candidate.address().IsUnresolvedIP()) {
976 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
977 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700978 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800979 local_candidate.address().hostname());
980 RTC_DCHECK(!resolved_ip.IsNil());
981 resolved_addr.SetResolvedIP(resolved_ip);
982 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
983 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
984 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700985 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700986 }
987
deadbeef1dcb1642017-03-29 21:08:16 -0700988 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800989 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700990 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700991 // Remote party may be deleted.
992 return;
993 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800994 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700995 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700996 }
Eldar Rello0095d372019-12-02 22:22:07 +0200997 void OnIceCandidateError(const std::string& address,
998 int port,
Eldar Relloda13ea22019-06-01 12:23:43 +0300999 const std::string& url,
1000 int error_code,
1001 const std::string& error_text) override {
Eldar Rello0095d372019-12-02 22:22:07 +02001002 error_event_ = cricket::IceCandidateErrorEvent(address, port, url,
Eldar Relloda13ea22019-06-01 12:23:43 +03001003 error_code, error_text);
1004 }
deadbeef1dcb1642017-03-29 21:08:16 -07001005 void OnDataChannel(
1006 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001007 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -07001008 data_channel_ = data_channel;
1009 data_observer_.reset(new MockDataChannelObserver(data_channel));
1010 }
1011
deadbeef1dcb1642017-03-29 21:08:16 -07001012 std::string debug_name_;
1013
1014 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -07001015 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
1016 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001017
1018 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
1019 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
1020 peer_connection_factory_;
1021
Steve Antonede9ca52017-10-16 13:04:27 -07001022 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -07001023 // Needed to keep track of number of frames sent.
1024 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
1025 // Needed to keep track of number of frames received.
1026 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1027 fake_video_renderers_;
1028 // Needed to ensure frames aren't received for removed tracks.
1029 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1030 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001031
1032 // For remote peer communication.
1033 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1034 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001035 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001036 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001037 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001038
Niels Möller5c7efe72018-05-11 10:34:46 +02001039 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001040 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001041 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1042 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001043 // |local_video_renderer_| attached to the first created local video track.
1044 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1045
Seth Hampson2f0d7022018-02-20 11:54:42 -08001046 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001047 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1048 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1049 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001050 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001051 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001052 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1053 std::unique_ptr<MockDataChannelObserver> data_observer_;
1054
1055 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1056
Steve Antonede9ca52017-10-16 13:04:27 -07001057 std::vector<PeerConnectionInterface::IceConnectionState>
1058 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001059 std::vector<PeerConnectionInterface::IceConnectionState>
1060 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001061 std::vector<PeerConnectionInterface::PeerConnectionState>
1062 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001063 std::vector<PeerConnectionInterface::IceGatheringState>
1064 ice_gathering_state_history_;
Alex Drake00c7ecf2019-08-06 10:54:47 -07001065 std::vector<cricket::CandidatePairChangeEvent>
1066 ice_candidate_pair_change_history_;
Eldar Rello5ab79e62019-10-09 18:29:44 +03001067 std::vector<PeerConnectionInterface::SignalingState>
1068 peer_connection_signaling_state_history_;
Qingsi Wang7685e862018-06-11 20:15:46 -07001069 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1070
deadbeef1dcb1642017-03-29 21:08:16 -07001071 rtc::AsyncInvoker invoker_;
1072
Seth Hampson2f0d7022018-02-20 11:54:42 -08001073 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001074};
1075
Elad Alon99c3fe52017-10-13 16:29:40 +02001076class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1077 public:
1078 virtual ~MockRtcEventLogOutput() = default;
Danil Chapovalov3a353122020-05-15 11:16:53 +02001079 MOCK_METHOD(bool, IsActive, (), (const, override));
1080 MOCK_METHOD(bool, Write, (const std::string&), (override));
Elad Alon99c3fe52017-10-13 16:29:40 +02001081};
1082
Seth Hampson2f0d7022018-02-20 11:54:42 -08001083// This helper object is used for both specifying how many audio/video frames
1084// are expected to be received for a caller/callee. It provides helper functions
1085// to specify these expectations. The object initially starts in a state of no
1086// expectations.
1087class MediaExpectations {
1088 public:
1089 enum ExpectFrames {
1090 kExpectSomeFrames,
1091 kExpectNoFrames,
1092 kNoExpectation,
1093 };
1094
1095 void ExpectBidirectionalAudioAndVideo() {
1096 ExpectBidirectionalAudio();
1097 ExpectBidirectionalVideo();
1098 }
1099
1100 void ExpectBidirectionalAudio() {
1101 CallerExpectsSomeAudio();
1102 CalleeExpectsSomeAudio();
1103 }
1104
1105 void ExpectNoAudio() {
1106 CallerExpectsNoAudio();
1107 CalleeExpectsNoAudio();
1108 }
1109
1110 void ExpectBidirectionalVideo() {
1111 CallerExpectsSomeVideo();
1112 CalleeExpectsSomeVideo();
1113 }
1114
1115 void ExpectNoVideo() {
1116 CallerExpectsNoVideo();
1117 CalleeExpectsNoVideo();
1118 }
1119
1120 void CallerExpectsSomeAudioAndVideo() {
1121 CallerExpectsSomeAudio();
1122 CallerExpectsSomeVideo();
1123 }
1124
1125 void CalleeExpectsSomeAudioAndVideo() {
1126 CalleeExpectsSomeAudio();
1127 CalleeExpectsSomeVideo();
1128 }
1129
1130 // Caller's audio functions.
1131 void CallerExpectsSomeAudio(
1132 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1133 caller_audio_expectation_ = kExpectSomeFrames;
1134 caller_audio_frames_expected_ = expected_audio_frames;
1135 }
1136
1137 void CallerExpectsNoAudio() {
1138 caller_audio_expectation_ = kExpectNoFrames;
1139 caller_audio_frames_expected_ = 0;
1140 }
1141
1142 // Caller's video functions.
1143 void CallerExpectsSomeVideo(
1144 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1145 caller_video_expectation_ = kExpectSomeFrames;
1146 caller_video_frames_expected_ = expected_video_frames;
1147 }
1148
1149 void CallerExpectsNoVideo() {
1150 caller_video_expectation_ = kExpectNoFrames;
1151 caller_video_frames_expected_ = 0;
1152 }
1153
1154 // Callee's audio functions.
1155 void CalleeExpectsSomeAudio(
1156 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1157 callee_audio_expectation_ = kExpectSomeFrames;
1158 callee_audio_frames_expected_ = expected_audio_frames;
1159 }
1160
1161 void CalleeExpectsNoAudio() {
1162 callee_audio_expectation_ = kExpectNoFrames;
1163 callee_audio_frames_expected_ = 0;
1164 }
1165
1166 // Callee's video functions.
1167 void CalleeExpectsSomeVideo(
1168 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1169 callee_video_expectation_ = kExpectSomeFrames;
1170 callee_video_frames_expected_ = expected_video_frames;
1171 }
1172
1173 void CalleeExpectsNoVideo() {
1174 callee_video_expectation_ = kExpectNoFrames;
1175 callee_video_frames_expected_ = 0;
1176 }
1177
1178 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1179 ExpectFrames caller_video_expectation_ = kNoExpectation;
1180 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1181 ExpectFrames callee_video_expectation_ = kNoExpectation;
1182 int caller_audio_frames_expected_ = 0;
1183 int caller_video_frames_expected_ = 0;
1184 int callee_audio_frames_expected_ = 0;
1185 int callee_video_frames_expected_ = 0;
1186};
1187
Qingsi Wang25ec8882019-11-15 12:33:05 -08001188class MockIceTransport : public webrtc::IceTransportInterface {
1189 public:
1190 MockIceTransport(const std::string& name, int component)
1191 : internal_(std::make_unique<cricket::FakeIceTransport>(
1192 name,
1193 component,
1194 nullptr /* network_thread */)) {}
1195 ~MockIceTransport() = default;
1196 cricket::IceTransportInternal* internal() { return internal_.get(); }
1197
1198 private:
1199 std::unique_ptr<cricket::FakeIceTransport> internal_;
1200};
1201
1202class MockIceTransportFactory : public IceTransportFactory {
1203 public:
1204 ~MockIceTransportFactory() override = default;
1205 rtc::scoped_refptr<IceTransportInterface> CreateIceTransport(
1206 const std::string& transport_name,
1207 int component,
1208 IceTransportInit init) {
1209 RecordIceTransportCreated();
1210 return new rtc::RefCountedObject<MockIceTransport>(transport_name,
1211 component);
1212 }
Danil Chapovalov3a353122020-05-15 11:16:53 +02001213 MOCK_METHOD(void, RecordIceTransportCreated, ());
Qingsi Wang25ec8882019-11-15 12:33:05 -08001214};
1215
deadbeef1dcb1642017-03-29 21:08:16 -07001216// Tests two PeerConnections connecting to each other end-to-end, using a
1217// virtual network, fake A/V capture and fake encoder/decoders. The
1218// PeerConnections share the threads/socket servers, but use separate versions
1219// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001220class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001221 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001222 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1223 : sdp_semantics_(sdp_semantics),
1224 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001225 fss_(new rtc::FirewallSocketServer(ss_.get())),
1226 network_thread_(new rtc::Thread(fss_.get())),
Niels Möller2a707032020-06-16 16:39:13 +02001227 worker_thread_(rtc::Thread::Create()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001228 network_thread_->SetName("PCNetworkThread", this);
1229 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001230 RTC_CHECK(network_thread_->Start());
1231 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001232 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001233 }
1234
Seth Hampson2f0d7022018-02-20 11:54:42 -08001235 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001236 // The PeerConnections should deleted before the TurnCustomizers.
1237 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1238 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1239 // that the TurnCustomizer outlives the life of the PeerConnection or else
1240 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001241 if (caller_) {
1242 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001243 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001244 }
1245 if (callee_) {
1246 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001247 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001248 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001249
1250 // If turn servers were created for the test they need to be destroyed on
1251 // the network thread.
1252 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1253 turn_servers_.clear();
1254 turn_customizers_.clear();
1255 });
deadbeef1dcb1642017-03-29 21:08:16 -07001256 }
1257
1258 bool SignalingStateStable() {
1259 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1260 }
1261
deadbeef71452802017-05-07 17:21:01 -07001262 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001263 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1264 // are connected. This is an important distinction. Once we have separate
1265 // ICE and DTLS state, this check needs to use the DTLS state.
1266 return (callee()->ice_connection_state() ==
1267 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1268 callee()->ice_connection_state() ==
1269 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1270 (caller()->ice_connection_state() ==
1271 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1272 caller()->ice_connection_state() ==
1273 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001274 }
1275
Qingsi Wang7685e862018-06-11 20:15:46 -07001276 // When |event_log_factory| is null, the default implementation of the event
1277 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001278 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1279 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001280 const PeerConnectionFactory::Options* options,
1281 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001282 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001283 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
Johannes Kron3e983682020-03-29 22:17:00 +02001284 bool reset_encoder_factory,
1285 bool reset_decoder_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001286 RTCConfiguration modified_config;
1287 if (config) {
1288 modified_config = *config;
1289 }
Steve Anton3acffc32018-04-12 17:21:03 -07001290 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001291 if (!dependencies.cert_generator) {
1292 dependencies.cert_generator =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001293 std::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001294 }
1295 std::unique_ptr<PeerConnectionWrapper> client(
1296 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001297
Niels Möllerf06f9232018-08-07 12:32:18 +02001298 if (!client->Init(options, &modified_config, std::move(dependencies),
1299 network_thread_.get(), worker_thread_.get(),
Niels Möller2a707032020-06-16 16:39:13 +02001300 std::move(event_log_factory), reset_encoder_factory,
Johannes Kron3e983682020-03-29 22:17:00 +02001301 reset_decoder_factory)) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001302 return nullptr;
1303 }
1304 return client;
1305 }
1306
Qingsi Wang7685e862018-06-11 20:15:46 -07001307 std::unique_ptr<PeerConnectionWrapper>
1308 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1309 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001310 const PeerConnectionFactory::Options* options,
1311 const RTCConfiguration* config,
1312 webrtc::PeerConnectionDependencies dependencies) {
1313 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1314 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möller2a707032020-06-16 16:39:13 +02001315 return CreatePeerConnectionWrapper(debug_name, options, config,
1316 std::move(dependencies),
1317 std::move(event_log_factory),
1318 /*reset_encoder_factory=*/false,
1319 /*reset_decoder_factory=*/false);
Qingsi Wang7685e862018-06-11 20:15:46 -07001320 }
1321
deadbeef1dcb1642017-03-29 21:08:16 -07001322 bool CreatePeerConnectionWrappers() {
1323 return CreatePeerConnectionWrappersWithConfig(
1324 PeerConnectionInterface::RTCConfiguration(),
1325 PeerConnectionInterface::RTCConfiguration());
1326 }
1327
Steve Anton3acffc32018-04-12 17:21:03 -07001328 bool CreatePeerConnectionWrappersWithSdpSemantics(
1329 SdpSemantics caller_semantics,
1330 SdpSemantics callee_semantics) {
1331 // Can't specify the sdp_semantics in the passed-in configuration since it
1332 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1333 // stored in sdp_semantics_. So get around this by modifying the instance
1334 // variable before calling CreatePeerConnectionWrapper for the caller and
1335 // callee PeerConnections.
1336 SdpSemantics original_semantics = sdp_semantics_;
1337 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001338 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001339 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Niels Möller2a707032020-06-16 16:39:13 +02001340 nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001341 /*reset_encoder_factory=*/false,
1342 /*reset_decoder_factory=*/false);
Steve Anton3acffc32018-04-12 17:21:03 -07001343 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001344 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001345 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Niels Möller2a707032020-06-16 16:39:13 +02001346 nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001347 /*reset_encoder_factory=*/false,
1348 /*reset_decoder_factory=*/false);
Steve Anton3acffc32018-04-12 17:21:03 -07001349 sdp_semantics_ = original_semantics;
1350 return caller_ && callee_;
1351 }
1352
deadbeef1dcb1642017-03-29 21:08:16 -07001353 bool CreatePeerConnectionWrappersWithConfig(
1354 const PeerConnectionInterface::RTCConfiguration& caller_config,
1355 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001356 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001357 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001358 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Niels Möller2a707032020-06-16 16:39:13 +02001359 /*reset_encoder_factory=*/false,
Johannes Kron3e983682020-03-29 22:17:00 +02001360 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001361 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001362 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001363 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Niels Möller2a707032020-06-16 16:39:13 +02001364 /*reset_encoder_factory=*/false,
Johannes Kron3e983682020-03-29 22:17:00 +02001365 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001366 return caller_ && callee_;
1367 }
1368
1369 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1370 const PeerConnectionInterface::RTCConfiguration& caller_config,
1371 webrtc::PeerConnectionDependencies caller_dependencies,
1372 const PeerConnectionInterface::RTCConfiguration& callee_config,
1373 webrtc::PeerConnectionDependencies callee_dependencies) {
Niels Möller2a707032020-06-16 16:39:13 +02001374 caller_ =
1375 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1376 std::move(caller_dependencies), nullptr,
1377 /*reset_encoder_factory=*/false,
1378 /*reset_decoder_factory=*/false);
1379 callee_ =
1380 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1381 std::move(callee_dependencies), nullptr,
1382 /*reset_encoder_factory=*/false,
1383 /*reset_decoder_factory=*/false);
deadbeef1dcb1642017-03-29 21:08:16 -07001384 return caller_ && callee_;
1385 }
1386
1387 bool CreatePeerConnectionWrappersWithOptions(
1388 const PeerConnectionFactory::Options& caller_options,
1389 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001390 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001391 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001392 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Niels Möller2a707032020-06-16 16:39:13 +02001393 /*reset_encoder_factory=*/false,
Johannes Kron3e983682020-03-29 22:17:00 +02001394 /*reset_decoder_factory=*/false);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001395 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001396 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001397 webrtc::PeerConnectionDependencies(nullptr), nullptr,
Niels Möller2a707032020-06-16 16:39:13 +02001398 /*reset_encoder_factory=*/false,
Johannes Kron3e983682020-03-29 22:17:00 +02001399 /*reset_decoder_factory=*/false);
Qingsi Wang7685e862018-06-11 20:15:46 -07001400 return caller_ && callee_;
1401 }
1402
1403 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1404 PeerConnectionInterface::RTCConfiguration default_config;
1405 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001406 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001407 webrtc::PeerConnectionDependencies(nullptr));
1408 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001409 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001410 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001411 return caller_ && callee_;
1412 }
1413
Seth Hampson2f0d7022018-02-20 11:54:42 -08001414 std::unique_ptr<PeerConnectionWrapper>
1415 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001416 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1417 new FakeRTCCertificateGenerator());
1418 cert_generator->use_alternate_key();
1419
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001420 webrtc::PeerConnectionDependencies dependencies(nullptr);
1421 dependencies.cert_generator = std::move(cert_generator);
Niels Möller2a707032020-06-16 16:39:13 +02001422 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
1423 std::move(dependencies), nullptr,
1424 /*reset_encoder_factory=*/false,
1425 /*reset_decoder_factory=*/false);
Johannes Kron3e983682020-03-29 22:17:00 +02001426 }
1427
1428 bool CreateOneDirectionalPeerConnectionWrappers(bool caller_to_callee) {
1429 caller_ = CreatePeerConnectionWrapper(
1430 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Niels Möller2a707032020-06-16 16:39:13 +02001431 nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001432 /*reset_encoder_factory=*/!caller_to_callee,
1433 /*reset_decoder_factory=*/caller_to_callee);
1434 callee_ = CreatePeerConnectionWrapper(
1435 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Niels Möller2a707032020-06-16 16:39:13 +02001436 nullptr,
Johannes Kron3e983682020-03-29 22:17:00 +02001437 /*reset_encoder_factory=*/caller_to_callee,
1438 /*reset_decoder_factory=*/!caller_to_callee);
1439 return caller_ && callee_;
deadbeef1dcb1642017-03-29 21:08:16 -07001440 }
1441
Seth Hampsonaed71642018-06-11 07:41:32 -07001442 cricket::TestTurnServer* CreateTurnServer(
1443 rtc::SocketAddress internal_address,
1444 rtc::SocketAddress external_address,
1445 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1446 const std::string& common_name = "test turn server") {
1447 rtc::Thread* thread = network_thread();
1448 std::unique_ptr<cricket::TestTurnServer> turn_server =
1449 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1450 RTC_FROM_HERE,
1451 [thread, internal_address, external_address, type, common_name] {
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001452 return std::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001453 thread, internal_address, external_address, type,
1454 /*ignore_bad_certs=*/true, common_name);
1455 });
1456 turn_servers_.push_back(std::move(turn_server));
1457 // Interactions with the turn server should be done on the network thread.
1458 return turn_servers_.back().get();
1459 }
1460
1461 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1462 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1463 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1464 RTC_FROM_HERE,
Mirko Bonadei317a1f02019-09-17 17:06:18 +02001465 [] { return std::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001466 turn_customizers_.push_back(std::move(turn_customizer));
1467 // Interactions with the turn customizer should be done on the network
1468 // thread.
1469 return turn_customizers_.back().get();
1470 }
1471
1472 // Checks that the function counters for a TestTurnCustomizer are greater than
1473 // 0.
1474 void ExpectTurnCustomizerCountersIncremented(
1475 cricket::TestTurnCustomizer* turn_customizer) {
1476 unsigned int allow_channel_data_counter =
1477 network_thread()->Invoke<unsigned int>(
1478 RTC_FROM_HERE, [turn_customizer] {
1479 return turn_customizer->allow_channel_data_cnt_;
1480 });
1481 EXPECT_GT(allow_channel_data_counter, 0u);
1482 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1483 RTC_FROM_HERE,
1484 [turn_customizer] { return turn_customizer->modify_cnt_; });
1485 EXPECT_GT(modify_counter, 0u);
1486 }
1487
deadbeef1dcb1642017-03-29 21:08:16 -07001488 // Once called, SDP blobs and ICE candidates will be automatically signaled
1489 // between PeerConnections.
1490 void ConnectFakeSignaling() {
1491 caller_->set_signaling_message_receiver(callee_.get());
1492 callee_->set_signaling_message_receiver(caller_.get());
1493 }
1494
Steve Antonede9ca52017-10-16 13:04:27 -07001495 // Once called, SDP blobs will be automatically signaled between
1496 // PeerConnections. Note that ICE candidates will not be signaled unless they
1497 // are in the exchanged SDP blobs.
1498 void ConnectFakeSignalingForSdpOnly() {
1499 ConnectFakeSignaling();
1500 SetSignalIceCandidates(false);
1501 }
1502
deadbeef1dcb1642017-03-29 21:08:16 -07001503 void SetSignalingDelayMs(int delay_ms) {
1504 caller_->set_signaling_delay_ms(delay_ms);
1505 callee_->set_signaling_delay_ms(delay_ms);
1506 }
1507
Steve Antonede9ca52017-10-16 13:04:27 -07001508 void SetSignalIceCandidates(bool signal) {
1509 caller_->set_signal_ice_candidates(signal);
1510 callee_->set_signal_ice_candidates(signal);
1511 }
1512
deadbeef1dcb1642017-03-29 21:08:16 -07001513 // Messages may get lost on the unreliable DataChannel, so we send multiple
1514 // times to avoid test flakiness.
1515 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1516 const std::string& data,
1517 int retries) {
1518 for (int i = 0; i < retries; ++i) {
1519 dc->Send(DataBuffer(data));
1520 }
1521 }
1522
1523 rtc::Thread* network_thread() { return network_thread_.get(); }
1524
1525 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1526
1527 PeerConnectionWrapper* caller() { return caller_.get(); }
1528
1529 // Set the |caller_| to the |wrapper| passed in and return the
1530 // original |caller_|.
1531 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1532 PeerConnectionWrapper* wrapper) {
1533 PeerConnectionWrapper* old = caller_.release();
1534 caller_.reset(wrapper);
1535 return old;
1536 }
1537
1538 PeerConnectionWrapper* callee() { return callee_.get(); }
1539
1540 // Set the |callee_| to the |wrapper| passed in and return the
1541 // original |callee_|.
1542 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1543 PeerConnectionWrapper* wrapper) {
1544 PeerConnectionWrapper* old = callee_.release();
1545 callee_.reset(wrapper);
1546 return old;
1547 }
1548
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001549 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1550 network_thread()->Invoke<void>(
1551 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1552 caller()->port_allocator(), caller_flags));
1553 network_thread()->Invoke<void>(
1554 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1555 callee()->port_allocator(), callee_flags));
1556 }
1557
Steve Antonede9ca52017-10-16 13:04:27 -07001558 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1559
Seth Hampson2f0d7022018-02-20 11:54:42 -08001560 // Expects the provided number of new frames to be received within
1561 // kMaxWaitForFramesMs. The new expected frames are specified in
1562 // |media_expectations|. Returns false if any of the expectations were
1563 // not met.
1564 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
Harald Alvestrand6060df52020-08-11 09:54:02 +02001565 // Make sure there are no bogus tracks confusing the issue.
1566 caller()->RemoveUnusedVideoRenderers();
1567 callee()->RemoveUnusedVideoRenderers();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001568 // First initialize the expected frame counts based upon the current
1569 // frame count.
1570 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1571 if (media_expectations.caller_audio_expectation_ ==
1572 MediaExpectations::kExpectSomeFrames) {
1573 total_caller_audio_frames_expected +=
1574 media_expectations.caller_audio_frames_expected_;
1575 }
1576 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001577 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001578 if (media_expectations.caller_video_expectation_ ==
1579 MediaExpectations::kExpectSomeFrames) {
1580 total_caller_video_frames_expected +=
1581 media_expectations.caller_video_frames_expected_;
1582 }
1583 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1584 if (media_expectations.callee_audio_expectation_ ==
1585 MediaExpectations::kExpectSomeFrames) {
1586 total_callee_audio_frames_expected +=
1587 media_expectations.callee_audio_frames_expected_;
1588 }
1589 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001590 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001591 if (media_expectations.callee_video_expectation_ ==
1592 MediaExpectations::kExpectSomeFrames) {
1593 total_callee_video_frames_expected +=
1594 media_expectations.callee_video_frames_expected_;
1595 }
deadbeef1dcb1642017-03-29 21:08:16 -07001596
Seth Hampson2f0d7022018-02-20 11:54:42 -08001597 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001598 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001599 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001600 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001601 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001602 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001603 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001604 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001605 total_callee_video_frames_expected,
1606 kMaxWaitForFramesMs);
1607 bool expectations_correct =
1608 caller()->audio_frames_received() >=
1609 total_caller_audio_frames_expected &&
1610 caller()->min_video_frames_received_per_track() >=
1611 total_caller_video_frames_expected &&
1612 callee()->audio_frames_received() >=
1613 total_callee_audio_frames_expected &&
1614 callee()->min_video_frames_received_per_track() >=
1615 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001616
Seth Hampson2f0d7022018-02-20 11:54:42 -08001617 // After the combined wait, print out a more detailed message upon
1618 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001619 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001620 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001621 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001622 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001623 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001624 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001625 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001626 total_callee_video_frames_expected);
1627
1628 // We want to make sure nothing unexpected was received.
1629 if (media_expectations.caller_audio_expectation_ ==
1630 MediaExpectations::kExpectNoFrames) {
1631 EXPECT_EQ(caller()->audio_frames_received(),
1632 total_caller_audio_frames_expected);
1633 if (caller()->audio_frames_received() !=
1634 total_caller_audio_frames_expected) {
1635 expectations_correct = false;
1636 }
1637 }
1638 if (media_expectations.caller_video_expectation_ ==
1639 MediaExpectations::kExpectNoFrames) {
1640 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1641 total_caller_video_frames_expected);
1642 if (caller()->min_video_frames_received_per_track() !=
1643 total_caller_video_frames_expected) {
1644 expectations_correct = false;
1645 }
1646 }
1647 if (media_expectations.callee_audio_expectation_ ==
1648 MediaExpectations::kExpectNoFrames) {
1649 EXPECT_EQ(callee()->audio_frames_received(),
1650 total_callee_audio_frames_expected);
1651 if (callee()->audio_frames_received() !=
1652 total_callee_audio_frames_expected) {
1653 expectations_correct = false;
1654 }
1655 }
1656 if (media_expectations.callee_video_expectation_ ==
1657 MediaExpectations::kExpectNoFrames) {
1658 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1659 total_callee_video_frames_expected);
1660 if (callee()->min_video_frames_received_per_track() !=
1661 total_callee_video_frames_expected) {
1662 expectations_correct = false;
1663 }
1664 }
1665 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001666 }
1667
Steve Antond91969e2019-05-30 12:27:03 -07001668 void ClosePeerConnections() {
1669 caller()->pc()->Close();
1670 callee()->pc()->Close();
1671 }
1672
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001673 void TestNegotiatedCipherSuite(
1674 const PeerConnectionFactory::Options& caller_options,
1675 const PeerConnectionFactory::Options& callee_options,
1676 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001677 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1678 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001679 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001680 caller()->AddAudioVideoTracks();
1681 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001682 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001683 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001684 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001685 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001686 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01001687 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
1688 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1689 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001690 }
1691
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001692 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1693 bool remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001694 bool aes_ctr_enabled,
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001695 int expected_cipher_suite) {
1696 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001697 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1698 local_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001699 caller_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1700 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001701 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001702 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1703 remote_gcm_enabled;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02001704 callee_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher =
1705 aes_ctr_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001706 TestNegotiatedCipherSuite(caller_options, callee_options,
1707 expected_cipher_suite);
1708 }
1709
Seth Hampson2f0d7022018-02-20 11:54:42 -08001710 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001711 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001712
deadbeef1dcb1642017-03-29 21:08:16 -07001713 private:
1714 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001715 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001716 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001717 // |network_thread_| and |worker_thread_| are used by both
1718 // |caller_| and |callee_| so they must be destroyed
1719 // later.
1720 std::unique_ptr<rtc::Thread> network_thread_;
1721 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001722 // The turn servers and turn customizers should be accessed & deleted on the
1723 // network thread to avoid a race with the socket read/write that occurs
1724 // on the network thread.
1725 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1726 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001727 std::unique_ptr<PeerConnectionWrapper> caller_;
1728 std::unique_ptr<PeerConnectionWrapper> callee_;
1729};
1730
Seth Hampson2f0d7022018-02-20 11:54:42 -08001731class PeerConnectionIntegrationTest
1732 : public PeerConnectionIntegrationBaseTest,
1733 public ::testing::WithParamInterface<SdpSemantics> {
1734 protected:
1735 PeerConnectionIntegrationTest()
1736 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1737};
1738
Yves Gerey100fe632020-01-17 19:15:53 +01001739// Fake clock must be set before threads are started to prevent race on
1740// Set/GetClockForTesting().
1741// To achieve that, multiple inheritance is used as a mixin pattern
1742// where order of construction is finely controlled.
1743// This also ensures peerconnection is closed before switching back to non-fake
1744// clock, avoiding other races and DCHECK failures such as in rtp_sender.cc.
1745class FakeClockForTest : public rtc::ScopedFakeClock {
1746 protected:
1747 FakeClockForTest() {
1748 // Some things use a time of "0" as a special value, so we need to start out
1749 // the fake clock at a nonzero time.
1750 // TODO(deadbeef): Fix this.
Danil Chapovalov0c626af2020-02-10 11:16:00 +01001751 AdvanceTime(webrtc::TimeDelta::Seconds(1));
Yves Gerey100fe632020-01-17 19:15:53 +01001752 }
1753
1754 // Explicit handle.
1755 ScopedFakeClock& FakeClock() { return *this; }
1756};
1757
1758// Ensure FakeClockForTest is constructed first (see class for rationale).
1759class PeerConnectionIntegrationTestWithFakeClock
1760 : public FakeClockForTest,
1761 public PeerConnectionIntegrationTest {};
1762
Seth Hampson2f0d7022018-02-20 11:54:42 -08001763class PeerConnectionIntegrationTestPlanB
1764 : public PeerConnectionIntegrationBaseTest {
1765 protected:
1766 PeerConnectionIntegrationTestPlanB()
1767 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1768};
1769
1770class PeerConnectionIntegrationTestUnifiedPlan
1771 : public PeerConnectionIntegrationBaseTest {
1772 protected:
1773 PeerConnectionIntegrationTestUnifiedPlan()
1774 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1775};
1776
deadbeef1dcb1642017-03-29 21:08:16 -07001777// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1778// includes testing that the callback is invoked if an observer is connected
1779// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001780TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001781 RtpReceiverObserverOnFirstPacketReceived) {
1782 ASSERT_TRUE(CreatePeerConnectionWrappers());
1783 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001784 caller()->AddAudioVideoTracks();
1785 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001786 // Start offer/answer exchange and wait for it to complete.
1787 caller()->CreateAndSetAndSignalOffer();
1788 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1789 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001790 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1791 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001792 // Wait for all "first packet received" callbacks to be fired.
1793 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001794 absl::c_all_of(caller()->rtp_receiver_observers(),
1795 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1796 return o->first_packet_received();
1797 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001798 kMaxWaitForFramesMs);
1799 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001800 absl::c_all_of(callee()->rtp_receiver_observers(),
1801 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1802 return o->first_packet_received();
1803 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001804 kMaxWaitForFramesMs);
1805 // If new observers are set after the first packet was already received, the
1806 // callback should still be invoked.
1807 caller()->ResetRtpReceiverObservers();
1808 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001809 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1810 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001811 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001812 absl::c_all_of(caller()->rtp_receiver_observers(),
1813 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1814 return o->first_packet_received();
1815 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001816 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001817 absl::c_all_of(callee()->rtp_receiver_observers(),
1818 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1819 return o->first_packet_received();
1820 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001821}
1822
1823class DummyDtmfObserver : public DtmfSenderObserverInterface {
1824 public:
1825 DummyDtmfObserver() : completed_(false) {}
1826
1827 // Implements DtmfSenderObserverInterface.
1828 void OnToneChange(const std::string& tone) override {
1829 tones_.push_back(tone);
1830 if (tone.empty()) {
1831 completed_ = true;
1832 }
1833 }
1834
1835 const std::vector<std::string>& tones() const { return tones_; }
1836 bool completed() const { return completed_; }
1837
1838 private:
1839 bool completed_;
1840 std::vector<std::string> tones_;
1841};
1842
1843// Assumes |sender| already has an audio track added and the offer/answer
1844// exchange is done.
1845void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1846 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001847 // We should be able to get a DTMF sender from the local sender.
1848 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1849 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1850 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001851 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001852 dtmf_sender->RegisterObserver(&observer);
1853
1854 // Test the DtmfSender object just created.
1855 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1856 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1857
1858 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1859 std::vector<std::string> tones = {"1", "a", ""};
1860 EXPECT_EQ(tones, observer.tones());
1861 dtmf_sender->UnregisterObserver();
1862 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1863}
1864
1865// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1866// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001867TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001868 ASSERT_TRUE(CreatePeerConnectionWrappers());
1869 ConnectFakeSignaling();
1870 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001871 caller()->AddAudioTrack();
1872 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001873 caller()->CreateAndSetAndSignalOffer();
1874 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001875 // DTLS must finish before the DTMF sender can be used reliably.
1876 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001877 TestDtmfFromSenderToReceiver(caller(), callee());
1878 TestDtmfFromSenderToReceiver(callee(), caller());
1879}
1880
1881// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1882// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001883TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001884 ASSERT_TRUE(CreatePeerConnectionWrappers());
1885 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001886
deadbeef1dcb1642017-03-29 21:08:16 -07001887 // Do normal offer/answer and wait for some frames to be received in each
1888 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001889 caller()->AddAudioVideoTracks();
1890 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001891 caller()->CreateAndSetAndSignalOffer();
1892 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001893 MediaExpectations media_expectations;
1894 media_expectations.ExpectBidirectionalAudioAndVideo();
1895 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001896 EXPECT_METRIC_LE(
1897 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1898 webrtc::kEnumCounterKeyProtocolDtls));
1899 EXPECT_METRIC_EQ(
1900 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1901 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001902}
1903
1904// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001905TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001906 PeerConnectionInterface::RTCConfiguration sdes_config;
1907 sdes_config.enable_dtls_srtp.emplace(false);
1908 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1909 ConnectFakeSignaling();
1910
1911 // Do normal offer/answer and wait for some frames to be received in each
1912 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001913 caller()->AddAudioVideoTracks();
1914 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001915 caller()->CreateAndSetAndSignalOffer();
1916 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001917 MediaExpectations media_expectations;
1918 media_expectations.ExpectBidirectionalAudioAndVideo();
1919 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Ying Wangef3998f2019-12-09 13:06:53 +01001920 EXPECT_METRIC_LE(
1921 2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1922 webrtc::kEnumCounterKeyProtocolSdes));
1923 EXPECT_METRIC_EQ(
1924 0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1925 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001926}
1927
Steve Anton9a44b2d2019-07-12 12:58:30 -07001928// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1929// option to offer encrypted versions of all header extensions alongside the
1930// unencrypted versions.
1931TEST_P(PeerConnectionIntegrationTest,
1932 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1933 CryptoOptions crypto_options;
1934 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1935 PeerConnectionInterface::RTCConfiguration config;
1936 config.crypto_options = crypto_options;
1937 // Note: This allows offering >14 RTP header extensions.
1938 config.offer_extmap_allow_mixed = true;
1939 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1940 ConnectFakeSignaling();
1941
1942 // Do normal offer/answer and wait for some frames to be received in each
1943 // direction.
1944 caller()->AddAudioVideoTracks();
1945 callee()->AddAudioVideoTracks();
1946 caller()->CreateAndSetAndSignalOffer();
1947 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1948 MediaExpectations media_expectations;
1949 media_expectations.ExpectBidirectionalAudioAndVideo();
1950 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1951}
1952
deadbeef1dcb1642017-03-29 21:08:16 -07001953// This test sets up a call between two parties with a source resolution of
1954// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001955TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001956 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1957 ASSERT_TRUE(CreatePeerConnectionWrappers());
1958 ConnectFakeSignaling();
1959
Niels Möller5c7efe72018-05-11 10:34:46 +02001960 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1961 webrtc::FakePeriodicVideoSource::Config config;
1962 config.width = 1280;
1963 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001964 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001965 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1966 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001967
1968 // Do normal offer/answer and wait for at least one frame to be received in
1969 // each direction.
1970 caller()->CreateAndSetAndSignalOffer();
1971 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1972 callee()->min_video_frames_received_per_track() > 0,
1973 kMaxWaitForFramesMs);
1974
1975 // Check rendered aspect ratio.
1976 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1977 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1978 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1979 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1980}
1981
1982// This test sets up an one-way call, with media only from caller to
1983// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001984TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001985 ASSERT_TRUE(CreatePeerConnectionWrappers());
1986 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001987 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001988 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001989 MediaExpectations media_expectations;
1990 media_expectations.CalleeExpectsSomeAudioAndVideo();
1991 media_expectations.CallerExpectsNoAudio();
1992 media_expectations.CallerExpectsNoVideo();
1993 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001994}
1995
Johannes Kron3e983682020-03-29 22:17:00 +02001996// Tests that send only works without the caller having a decoder factory and
1997// the callee having an encoder factory.
1998TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSendOnlyVideo) {
1999 ASSERT_TRUE(
2000 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/true));
2001 ConnectFakeSignaling();
2002 // Add one-directional video, from caller to callee.
2003 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2004 caller()->CreateLocalVideoTrack();
2005 caller()->AddTrack(caller_track);
2006 PeerConnectionInterface::RTCOfferAnswerOptions options;
2007 options.offer_to_receive_video = 0;
2008 caller()->SetOfferAnswerOptions(options);
2009 caller()->CreateAndSetAndSignalOffer();
2010 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2011 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
2012
2013 // Expect video to be received in one direction.
2014 MediaExpectations media_expectations;
2015 media_expectations.CallerExpectsNoVideo();
2016 media_expectations.CalleeExpectsSomeVideo();
2017
2018 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2019}
2020
2021// Tests that receive only works without the caller having an encoder factory
2022// and the callee having a decoder factory.
2023TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithReceiveOnlyVideo) {
2024 ASSERT_TRUE(
2025 CreateOneDirectionalPeerConnectionWrappers(/*caller_to_callee=*/false));
2026 ConnectFakeSignaling();
2027 // Add one-directional video, from callee to caller.
2028 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2029 callee()->CreateLocalVideoTrack();
2030 callee()->AddTrack(callee_track);
2031 PeerConnectionInterface::RTCOfferAnswerOptions options;
2032 options.offer_to_receive_video = 1;
2033 caller()->SetOfferAnswerOptions(options);
2034 caller()->CreateAndSetAndSignalOffer();
2035 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2036 ASSERT_EQ(caller()->pc()->GetReceivers().size(), 1u);
2037
2038 // Expect video to be received in one direction.
2039 MediaExpectations media_expectations;
2040 media_expectations.CallerExpectsSomeVideo();
2041 media_expectations.CalleeExpectsNoVideo();
2042
2043 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2044}
2045
2046TEST_P(PeerConnectionIntegrationTest,
2047 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2048 ASSERT_TRUE(CreatePeerConnectionWrappers());
2049 ConnectFakeSignaling();
2050 // Add one-directional video, from caller to callee.
2051 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2052 caller()->CreateLocalVideoTrack();
2053 caller()->AddTrack(caller_track);
2054 caller()->CreateAndSetAndSignalOffer();
2055 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2056
2057 // Add receive video.
2058 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2059 callee()->CreateLocalVideoTrack();
2060 callee()->AddTrack(callee_track);
2061 caller()->CreateAndSetAndSignalOffer();
2062 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2063
2064 // Ensure that video frames are received end-to-end.
2065 MediaExpectations media_expectations;
2066 media_expectations.ExpectBidirectionalVideo();
2067 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2068}
2069
2070TEST_P(PeerConnectionIntegrationTest,
2071 EndToEndCallAddSendVideoToReceiveOnlyCall) {
2072 ASSERT_TRUE(CreatePeerConnectionWrappers());
2073 ConnectFakeSignaling();
2074 // Add one-directional video, from callee to caller.
2075 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2076 callee()->CreateLocalVideoTrack();
2077 callee()->AddTrack(callee_track);
2078 caller()->CreateAndSetAndSignalOffer();
2079 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2080
2081 // Add send video.
2082 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2083 caller()->CreateLocalVideoTrack();
2084 caller()->AddTrack(caller_track);
2085 caller()->CreateAndSetAndSignalOffer();
2086 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2087
2088 // Expect video to be received in one direction.
2089 MediaExpectations media_expectations;
2090 media_expectations.ExpectBidirectionalVideo();
2091 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2092}
2093
2094TEST_P(PeerConnectionIntegrationTest,
2095 EndToEndCallRemoveReceiveVideoFromSendReceiveCall) {
2096 ASSERT_TRUE(CreatePeerConnectionWrappers());
2097 ConnectFakeSignaling();
2098 // Add send video, from caller to callee.
2099 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2100 caller()->CreateLocalVideoTrack();
2101 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2102 caller()->AddTrack(caller_track);
2103 // Add receive video, from callee to caller.
2104 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2105 callee()->CreateLocalVideoTrack();
2106
2107 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2108 callee()->AddTrack(callee_track);
2109 caller()->CreateAndSetAndSignalOffer();
2110 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2111
2112 // Remove receive video (i.e., callee sender track).
2113 callee()->pc()->RemoveTrack(callee_sender);
2114
2115 caller()->CreateAndSetAndSignalOffer();
2116 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2117
2118 // Expect one-directional video.
2119 MediaExpectations media_expectations;
2120 media_expectations.CallerExpectsNoVideo();
2121 media_expectations.CalleeExpectsSomeVideo();
2122
2123 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2124}
2125
2126TEST_P(PeerConnectionIntegrationTest,
2127 EndToEndCallRemoveSendVideoFromSendReceiveCall) {
2128 ASSERT_TRUE(CreatePeerConnectionWrappers());
2129 ConnectFakeSignaling();
2130 // Add send video, from caller to callee.
2131 rtc::scoped_refptr<webrtc::VideoTrackInterface> caller_track =
2132 caller()->CreateLocalVideoTrack();
2133 rtc::scoped_refptr<webrtc::RtpSenderInterface> caller_sender =
2134 caller()->AddTrack(caller_track);
2135 // Add receive video, from callee to caller.
2136 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2137 callee()->CreateLocalVideoTrack();
2138
2139 rtc::scoped_refptr<webrtc::RtpSenderInterface> callee_sender =
2140 callee()->AddTrack(callee_track);
2141 caller()->CreateAndSetAndSignalOffer();
2142 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2143
2144 // Remove send video (i.e., caller sender track).
2145 caller()->pc()->RemoveTrack(caller_sender);
2146
2147 caller()->CreateAndSetAndSignalOffer();
2148 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2149
2150 // Expect one-directional video.
2151 MediaExpectations media_expectations;
2152 media_expectations.CalleeExpectsNoVideo();
2153 media_expectations.CallerExpectsSomeVideo();
2154
2155 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2156}
2157
deadbeef1dcb1642017-03-29 21:08:16 -07002158// This test sets up a audio call initially, with the callee rejecting video
2159// initially. Then later the callee decides to upgrade to audio/video, and
2160// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002161TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07002162 ASSERT_TRUE(CreatePeerConnectionWrappers());
2163 ConnectFakeSignaling();
2164 // Initially, offer an audio/video stream from the caller, but refuse to
2165 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08002166 caller()->AddAudioVideoTracks();
2167 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002168 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2169 PeerConnectionInterface::RTCOfferAnswerOptions options;
2170 options.offer_to_receive_video = 0;
2171 callee()->SetOfferAnswerOptions(options);
2172 } else {
2173 callee()->SetRemoteOfferHandler([this] {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002174 callee()
2175 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2176 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002177 });
2178 }
deadbeef1dcb1642017-03-29 21:08:16 -07002179 // Do offer/answer and make sure audio is still received end-to-end.
2180 caller()->CreateAndSetAndSignalOffer();
2181 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002182 {
2183 MediaExpectations media_expectations;
2184 media_expectations.ExpectBidirectionalAudio();
2185 media_expectations.ExpectNoVideo();
2186 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2187 }
deadbeef1dcb1642017-03-29 21:08:16 -07002188 // Sanity check that the callee's description has a rejected video section.
2189 ASSERT_NE(nullptr, callee()->pc()->local_description());
2190 const ContentInfo* callee_video_content =
2191 GetFirstVideoContent(callee()->pc()->local_description()->description());
2192 ASSERT_NE(nullptr, callee_video_content);
2193 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002194
deadbeef1dcb1642017-03-29 21:08:16 -07002195 // Now negotiate with video and ensure negotiation succeeds, with video
2196 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002197 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002198 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2199 PeerConnectionInterface::RTCOfferAnswerOptions options;
2200 options.offer_to_receive_video = 1;
2201 callee()->SetOfferAnswerOptions(options);
2202 } else {
2203 callee()->SetRemoteOfferHandler(nullptr);
2204 caller()->SetRemoteOfferHandler([this] {
2205 // The caller creates a new transceiver to receive video on when receiving
2206 // the offer, but by default it is send only.
2207 auto transceivers = caller()->pc()->GetTransceivers();
Harald Alvestrand6060df52020-08-11 09:54:02 +02002208 ASSERT_EQ(2U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002209 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
Harald Alvestrand6060df52020-08-11 09:54:02 +02002210 transceivers[1]->receiver()->media_type());
2211 transceivers[1]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2212 transceivers[1]->SetDirectionWithError(
2213 RtpTransceiverDirection::kSendRecv);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002214 });
2215 }
deadbeef1dcb1642017-03-29 21:08:16 -07002216 callee()->CreateAndSetAndSignalOffer();
2217 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002218 {
2219 // Expect additional audio frames to be received after the upgrade.
2220 MediaExpectations media_expectations;
2221 media_expectations.ExpectBidirectionalAudioAndVideo();
2222 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2223 }
deadbeef1dcb1642017-03-29 21:08:16 -07002224}
2225
deadbeef4389b4d2017-09-07 09:07:36 -07002226// Simpler than the above test; just add an audio track to an established
2227// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002228TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002229 ASSERT_TRUE(CreatePeerConnectionWrappers());
2230 ConnectFakeSignaling();
2231 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002232 caller()->AddVideoTrack();
2233 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002234 caller()->CreateAndSetAndSignalOffer();
2235 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2236 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002237 caller()->AddAudioTrack();
2238 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002239 caller()->CreateAndSetAndSignalOffer();
2240 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2241 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002242 MediaExpectations media_expectations;
2243 media_expectations.ExpectBidirectionalAudioAndVideo();
2244 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002245}
2246
deadbeef1dcb1642017-03-29 21:08:16 -07002247// This test sets up a call that's transferred to a new caller with a different
2248// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002249TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002250 ASSERT_TRUE(CreatePeerConnectionWrappers());
2251 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002252 caller()->AddAudioVideoTracks();
2253 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002254 caller()->CreateAndSetAndSignalOffer();
2255 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2256
2257 // Keep the original peer around which will still send packets to the
2258 // receiving client. These SRTP packets will be dropped.
2259 std::unique_ptr<PeerConnectionWrapper> original_peer(
2260 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002261 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002262 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2263 // directly above.
2264 original_peer->pc()->Close();
2265
2266 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002267 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002268 caller()->CreateAndSetAndSignalOffer();
2269 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2270 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002271 MediaExpectations media_expectations;
2272 media_expectations.ExpectBidirectionalAudioAndVideo();
2273 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002274}
2275
2276// This test sets up a call that's transferred to a new callee with a different
2277// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002278TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002279 ASSERT_TRUE(CreatePeerConnectionWrappers());
2280 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002281 caller()->AddAudioVideoTracks();
2282 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002283 caller()->CreateAndSetAndSignalOffer();
2284 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2285
2286 // Keep the original peer around which will still send packets to the
2287 // receiving client. These SRTP packets will be dropped.
2288 std::unique_ptr<PeerConnectionWrapper> original_peer(
2289 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002290 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002291 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2292 // directly above.
2293 original_peer->pc()->Close();
2294
2295 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002296 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002297 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2298 caller()->CreateAndSetAndSignalOffer();
2299 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2300 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002301 MediaExpectations media_expectations;
2302 media_expectations.ExpectBidirectionalAudioAndVideo();
2303 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002304}
2305
2306// This test sets up a non-bundled call and negotiates bundling at the same
2307// time as starting an ICE restart. When bundling is in effect in the restart,
2308// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002309TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002310 ASSERT_TRUE(CreatePeerConnectionWrappers());
2311 ConnectFakeSignaling();
2312
Steve Anton15324772018-01-16 10:26:49 -08002313 caller()->AddAudioVideoTracks();
2314 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002315 // Remove the bundle group from the SDP received by the callee.
2316 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2317 desc->RemoveGroupByName("BUNDLE");
2318 });
2319 caller()->CreateAndSetAndSignalOffer();
2320 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002321 {
2322 MediaExpectations media_expectations;
2323 media_expectations.ExpectBidirectionalAudioAndVideo();
2324 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2325 }
deadbeef1dcb1642017-03-29 21:08:16 -07002326 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2327 callee()->SetReceivedSdpMunger(nullptr);
2328 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2329 caller()->CreateAndSetAndSignalOffer();
2330 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2331
2332 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002333 {
2334 MediaExpectations media_expectations;
2335 media_expectations.ExpectBidirectionalAudioAndVideo();
2336 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2337 }
deadbeef1dcb1642017-03-29 21:08:16 -07002338}
2339
2340// Test CVO (Coordination of Video Orientation). If a video source is rotated
2341// and both peers support the CVO RTP header extension, the actual video frames
2342// don't need to be encoded in different resolutions, since the rotation is
2343// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002344TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002345 ASSERT_TRUE(CreatePeerConnectionWrappers());
2346 ConnectFakeSignaling();
2347 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002348 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002349 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002350 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002351 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2352
2353 // Wait for video frames to be received by both sides.
2354 caller()->CreateAndSetAndSignalOffer();
2355 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2356 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2357 callee()->min_video_frames_received_per_track() > 0,
2358 kMaxWaitForFramesMs);
2359
2360 // Ensure that the aspect ratio is unmodified.
2361 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2362 // not just assumed.
2363 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2364 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2365 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2366 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2367 // Ensure that the CVO bits were surfaced to the renderer.
2368 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2369 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2370}
2371
2372// Test that when the CVO extension isn't supported, video is rotated the
2373// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002374TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002375 ASSERT_TRUE(CreatePeerConnectionWrappers());
2376 ConnectFakeSignaling();
2377 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002378 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002379 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002380 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002381 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2382
2383 // Remove the CVO extension from the offered SDP.
2384 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2385 cricket::VideoContentDescription* video =
2386 GetFirstVideoContentDescription(desc);
2387 video->ClearRtpHeaderExtensions();
2388 });
2389 // Wait for video frames to be received by both sides.
2390 caller()->CreateAndSetAndSignalOffer();
2391 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2392 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2393 callee()->min_video_frames_received_per_track() > 0,
2394 kMaxWaitForFramesMs);
2395
2396 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2397 // rotation.
2398 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2399 // not just assumed.
2400 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2401 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2402 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2403 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2404 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2405 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2406 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2407}
2408
deadbeef1dcb1642017-03-29 21:08:16 -07002409// Test that if the answerer rejects the audio m= section, no audio is sent or
2410// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002411TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002412 ASSERT_TRUE(CreatePeerConnectionWrappers());
2413 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002414 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002415 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2416 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2417 // it will reject the audio m= section completely.
2418 PeerConnectionInterface::RTCOfferAnswerOptions options;
2419 options.offer_to_receive_audio = 0;
2420 callee()->SetOfferAnswerOptions(options);
2421 } else {
2422 // Stopping the audio RtpTransceiver will cause the media section to be
2423 // rejected in the answer.
2424 callee()->SetRemoteOfferHandler([this] {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002425 callee()
2426 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2427 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002428 });
2429 }
Steve Anton15324772018-01-16 10:26:49 -08002430 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002431 // Do offer/answer and wait for successful end-to-end video frames.
2432 caller()->CreateAndSetAndSignalOffer();
2433 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002434 MediaExpectations media_expectations;
2435 media_expectations.ExpectBidirectionalVideo();
2436 media_expectations.ExpectNoAudio();
2437 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2438
deadbeef1dcb1642017-03-29 21:08:16 -07002439 // Sanity check that the callee's description has a rejected audio section.
2440 ASSERT_NE(nullptr, callee()->pc()->local_description());
2441 const ContentInfo* callee_audio_content =
2442 GetFirstAudioContent(callee()->pc()->local_description()->description());
2443 ASSERT_NE(nullptr, callee_audio_content);
2444 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002445 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002446 // The caller's transceiver should have stopped after receiving the answer,
2447 // and thus no longer listed in transceivers.
2448 EXPECT_EQ(nullptr,
2449 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO));
Seth Hampson2f0d7022018-02-20 11:54:42 -08002450 }
deadbeef1dcb1642017-03-29 21:08:16 -07002451}
2452
2453// Test that if the answerer rejects the video m= section, no video is sent or
2454// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002455TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002456 ASSERT_TRUE(CreatePeerConnectionWrappers());
2457 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002458 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002459 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2460 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2461 // it will reject the video m= section completely.
2462 PeerConnectionInterface::RTCOfferAnswerOptions options;
2463 options.offer_to_receive_video = 0;
2464 callee()->SetOfferAnswerOptions(options);
2465 } else {
2466 // Stopping the video RtpTransceiver will cause the media section to be
2467 // rejected in the answer.
2468 callee()->SetRemoteOfferHandler([this] {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002469 callee()
2470 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2471 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002472 });
2473 }
Steve Anton15324772018-01-16 10:26:49 -08002474 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002475 // Do offer/answer and wait for successful end-to-end audio frames.
2476 caller()->CreateAndSetAndSignalOffer();
2477 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002478 MediaExpectations media_expectations;
2479 media_expectations.ExpectBidirectionalAudio();
2480 media_expectations.ExpectNoVideo();
2481 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2482
deadbeef1dcb1642017-03-29 21:08:16 -07002483 // Sanity check that the callee's description has a rejected video section.
2484 ASSERT_NE(nullptr, callee()->pc()->local_description());
2485 const ContentInfo* callee_video_content =
2486 GetFirstVideoContent(callee()->pc()->local_description()->description());
2487 ASSERT_NE(nullptr, callee_video_content);
2488 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002489 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002490 // The caller's transceiver should have stopped after receiving the answer,
2491 // and thus is no longer present.
2492 EXPECT_EQ(nullptr,
2493 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO));
Seth Hampson2f0d7022018-02-20 11:54:42 -08002494 }
deadbeef1dcb1642017-03-29 21:08:16 -07002495}
2496
2497// Test that if the answerer rejects both audio and video m= sections, nothing
2498// bad happens.
2499// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2500// test anything but the fact that negotiation succeeds, which doesn't mean
2501// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002502TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002503 ASSERT_TRUE(CreatePeerConnectionWrappers());
2504 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002505 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002506 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2507 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2508 // will reject both audio and video m= sections.
2509 PeerConnectionInterface::RTCOfferAnswerOptions options;
2510 options.offer_to_receive_audio = 0;
2511 options.offer_to_receive_video = 0;
2512 callee()->SetOfferAnswerOptions(options);
2513 } else {
2514 callee()->SetRemoteOfferHandler([this] {
2515 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002516 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002517 transceiver->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002518 }
2519 });
2520 }
deadbeef1dcb1642017-03-29 21:08:16 -07002521 // Do offer/answer and wait for stable signaling state.
2522 caller()->CreateAndSetAndSignalOffer();
2523 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002524
deadbeef1dcb1642017-03-29 21:08:16 -07002525 // Sanity check that the callee's description has rejected m= sections.
2526 ASSERT_NE(nullptr, callee()->pc()->local_description());
2527 const ContentInfo* callee_audio_content =
2528 GetFirstAudioContent(callee()->pc()->local_description()->description());
2529 ASSERT_NE(nullptr, callee_audio_content);
2530 EXPECT_TRUE(callee_audio_content->rejected);
2531 const ContentInfo* callee_video_content =
2532 GetFirstVideoContent(callee()->pc()->local_description()->description());
2533 ASSERT_NE(nullptr, callee_video_content);
2534 EXPECT_TRUE(callee_video_content->rejected);
2535}
2536
2537// This test sets up an audio and video call between two parties. After the
2538// call runs for a while, the caller sends an updated offer with video being
2539// rejected. Once the re-negotiation is done, the video flow should stop and
2540// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002541TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002542 ASSERT_TRUE(CreatePeerConnectionWrappers());
2543 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002544 caller()->AddAudioVideoTracks();
2545 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002546 caller()->CreateAndSetAndSignalOffer();
2547 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002548 {
2549 MediaExpectations media_expectations;
2550 media_expectations.ExpectBidirectionalAudioAndVideo();
2551 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2552 }
deadbeef1dcb1642017-03-29 21:08:16 -07002553 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002554 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2555 caller()->SetGeneratedSdpMunger(
2556 [](cricket::SessionDescription* description) {
2557 for (cricket::ContentInfo& content : description->contents()) {
2558 if (cricket::IsVideoContent(&content)) {
2559 content.rejected = true;
2560 }
2561 }
2562 });
2563 } else {
Harald Alvestrand6060df52020-08-11 09:54:02 +02002564 caller()
2565 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2566 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002567 }
deadbeef1dcb1642017-03-29 21:08:16 -07002568 caller()->CreateAndSetAndSignalOffer();
2569 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2570
2571 // Sanity check that the caller's description has a rejected video section.
2572 ASSERT_NE(nullptr, caller()->pc()->local_description());
2573 const ContentInfo* caller_video_content =
2574 GetFirstVideoContent(caller()->pc()->local_description()->description());
2575 ASSERT_NE(nullptr, caller_video_content);
2576 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002577 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002578 {
2579 MediaExpectations media_expectations;
2580 media_expectations.ExpectBidirectionalAudio();
2581 media_expectations.ExpectNoVideo();
2582 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2583 }
deadbeef1dcb1642017-03-29 21:08:16 -07002584}
2585
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002586// Do one offer/answer with audio, another that disables it (rejecting the m=
2587// section), and another that re-enables it. Regression test for:
2588// bugs.webrtc.org/6023
2589TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2590 ASSERT_TRUE(CreatePeerConnectionWrappers());
2591 ConnectFakeSignaling();
2592
2593 // Add audio track, do normal offer/answer.
2594 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2595 caller()->CreateLocalAudioTrack();
2596 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2597 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2598 caller()->CreateAndSetAndSignalOffer();
2599 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2600
2601 // Remove audio track, and set offer_to_receive_audio to false to cause the
2602 // m= section to be completely disabled, not just "recvonly".
2603 caller()->pc()->RemoveTrack(sender);
2604 PeerConnectionInterface::RTCOfferAnswerOptions options;
2605 options.offer_to_receive_audio = 0;
2606 caller()->SetOfferAnswerOptions(options);
2607 caller()->CreateAndSetAndSignalOffer();
2608 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2609
2610 // Add the audio track again, expecting negotiation to succeed and frames to
2611 // flow.
2612 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2613 options.offer_to_receive_audio = 1;
2614 caller()->SetOfferAnswerOptions(options);
2615 caller()->CreateAndSetAndSignalOffer();
2616 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2617
2618 MediaExpectations media_expectations;
2619 media_expectations.CalleeExpectsSomeAudio();
2620 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2621}
2622
deadbeef1dcb1642017-03-29 21:08:16 -07002623// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2624// is needed to support legacy endpoints.
2625// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2626// add a test for an end-to-end test without MID signaling either (basically,
2627// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002628TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002629 ASSERT_TRUE(CreatePeerConnectionWrappers());
2630 ConnectFakeSignaling();
2631 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002632 caller()->AddAudioVideoTracks();
2633 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002634 // Remove SSRCs and MSIDs from the received offer SDP.
2635 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002636 caller()->CreateAndSetAndSignalOffer();
2637 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002638 MediaExpectations media_expectations;
2639 media_expectations.ExpectBidirectionalAudioAndVideo();
2640 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002641}
2642
Seth Hampson5897a6e2018-04-03 11:16:33 -07002643// Basic end-to-end test, without SSRC signaling. This means that the track
2644// was created properly and frames are delivered when the MSIDs are communicated
2645// with a=msid lines and no a=ssrc lines.
2646TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2647 EndToEndCallWithoutSsrcSignaling) {
2648 const char kStreamId[] = "streamId";
2649 ASSERT_TRUE(CreatePeerConnectionWrappers());
2650 ConnectFakeSignaling();
2651 // Add just audio tracks.
2652 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2653 callee()->AddAudioTrack();
2654
2655 // Remove SSRCs from the received offer SDP.
2656 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2657 caller()->CreateAndSetAndSignalOffer();
2658 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2659 MediaExpectations media_expectations;
2660 media_expectations.ExpectBidirectionalAudio();
2661 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2662}
2663
Johannes Kron3e983682020-03-29 22:17:00 +02002664TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2665 EndToEndCallAddReceiveVideoToSendOnlyCall) {
2666 ASSERT_TRUE(CreatePeerConnectionWrappers());
2667 ConnectFakeSignaling();
2668 // Add one-directional video, from caller to callee.
2669 rtc::scoped_refptr<webrtc::VideoTrackInterface> track =
2670 caller()->CreateLocalVideoTrack();
2671
2672 RtpTransceiverInit video_transceiver_init;
2673 video_transceiver_init.stream_ids = {"video1"};
2674 video_transceiver_init.direction = RtpTransceiverDirection::kSendOnly;
2675 auto video_sender =
2676 caller()->pc()->AddTransceiver(track, video_transceiver_init).MoveValue();
2677 caller()->CreateAndSetAndSignalOffer();
2678 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2679
2680 // Add receive direction.
Harald Alvestrand6060df52020-08-11 09:54:02 +02002681 video_sender->SetDirectionWithError(RtpTransceiverDirection::kSendRecv);
Johannes Kron3e983682020-03-29 22:17:00 +02002682
2683 rtc::scoped_refptr<webrtc::VideoTrackInterface> callee_track =
2684 callee()->CreateLocalVideoTrack();
2685
2686 callee()->AddTrack(callee_track);
2687 caller()->CreateAndSetAndSignalOffer();
2688 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2689 // Ensure that video frames are received end-to-end.
2690 MediaExpectations media_expectations;
2691 media_expectations.ExpectBidirectionalVideo();
2692 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2693}
2694
Steve Antondf527fd2018-04-27 15:52:03 -07002695// Tests that video flows between multiple video tracks when SSRCs are not
2696// signaled. This exercises the MID RTP header extension which is needed to
2697// demux the incoming video tracks.
2698TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2699 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2700 ASSERT_TRUE(CreatePeerConnectionWrappers());
2701 ConnectFakeSignaling();
2702 caller()->AddVideoTrack();
2703 caller()->AddVideoTrack();
2704 callee()->AddVideoTrack();
2705 callee()->AddVideoTrack();
2706
2707 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2708 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2709 caller()->CreateAndSetAndSignalOffer();
2710 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2711 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2712 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2713
2714 // Expect video to be received in both directions on both tracks.
2715 MediaExpectations media_expectations;
2716 media_expectations.ExpectBidirectionalVideo();
2717 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2718}
2719
Taylor Brandstetterd3ef4992020-10-15 18:22:57 -07002720// Used for the test below.
2721void RemoveBundleGroupSsrcsAndMidExtension(cricket::SessionDescription* desc) {
2722 RemoveSsrcsAndKeepMsids(desc);
2723 desc->RemoveGroupByName("BUNDLE");
2724 for (ContentInfo& content : desc->contents()) {
2725 cricket::MediaContentDescription* media = content.media_description();
2726 cricket::RtpHeaderExtensions extensions = media->rtp_header_extensions();
2727 extensions.erase(std::remove_if(extensions.begin(), extensions.end(),
2728 [](const RtpExtension& extension) {
2729 return extension.uri ==
2730 RtpExtension::kMidUri;
2731 }),
2732 extensions.end());
2733 media->set_rtp_header_extensions(extensions);
2734 }
2735}
2736
2737// Tests that video flows between multiple video tracks when BUNDLE is not used,
2738// SSRCs are not signaled and the MID RTP header extension is not used. This
2739// relies on demuxing by payload type, which normally doesn't work if you have
2740// multiple media sections using the same payload type, but which should work as
2741// long as the media sections aren't bundled.
2742// Regression test for: http://crbug.com/webrtc/12023
2743TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2744 EndToEndCallWithTwoVideoTracksNoBundleNoSignaledSsrcAndNoMid) {
2745 ASSERT_TRUE(CreatePeerConnectionWrappers());
2746 ConnectFakeSignaling();
2747 caller()->AddVideoTrack();
2748 caller()->AddVideoTrack();
2749 callee()->AddVideoTrack();
2750 callee()->AddVideoTrack();
2751 caller()->SetReceivedSdpMunger(&RemoveBundleGroupSsrcsAndMidExtension);
2752 callee()->SetReceivedSdpMunger(&RemoveBundleGroupSsrcsAndMidExtension);
2753 caller()->CreateAndSetAndSignalOffer();
2754 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2755 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2756 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2757 // Make sure we are not bundled.
2758 ASSERT_NE(caller()->pc()->GetSenders()[0]->dtls_transport(),
2759 caller()->pc()->GetSenders()[1]->dtls_transport());
2760
2761 // Expect video to be received in both directions on both tracks.
2762 MediaExpectations media_expectations;
2763 media_expectations.ExpectBidirectionalVideo();
2764 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2765}
2766
2767// Used for the test below.
2768void ModifyPayloadTypesAndRemoveMidExtension(
2769 cricket::SessionDescription* desc) {
2770 int pt = 96;
2771 for (ContentInfo& content : desc->contents()) {
2772 cricket::MediaContentDescription* media = content.media_description();
2773 cricket::RtpHeaderExtensions extensions = media->rtp_header_extensions();
2774 extensions.erase(std::remove_if(extensions.begin(), extensions.end(),
2775 [](const RtpExtension& extension) {
2776 return extension.uri ==
2777 RtpExtension::kMidUri;
2778 }),
2779 extensions.end());
2780 media->set_rtp_header_extensions(extensions);
2781 cricket::VideoContentDescription* video = media->as_video();
2782 ASSERT_TRUE(video != nullptr);
2783 std::vector<cricket::VideoCodec> codecs = {{pt++, "VP8"}};
2784 video->set_codecs(codecs);
2785 }
2786}
2787
2788// Tests that two video tracks can be demultiplexed by payload type alone, by
2789// using different payload types for the same codec in different m= sections.
2790// This practice is discouraged but historically has been supported.
2791// Regression test for: http://crbug.com/webrtc/12029
2792TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2793 EndToEndCallWithTwoVideoTracksDemultiplexedByPayloadType) {
2794 ASSERT_TRUE(CreatePeerConnectionWrappers());
2795 ConnectFakeSignaling();
2796 caller()->AddVideoTrack();
2797 caller()->AddVideoTrack();
2798 callee()->AddVideoTrack();
2799 callee()->AddVideoTrack();
2800 caller()->SetGeneratedSdpMunger(&ModifyPayloadTypesAndRemoveMidExtension);
2801 callee()->SetGeneratedSdpMunger(&ModifyPayloadTypesAndRemoveMidExtension);
2802 // We can't remove SSRCs from the generated SDP because then no send streams
2803 // would be created.
2804 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2805 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2806 caller()->CreateAndSetAndSignalOffer();
2807 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2808 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2809 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2810 // Make sure we are bundled.
2811 ASSERT_EQ(caller()->pc()->GetSenders()[0]->dtls_transport(),
2812 caller()->pc()->GetSenders()[1]->dtls_transport());
2813
2814 // Expect video to be received in both directions on both tracks.
2815 MediaExpectations media_expectations;
2816 media_expectations.ExpectBidirectionalVideo();
2817 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2818}
2819
Henrik Boström5b147782018-12-04 11:25:05 +01002820TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2821 ASSERT_TRUE(CreatePeerConnectionWrappers());
2822 ConnectFakeSignaling();
2823 caller()->AddAudioTrack();
2824 caller()->AddVideoTrack();
2825 caller()->CreateAndSetAndSignalOffer();
2826 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2827 auto callee_receivers = callee()->pc()->GetReceivers();
2828 ASSERT_EQ(2u, callee_receivers.size());
2829 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2830 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2831}
2832
2833TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2834 ASSERT_TRUE(CreatePeerConnectionWrappers());
2835 ConnectFakeSignaling();
2836 caller()->AddAudioTrack();
2837 caller()->AddVideoTrack();
2838 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2839 caller()->CreateAndSetAndSignalOffer();
2840 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2841 auto callee_receivers = callee()->pc()->GetReceivers();
2842 ASSERT_EQ(2u, callee_receivers.size());
2843 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2844 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2845 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2846 callee_receivers[1]->stream_ids()[0]);
2847 EXPECT_EQ(callee_receivers[0]->streams()[0],
2848 callee_receivers[1]->streams()[0]);
2849}
2850
deadbeef1dcb1642017-03-29 21:08:16 -07002851// Test that if two video tracks are sent (from caller to callee, in this test),
2852// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002853TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002854 ASSERT_TRUE(CreatePeerConnectionWrappers());
2855 ConnectFakeSignaling();
2856 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002857 caller()->AddAudioVideoTracks();
2858 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002859 caller()->CreateAndSetAndSignalOffer();
2860 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002861 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002862
2863 MediaExpectations media_expectations;
2864 media_expectations.CalleeExpectsSomeAudioAndVideo();
2865 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002866}
2867
2868static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2869 bool first = true;
2870 for (cricket::ContentInfo& content : desc->contents()) {
2871 if (first) {
2872 first = false;
2873 continue;
2874 }
2875 content.bundle_only = true;
2876 }
2877 first = true;
2878 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2879 if (first) {
2880 first = false;
2881 continue;
2882 }
2883 transport.description.ice_ufrag.clear();
2884 transport.description.ice_pwd.clear();
2885 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2886 transport.description.identity_fingerprint.reset(nullptr);
2887 }
2888}
2889
2890// Test that if applying a true "max bundle" offer, which uses ports of 0,
2891// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2892// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2893// successfully and media flows.
2894// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2895// TODO(deadbeef): Won't need this test once we start generating actual
2896// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002897TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002898 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2899 ASSERT_TRUE(CreatePeerConnectionWrappers());
2900 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002901 caller()->AddAudioVideoTracks();
2902 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002903 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2904 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2905 // but the first m= section.
2906 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2907 caller()->CreateAndSetAndSignalOffer();
2908 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002909 MediaExpectations media_expectations;
2910 media_expectations.ExpectBidirectionalAudioAndVideo();
2911 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002912}
2913
2914// Test that we can receive the audio output level from a remote audio track.
2915// TODO(deadbeef): Use a fake audio source and verify that the output level is
2916// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002917TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002918 ASSERT_TRUE(CreatePeerConnectionWrappers());
2919 ConnectFakeSignaling();
2920 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002921 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002922 caller()->CreateAndSetAndSignalOffer();
2923 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2924
2925 // Get the audio output level stats. Note that the level is not available
2926 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002927 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002928 kMaxWaitForFramesMs);
2929}
2930
2931// Test that an audio input level is reported.
2932// TODO(deadbeef): Use a fake audio source and verify that the input level is
2933// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002934TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002935 ASSERT_TRUE(CreatePeerConnectionWrappers());
2936 ConnectFakeSignaling();
2937 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002938 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002939 caller()->CreateAndSetAndSignalOffer();
2940 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2941
2942 // Get the audio input level stats. The level should be available very
2943 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002944 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002945 kMaxWaitForStatsMs);
2946}
2947
2948// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002949TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002950 ASSERT_TRUE(CreatePeerConnectionWrappers());
2951 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002952 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002953 // Do offer/answer, wait for the callee to receive some frames.
2954 caller()->CreateAndSetAndSignalOffer();
2955 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002956
2957 MediaExpectations media_expectations;
2958 media_expectations.CalleeExpectsSomeAudioAndVideo();
2959 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002960
2961 // Get a handle to the remote tracks created, so they can be used as GetStats
2962 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002963 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002964 // We received frames, so we definitely should have nonzero "received bytes"
2965 // stats at this point.
2966 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2967 0);
2968 }
deadbeef1dcb1642017-03-29 21:08:16 -07002969}
2970
2971// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002972TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002973 ASSERT_TRUE(CreatePeerConnectionWrappers());
2974 ConnectFakeSignaling();
2975 auto audio_track = caller()->CreateLocalAudioTrack();
2976 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002977 caller()->AddTrack(audio_track);
2978 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002979 // Do offer/answer, wait for the callee to receive some frames.
2980 caller()->CreateAndSetAndSignalOffer();
2981 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002982 MediaExpectations media_expectations;
2983 media_expectations.CalleeExpectsSomeAudioAndVideo();
2984 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002985
2986 // The callee received frames, so we definitely should have nonzero "sent
2987 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002988 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2989 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2990}
2991
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002992// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002993TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002994 ASSERT_TRUE(CreatePeerConnectionWrappers());
2995 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002996 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002997
Steve Anton15324772018-01-16 10:26:49 -08002998 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002999
3000 // Do offer/answer, wait for the callee to receive some frames.
3001 caller()->CreateAndSetAndSignalOffer();
3002 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3003
3004 // Get the remote audio track created on the receiver, so they can be used as
3005 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08003006 auto receivers = callee()->pc()->GetReceivers();
3007 ASSERT_EQ(1u, receivers.size());
3008 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02003009
3010 // Get the audio output level stats. Note that the level is not available
3011 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07003012 EXPECT_TRUE_WAIT(
3013 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
3014 0,
3015 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02003016}
3017
Steve Antona41959e2018-11-28 11:15:33 -08003018// Test that the track ID is associated with all local and remote SSRC stats
3019// using the old GetStats() and more than 1 audio and more than 1 video track.
3020// This is a regression test for crbug.com/906988
3021TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
3022 OldGetStatsAssociatesTrackIdForManyMediaSections) {
3023 ASSERT_TRUE(CreatePeerConnectionWrappers());
3024 ConnectFakeSignaling();
3025 auto audio_sender_1 = caller()->AddAudioTrack();
3026 auto video_sender_1 = caller()->AddVideoTrack();
3027 auto audio_sender_2 = caller()->AddAudioTrack();
3028 auto video_sender_2 = caller()->AddVideoTrack();
3029 caller()->CreateAndSetAndSignalOffer();
3030 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3031
3032 MediaExpectations media_expectations;
3033 media_expectations.CalleeExpectsSomeAudioAndVideo();
3034 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3035
3036 std::vector<std::string> track_ids = {
3037 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3038 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3039
3040 auto caller_stats = caller()->OldGetStats();
3041 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3042 auto callee_stats = callee()->OldGetStats();
3043 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
3044}
3045
Steve Antonffa6ce42018-11-30 09:26:08 -08003046// Test that the new GetStats() returns stats for all outgoing/incoming streams
3047// with the correct track IDs if there are more than one audio and more than one
3048// video senders/receivers.
3049TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
3050 ASSERT_TRUE(CreatePeerConnectionWrappers());
3051 ConnectFakeSignaling();
3052 auto audio_sender_1 = caller()->AddAudioTrack();
3053 auto video_sender_1 = caller()->AddVideoTrack();
3054 auto audio_sender_2 = caller()->AddAudioTrack();
3055 auto video_sender_2 = caller()->AddVideoTrack();
3056 caller()->CreateAndSetAndSignalOffer();
3057 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3058
3059 MediaExpectations media_expectations;
3060 media_expectations.CalleeExpectsSomeAudioAndVideo();
3061 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
3062
3063 std::vector<std::string> track_ids = {
3064 audio_sender_1->track()->id(), video_sender_1->track()->id(),
3065 audio_sender_2->track()->id(), video_sender_2->track()->id()};
3066
3067 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
3068 caller()->NewGetStats();
3069 ASSERT_TRUE(caller_report);
3070 auto outbound_stream_stats =
3071 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
Henrik Boströma0ff50c2020-05-05 15:54:46 +02003072 ASSERT_EQ(outbound_stream_stats.size(), 4u);
Steve Antonffa6ce42018-11-30 09:26:08 -08003073 std::vector<std::string> outbound_track_ids;
3074 for (const auto& stat : outbound_stream_stats) {
3075 ASSERT_TRUE(stat->bytes_sent.is_defined());
3076 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02003077 if (*stat->kind == "video") {
3078 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
3079 EXPECT_GT(*stat->key_frames_encoded, 0u);
3080 ASSERT_TRUE(stat->frames_encoded.is_defined());
3081 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
3082 }
Steve Antonffa6ce42018-11-30 09:26:08 -08003083 ASSERT_TRUE(stat->track_id.is_defined());
3084 const auto* track_stat =
3085 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3086 ASSERT_TRUE(track_stat);
3087 outbound_track_ids.push_back(*track_stat->track_identifier);
3088 }
3089 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
3090
3091 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
3092 callee()->NewGetStats();
3093 ASSERT_TRUE(callee_report);
3094 auto inbound_stream_stats =
3095 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3096 ASSERT_EQ(4u, inbound_stream_stats.size());
3097 std::vector<std::string> inbound_track_ids;
3098 for (const auto& stat : inbound_stream_stats) {
3099 ASSERT_TRUE(stat->bytes_received.is_defined());
3100 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02003101 if (*stat->kind == "video") {
3102 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
3103 EXPECT_GT(*stat->key_frames_decoded, 0u);
3104 ASSERT_TRUE(stat->frames_decoded.is_defined());
3105 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
3106 }
Steve Antonffa6ce42018-11-30 09:26:08 -08003107 ASSERT_TRUE(stat->track_id.is_defined());
3108 const auto* track_stat =
3109 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
3110 ASSERT_TRUE(track_stat);
3111 inbound_track_ids.push_back(*track_stat->track_identifier);
3112 }
3113 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
3114}
3115
3116// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07003117// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
3118// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003119TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07003120 GetStatsForUnsignaledStreamWithNewStatsApi) {
3121 ASSERT_TRUE(CreatePeerConnectionWrappers());
3122 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003123 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07003124 // Remove SSRCs and MSIDs from the received offer SDP.
3125 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3126 caller()->CreateAndSetAndSignalOffer();
3127 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003128 MediaExpectations media_expectations;
3129 media_expectations.CalleeExpectsSomeAudio(1);
3130 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07003131
3132 // We received a frame, so we should have nonzero "bytes received" stats for
3133 // the unsignaled stream, if stats are working for it.
3134 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3135 callee()->NewGetStats();
3136 ASSERT_NE(nullptr, report);
3137 auto inbound_stream_stats =
3138 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3139 ASSERT_EQ(1U, inbound_stream_stats.size());
3140 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
3141 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07003142 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
3143}
3144
Taylor Brandstettera4653442018-06-19 09:44:26 -07003145// Same as above but for the legacy stats implementation.
3146TEST_P(PeerConnectionIntegrationTest,
3147 GetStatsForUnsignaledStreamWithOldStatsApi) {
3148 ASSERT_TRUE(CreatePeerConnectionWrappers());
3149 ConnectFakeSignaling();
3150 caller()->AddAudioTrack();
3151 // Remove SSRCs and MSIDs from the received offer SDP.
3152 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3153 caller()->CreateAndSetAndSignalOffer();
3154 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3155
3156 // Note that, since the old stats implementation associates SSRCs with tracks
3157 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
3158 // associated track ID. So we can't use the track "selector" argument.
3159 //
3160 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
3161 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003162 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07003163 kDefaultTimeout);
3164}
3165
zhihuangf8164932017-05-19 13:09:47 -07003166// Test that we can successfully get the media related stats (audio level
3167// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003168TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07003169 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
3170 ASSERT_TRUE(CreatePeerConnectionWrappers());
3171 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003172 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07003173 // Remove SSRCs and MSIDs from the received offer SDP.
3174 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3175 caller()->CreateAndSetAndSignalOffer();
3176 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003177 MediaExpectations media_expectations;
3178 media_expectations.CalleeExpectsSomeAudio(1);
3179 media_expectations.CalleeExpectsSomeVideo(1);
3180 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07003181
3182 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3183 callee()->NewGetStats();
3184 ASSERT_NE(nullptr, report);
3185
3186 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3187 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
3188 ASSERT_GE(audio_index, 0);
3189 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07003190}
3191
deadbeef4e2deab2017-09-20 13:56:21 -07003192// Helper for test below.
3193void ModifySsrcs(cricket::SessionDescription* desc) {
3194 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07003195 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08003196 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07003197 for (uint32_t& ssrc : stream.ssrcs) {
3198 ssrc = rtc::CreateRandomId();
3199 }
3200 }
3201 }
3202}
3203
3204// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
3205// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
3206// This should result in two "RTCInboundRTPStreamStats", but only one
3207// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
3208// being reset to 0 once the SSRC change occurs.
3209//
3210// Regression test for this bug:
3211// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
3212//
3213// The bug causes the track stats to only represent one of the two streams:
3214// whichever one has the higher SSRC. So with this bug, there was a 50% chance
3215// that the track stat counters would reset to 0 when the new stream is
3216// received, and a 50% chance that they'll stop updating (while
3217// "concealed_samples" continues increasing, due to silence being generated for
3218// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003219TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08003220 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07003221 ASSERT_TRUE(CreatePeerConnectionWrappers());
3222 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003223 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07003224 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
3225 // that doesn't signal SSRCs (from the callee's perspective).
3226 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
3227 caller()->CreateAndSetAndSignalOffer();
3228 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3229 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003230 {
3231 MediaExpectations media_expectations;
3232 media_expectations.CalleeExpectsSomeAudio(50);
3233 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3234 }
deadbeef4e2deab2017-09-20 13:56:21 -07003235 // Some audio frames were received, so we should have nonzero "samples
3236 // received" for the track.
3237 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
3238 callee()->NewGetStats();
3239 ASSERT_NE(nullptr, report);
3240 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3241 ASSERT_EQ(1U, track_stats.size());
3242 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3243 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
3244 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
3245
3246 // Create a new offer and munge it to cause the caller to use a new SSRC.
3247 caller()->SetGeneratedSdpMunger(ModifySsrcs);
3248 caller()->CreateAndSetAndSignalOffer();
3249 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3250 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
3251 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003252 {
3253 MediaExpectations media_expectations;
3254 media_expectations.CalleeExpectsSomeAudio(25);
3255 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3256 }
deadbeef4e2deab2017-09-20 13:56:21 -07003257
3258 report = callee()->NewGetStats();
3259 ASSERT_NE(nullptr, report);
3260 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
3261 ASSERT_EQ(1U, track_stats.size());
3262 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
3263 // The "total samples received" stat should only be greater than it was
3264 // before.
3265 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
3266 // Right now, the new SSRC will cause the counters to reset to 0.
3267 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
3268
3269 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08003270 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07003271 // good sign that we're seeing stats from the old stream that's no longer
3272 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08003273 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07003274 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
3275 EXPECT_LT(*track_stats[0]->concealed_samples,
3276 *track_stats[0]->total_samples_received *
3277 kAcceptableConcealedSamplesPercentage);
3278
3279 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
3280 // sanity check that the SSRC really changed.
3281 // TODO(deadbeef): This isn't working right now, because we're not returning
3282 // *any* stats for the inactive stream. Uncomment when the bug is completely
3283 // fixed.
3284 // auto inbound_stream_stats =
3285 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
3286 // ASSERT_EQ(2U, inbound_stream_stats.size());
3287}
3288
deadbeef1dcb1642017-03-29 21:08:16 -07003289// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003290TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003291 PeerConnectionFactory::Options dtls_10_options;
3292 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3293 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3294 dtls_10_options));
3295 ConnectFakeSignaling();
3296 // Do normal offer/answer and wait for some frames to be received in each
3297 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003298 caller()->AddAudioVideoTracks();
3299 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003300 caller()->CreateAndSetAndSignalOffer();
3301 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003302 MediaExpectations media_expectations;
3303 media_expectations.ExpectBidirectionalAudioAndVideo();
3304 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003305}
3306
3307// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003308TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003309 PeerConnectionFactory::Options dtls_10_options;
3310 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3311 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
3312 dtls_10_options));
3313 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003314 caller()->AddAudioVideoTracks();
3315 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003316 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003317 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003318 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003319 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003320 kDefaultTimeout);
3321 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003322 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003323 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003324 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3325 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3326 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003327}
3328
3329// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003330TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003331 PeerConnectionFactory::Options dtls_12_options;
3332 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3333 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3334 dtls_12_options));
3335 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003336 caller()->AddAudioVideoTracks();
3337 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003338 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003339 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003340 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003341 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003342 kDefaultTimeout);
3343 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003344 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003345 // TODO(bugs.webrtc.org/9456): Fix it.
Ying Wangef3998f2019-12-09 13:06:53 +01003346 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3347 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3348 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003349}
3350
3351// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3352// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003353TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003354 PeerConnectionFactory::Options caller_options;
3355 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3356 PeerConnectionFactory::Options callee_options;
3357 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3358 ASSERT_TRUE(
3359 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3360 ConnectFakeSignaling();
3361 // Do normal offer/answer and wait for some frames to be received in each
3362 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003363 caller()->AddAudioVideoTracks();
3364 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003365 caller()->CreateAndSetAndSignalOffer();
3366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003367 MediaExpectations media_expectations;
3368 media_expectations.ExpectBidirectionalAudioAndVideo();
3369 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003370}
3371
3372// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3373// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003374TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003375 PeerConnectionFactory::Options caller_options;
3376 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3377 PeerConnectionFactory::Options callee_options;
3378 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3379 ASSERT_TRUE(
3380 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3381 ConnectFakeSignaling();
3382 // Do normal offer/answer and wait for some frames to be received in each
3383 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003384 caller()->AddAudioVideoTracks();
3385 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003386 caller()->CreateAndSetAndSignalOffer();
3387 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003388 MediaExpectations media_expectations;
3389 media_expectations.ExpectBidirectionalAudioAndVideo();
3390 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003391}
3392
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003393// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3394// works as expected; the cipher should only be used if enabled by both sides.
3395TEST_P(PeerConnectionIntegrationTest,
3396 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3397 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003398 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003399 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003400 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3401 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003402 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3403 TestNegotiatedCipherSuite(caller_options, callee_options,
3404 expected_cipher_suite);
3405}
3406
3407TEST_P(PeerConnectionIntegrationTest,
3408 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3409 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003410 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3411 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003412 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003413 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003414 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3415 TestNegotiatedCipherSuite(caller_options, callee_options,
3416 expected_cipher_suite);
3417}
3418
3419TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3420 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003421 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003422 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003423 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003424 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3425 TestNegotiatedCipherSuite(caller_options, callee_options,
3426 expected_cipher_suite);
3427}
3428
deadbeef1dcb1642017-03-29 21:08:16 -07003429// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003430TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003431 bool local_gcm_enabled = false;
3432 bool remote_gcm_enabled = false;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003433 bool aes_ctr_enabled = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003434 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3435 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003436 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003437}
3438
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003439// Test that a GCM cipher is used if both ends support it and non-GCM is
3440// disabled.
3441TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenOnlyGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003442 bool local_gcm_enabled = true;
3443 bool remote_gcm_enabled = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003444 bool aes_ctr_enabled = false;
deadbeef1dcb1642017-03-29 21:08:16 -07003445 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3446 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003447 aes_ctr_enabled, expected_cipher_suite);
deadbeef1dcb1642017-03-29 21:08:16 -07003448}
3449
deadbeef7914b8c2017-04-21 03:23:33 -07003450// Verify that media can be transmitted end-to-end when GCM crypto suites are
3451// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3452// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3453// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003454TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003455 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003456 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
Philipp Hancke2ebbff82019-10-26 06:12:55 +02003457 gcm_options.crypto_options.srtp.enable_aes128_sha1_80_crypto_cipher = false;
deadbeef7914b8c2017-04-21 03:23:33 -07003458 ASSERT_TRUE(
3459 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3460 ConnectFakeSignaling();
3461 // Do normal offer/answer and wait for some frames to be received in each
3462 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003463 caller()->AddAudioVideoTracks();
3464 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003465 caller()->CreateAndSetAndSignalOffer();
3466 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003467 MediaExpectations media_expectations;
3468 media_expectations.ExpectBidirectionalAudioAndVideo();
3469 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003470}
3471
deadbeef1dcb1642017-03-29 21:08:16 -07003472// This test sets up a call between two parties with audio, video and an RTP
3473// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003474TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003475 PeerConnectionInterface::RTCConfiguration rtc_config;
3476 rtc_config.enable_rtp_data_channel = true;
3477 rtc_config.enable_dtls_srtp = false;
3478 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003479 ConnectFakeSignaling();
3480 // Expect that data channel created on caller side will show up for callee as
3481 // well.
3482 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003483 caller()->AddAudioVideoTracks();
3484 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003485 caller()->CreateAndSetAndSignalOffer();
3486 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3487 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003488 MediaExpectations media_expectations;
3489 media_expectations.ExpectBidirectionalAudioAndVideo();
3490 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003491 ASSERT_NE(nullptr, caller()->data_channel());
3492 ASSERT_NE(nullptr, callee()->data_channel());
3493 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3494 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3495
3496 // Ensure data can be sent in both directions.
3497 std::string data = "hello world";
3498 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3499 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3500 kDefaultTimeout);
3501 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3502 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3503 kDefaultTimeout);
3504}
3505
Eldar Rellod9ebe012020-03-18 20:41:45 +02003506TEST_P(PeerConnectionIntegrationTest, RtpDataChannelWorksAfterRollback) {
3507 PeerConnectionInterface::RTCConfiguration rtc_config;
3508 rtc_config.enable_rtp_data_channel = true;
3509 rtc_config.enable_dtls_srtp = false;
3510 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
3511 ConnectFakeSignaling();
3512 auto data_channel = caller()->pc()->CreateDataChannel("label_1", nullptr);
3513 ASSERT_TRUE(data_channel.get() != nullptr);
3514 caller()->CreateAndSetAndSignalOffer();
3515 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3516
3517 caller()->CreateDataChannel("label_2", nullptr);
3518 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
3519 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
3520 caller()->pc()->SetLocalDescription(observer,
3521 caller()->CreateOfferAndWait().release());
3522 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
3523 caller()->Rollback();
3524
3525 std::string data = "hello world";
3526 SendRtpDataWithRetries(data_channel, data, 5);
3527 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3528 kDefaultTimeout);
3529}
3530
deadbeef1dcb1642017-03-29 21:08:16 -07003531// Ensure that an RTP data channel is signaled as closed for the caller when
3532// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003533TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003534 RtpDataChannelSignaledClosedInCalleeOffer) {
3535 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003536 PeerConnectionInterface::RTCConfiguration rtc_config;
3537 rtc_config.enable_rtp_data_channel = true;
3538 rtc_config.enable_dtls_srtp = false;
3539 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003540 ConnectFakeSignaling();
3541 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003542 caller()->AddAudioVideoTracks();
3543 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003544 caller()->CreateAndSetAndSignalOffer();
3545 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3546 ASSERT_NE(nullptr, caller()->data_channel());
3547 ASSERT_NE(nullptr, callee()->data_channel());
3548 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3549 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3550
3551 // Close the data channel on the callee, and do an updated offer/answer.
3552 callee()->data_channel()->Close();
3553 callee()->CreateAndSetAndSignalOffer();
3554 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3555 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3556 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3557}
3558
3559// Tests that data is buffered in an RTP data channel until an observer is
3560// registered for it.
3561//
3562// NOTE: RTP data channels can receive data before the underlying
3563// transport has detected that a channel is writable and thus data can be
3564// received before the data channel state changes to open. That is hard to test
3565// but the same buffering is expected to be used in that case.
Yves Gerey100fe632020-01-17 19:15:53 +01003566//
3567// Use fake clock and simulated network delay so that we predictably can wait
3568// until an SCTP message has been delivered without "sleep()"ing.
3569TEST_P(PeerConnectionIntegrationTestWithFakeClock,
deadbeef1dcb1642017-03-29 21:08:16 -07003570 DataBufferedUntilRtpDataChannelObserverRegistered) {
deadbeef1dcb1642017-03-29 21:08:16 -07003571 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3572 virtual_socket_server()->UpdateDelayDistribution();
3573
Niels Möllerf06f9232018-08-07 12:32:18 +02003574 PeerConnectionInterface::RTCConfiguration rtc_config;
3575 rtc_config.enable_rtp_data_channel = true;
3576 rtc_config.enable_dtls_srtp = false;
3577 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003578 ConnectFakeSignaling();
3579 caller()->CreateDataChannel();
3580 caller()->CreateAndSetAndSignalOffer();
3581 ASSERT_TRUE(caller()->data_channel() != nullptr);
3582 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
Yves Gerey100fe632020-01-17 19:15:53 +01003583 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003584 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
Yves Gerey100fe632020-01-17 19:15:53 +01003585 kDefaultTimeout, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003586 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3587 callee()->data_channel()->state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003588 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003589
3590 // Unregister the observer which is normally automatically registered.
3591 callee()->data_channel()->UnregisterObserver();
3592 // Send data and advance fake clock until it should have been received.
3593 std::string data = "hello world";
3594 caller()->data_channel()->Send(DataBuffer(data));
Yves Gerey100fe632020-01-17 19:15:53 +01003595 SIMULATED_WAIT(false, 50, FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003596
3597 // Attach data channel and expect data to be received immediately. Note that
3598 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3599 // further, but data can be received even if the callback is asynchronous.
3600 MockDataChannelObserver new_observer(callee()->data_channel());
3601 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01003602 FakeClock());
deadbeef1dcb1642017-03-29 21:08:16 -07003603}
3604
3605// This test sets up a call between two parties with audio, video and but only
3606// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003607TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003608 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3609 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003610 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003611 rtc_config_1.enable_dtls_srtp = false;
3612 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3613 rtc_config_2.enable_dtls_srtp = false;
3614 rtc_config_2.enable_dtls_srtp = false;
3615 ASSERT_TRUE(
3616 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003617 ConnectFakeSignaling();
3618 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003619 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003620 caller()->AddAudioVideoTracks();
3621 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003622 caller()->CreateAndSetAndSignalOffer();
3623 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3624 // The caller should still have a data channel, but it should be closed, and
3625 // one should ever have been created for the callee.
3626 EXPECT_TRUE(caller()->data_channel() != nullptr);
3627 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3628 EXPECT_EQ(nullptr, callee()->data_channel());
3629}
3630
3631// This test sets up a call between two parties with audio, and video. When
3632// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003633TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003634 PeerConnectionInterface::RTCConfiguration rtc_config;
3635 rtc_config.enable_rtp_data_channel = true;
3636 rtc_config.enable_dtls_srtp = false;
3637 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003638 ConnectFakeSignaling();
3639 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003640 caller()->AddAudioVideoTracks();
3641 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003642 caller()->CreateAndSetAndSignalOffer();
3643 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3644 // Create data channel and do new offer and answer.
3645 caller()->CreateDataChannel();
3646 caller()->CreateAndSetAndSignalOffer();
3647 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3648 ASSERT_NE(nullptr, caller()->data_channel());
3649 ASSERT_NE(nullptr, callee()->data_channel());
3650 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3651 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3652 // Ensure data can be sent in both directions.
3653 std::string data = "hello world";
3654 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3655 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3656 kDefaultTimeout);
3657 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3658 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3659 kDefaultTimeout);
3660}
3661
3662#ifdef HAVE_SCTP
3663
3664// This test sets up a call between two parties with audio, video and an SCTP
3665// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003666TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003667 ASSERT_TRUE(CreatePeerConnectionWrappers());
3668 ConnectFakeSignaling();
3669 // Expect that data channel created on caller side will show up for callee as
3670 // well.
3671 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003672 caller()->AddAudioVideoTracks();
3673 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003674 caller()->CreateAndSetAndSignalOffer();
3675 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3676 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003677 MediaExpectations media_expectations;
3678 media_expectations.ExpectBidirectionalAudioAndVideo();
3679 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003680 // Caller data channel should already exist (it created one). Callee data
3681 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3682 ASSERT_NE(nullptr, caller()->data_channel());
3683 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3684 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3685 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3686
3687 // Ensure data can be sent in both directions.
3688 std::string data = "hello world";
3689 caller()->data_channel()->Send(DataBuffer(data));
3690 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3691 kDefaultTimeout);
3692 callee()->data_channel()->Send(DataBuffer(data));
3693 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3694 kDefaultTimeout);
3695}
3696
3697// Ensure that when the callee closes an SCTP data channel, the closing
3698// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003699TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003700 // Same procedure as above test.
3701 ASSERT_TRUE(CreatePeerConnectionWrappers());
3702 ConnectFakeSignaling();
3703 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003704 caller()->AddAudioVideoTracks();
3705 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003706 caller()->CreateAndSetAndSignalOffer();
3707 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3708 ASSERT_NE(nullptr, caller()->data_channel());
3709 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3710 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3711 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3712
3713 // Close the data channel on the callee side, and wait for it to reach the
3714 // "closed" state on both sides.
3715 callee()->data_channel()->Close();
3716 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3717 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3718}
3719
Seth Hampson2f0d7022018-02-20 11:54:42 -08003720TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003721 ASSERT_TRUE(CreatePeerConnectionWrappers());
3722 ConnectFakeSignaling();
3723 webrtc::DataChannelInit init;
3724 init.id = 53;
3725 init.maxRetransmits = 52;
3726 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003727 caller()->AddAudioVideoTracks();
3728 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003729 caller()->CreateAndSetAndSignalOffer();
3730 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003731 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3732 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003733 // Since "negotiated" is false, the "id" parameter should be ignored.
3734 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003735 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3736 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3737 EXPECT_FALSE(callee()->data_channel()->negotiated());
3738}
3739
deadbeef1dcb1642017-03-29 21:08:16 -07003740// Test usrsctp's ability to process unordered data stream, where data actually
3741// arrives out of order using simulated delays. Previously there have been some
3742// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003743TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003744 // Introduce random network delays.
3745 // Otherwise it's not a true "unordered" test.
3746 virtual_socket_server()->set_delay_mean(20);
3747 virtual_socket_server()->set_delay_stddev(5);
3748 virtual_socket_server()->UpdateDelayDistribution();
3749 // Normal procedure, but with unordered data channel config.
3750 ASSERT_TRUE(CreatePeerConnectionWrappers());
3751 ConnectFakeSignaling();
3752 webrtc::DataChannelInit init;
3753 init.ordered = false;
3754 caller()->CreateDataChannel(&init);
3755 caller()->CreateAndSetAndSignalOffer();
3756 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3757 ASSERT_NE(nullptr, caller()->data_channel());
3758 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3759 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3760 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3761
3762 static constexpr int kNumMessages = 100;
3763 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3764 static constexpr size_t kMaxMessageSize = 4096;
3765 // Create and send random messages.
3766 std::vector<std::string> sent_messages;
3767 for (int i = 0; i < kNumMessages; ++i) {
3768 size_t length =
3769 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3770 std::string message;
3771 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3772 caller()->data_channel()->Send(DataBuffer(message));
3773 callee()->data_channel()->Send(DataBuffer(message));
3774 sent_messages.push_back(message);
3775 }
3776
3777 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003778 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003779 caller()->data_observer()->received_message_count(),
3780 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003781 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003782 callee()->data_observer()->received_message_count(),
3783 kDefaultTimeout);
3784
3785 // Sort and compare to make sure none of the messages were corrupted.
3786 std::vector<std::string> caller_received_messages =
3787 caller()->data_observer()->messages();
3788 std::vector<std::string> callee_received_messages =
3789 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003790 absl::c_sort(sent_messages);
3791 absl::c_sort(caller_received_messages);
3792 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003793 EXPECT_EQ(sent_messages, caller_received_messages);
3794 EXPECT_EQ(sent_messages, callee_received_messages);
3795}
3796
3797// This test sets up a call between two parties with audio, and video. When
3798// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003799TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003800 ASSERT_TRUE(CreatePeerConnectionWrappers());
3801 ConnectFakeSignaling();
3802 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003803 caller()->AddAudioVideoTracks();
3804 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003805 caller()->CreateAndSetAndSignalOffer();
3806 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3807 // Create data channel and do new offer and answer.
3808 caller()->CreateDataChannel();
3809 caller()->CreateAndSetAndSignalOffer();
3810 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3811 // Caller data channel should already exist (it created one). Callee data
3812 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3813 ASSERT_NE(nullptr, caller()->data_channel());
3814 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3815 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3816 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3817 // Ensure data can be sent in both directions.
3818 std::string data = "hello world";
3819 caller()->data_channel()->Send(DataBuffer(data));
3820 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3821 kDefaultTimeout);
3822 callee()->data_channel()->Send(DataBuffer(data));
3823 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3824 kDefaultTimeout);
3825}
3826
deadbeef7914b8c2017-04-21 03:23:33 -07003827// Set up a connection initially just using SCTP data channels, later upgrading
3828// to audio/video, ensuring frames are received end-to-end. Effectively the
3829// inverse of the test above.
3830// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003831TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003832 ASSERT_TRUE(CreatePeerConnectionWrappers());
3833 ConnectFakeSignaling();
3834 // Do initial offer/answer with just data channel.
3835 caller()->CreateDataChannel();
3836 caller()->CreateAndSetAndSignalOffer();
3837 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3838 // Wait until data can be sent over the data channel.
3839 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3840 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3841 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3842
3843 // Do subsequent offer/answer with two-way audio and video. Audio and video
3844 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003845 caller()->AddAudioVideoTracks();
3846 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003847 caller()->CreateAndSetAndSignalOffer();
3848 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003849 MediaExpectations media_expectations;
3850 media_expectations.ExpectBidirectionalAudioAndVideo();
3851 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003852}
3853
deadbeef8b7e9ad2017-05-25 09:38:55 -07003854static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003855 cricket::SctpDataContentDescription* dcd_offer =
3856 GetFirstSctpDataContentDescription(desc);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01003857 // See https://crbug.com/webrtc/11211 - this function is a no-op
Steve Antonb1c1de12017-12-21 15:14:30 -08003858 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003859 dcd_offer->set_use_sctpmap(false);
3860 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3861}
3862
3863// Test that the data channel works when a spec-compliant SCTP m= section is
3864// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3865// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003866TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003867 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3868 ASSERT_TRUE(CreatePeerConnectionWrappers());
3869 ConnectFakeSignaling();
3870 caller()->CreateDataChannel();
3871 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3872 caller()->CreateAndSetAndSignalOffer();
3873 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3874 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3875 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3876 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3877
3878 // Ensure data can be sent in both directions.
3879 std::string data = "hello world";
3880 caller()->data_channel()->Send(DataBuffer(data));
3881 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3882 kDefaultTimeout);
3883 callee()->data_channel()->Send(DataBuffer(data));
3884 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3885 kDefaultTimeout);
3886}
3887
deadbeef1dcb1642017-03-29 21:08:16 -07003888#endif // HAVE_SCTP
3889
3890// Test that the ICE connection and gathering states eventually reach
3891// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003892TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003893 ASSERT_TRUE(CreatePeerConnectionWrappers());
3894 ConnectFakeSignaling();
3895 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003896 caller()->AddAudioVideoTracks();
3897 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003898 caller()->CreateAndSetAndSignalOffer();
3899 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3900 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3901 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3902 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3903 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3904 // After the best candidate pair is selected and all candidates are signaled,
3905 // the ICE connection state should reach "complete".
3906 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3907 // answerer/"callee" by default) only reaches "connected". When this is
3908 // fixed, this test should be updated.
3909 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3910 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00003911 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3912 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003913}
3914
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003915constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
3916 cricket::PORTALLOCATOR_DISABLE_RELAY |
3917 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003918
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003919// Use a mock resolver to resolve the hostname back to the original IP on both
3920// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003921TEST_P(PeerConnectionIntegrationTest,
3922 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003923 auto caller_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02003924 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003925 auto callee_resolver_factory =
Mirko Bonadei317a1f02019-09-17 17:06:18 +02003926 std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003927 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
3928 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003929
3930 // This also verifies that the injected AsyncResolverFactory is used by
3931 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003932 EXPECT_CALL(*caller_resolver_factory, Create())
3933 .WillOnce(Return(&caller_async_resolver));
3934 webrtc::PeerConnectionDependencies caller_deps(nullptr);
3935 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
3936
3937 EXPECT_CALL(*callee_resolver_factory, Create())
3938 .WillOnce(Return(&callee_async_resolver));
3939 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3940 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
3941
3942 PeerConnectionInterface::RTCConfiguration config;
3943 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3944 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3945
3946 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3947 config, std::move(caller_deps), config, std::move(callee_deps)));
3948
3949 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
3950 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
3951
3952 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07003953 caller()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02003954 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wangecd30542019-05-22 14:34:56 -07003955 callee()->SetMdnsResponder(
Mirko Bonadei317a1f02019-09-17 17:06:18 +02003956 std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003957
3958 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003959
3960 ConnectFakeSignaling();
3961 caller()->AddAudioVideoTracks();
3962 callee()->AddAudioVideoTracks();
3963 caller()->CreateAndSetAndSignalOffer();
3964 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3965 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3966 caller()->ice_connection_state(), kDefaultTimeout);
3967 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3968 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08003969
Ying Wangef3998f2019-12-09 13:06:53 +01003970 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
3971 "WebRTC.PeerConnection.CandidatePairType_UDP",
3972 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003973}
3974
Steve Antonede9ca52017-10-16 13:04:27 -07003975// Test that firewalling the ICE connection causes the clients to identify the
3976// disconnected state and then removing the firewall causes them to reconnect.
3977class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003978 : public PeerConnectionIntegrationBaseTest,
3979 public ::testing::WithParamInterface<
3980 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003981 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003982 PeerConnectionIntegrationIceStatesTest()
3983 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3984 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003985 }
3986
3987 void StartStunServer(const SocketAddress& server_address) {
3988 stun_server_.reset(
Niels Möller091617d2020-12-02 15:32:08 +01003989 cricket::TestStunServer::Create(firewall(), server_address));
Steve Antonede9ca52017-10-16 13:04:27 -07003990 }
3991
3992 bool TestIPv6() {
3993 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3994 }
3995
3996 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003997 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
3998 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07003999 }
4000
4001 std::vector<SocketAddress> CallerAddresses() {
4002 std::vector<SocketAddress> addresses;
4003 addresses.push_back(SocketAddress("1.1.1.1", 0));
4004 if (TestIPv6()) {
4005 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
4006 }
4007 return addresses;
4008 }
4009
4010 std::vector<SocketAddress> CalleeAddresses() {
4011 std::vector<SocketAddress> addresses;
4012 addresses.push_back(SocketAddress("2.2.2.2", 0));
4013 if (TestIPv6()) {
4014 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
4015 }
4016 return addresses;
4017 }
4018
4019 void SetUpNetworkInterfaces() {
4020 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07004021 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
4022 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07004023
4024 // Add network addresses for test.
4025 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004026 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004027 }
4028 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004029 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004030 }
4031 }
4032
4033 private:
4034 uint32_t port_allocator_flags_;
4035 std::unique_ptr<cricket::TestStunServer> stun_server_;
4036};
4037
Yves Gerey100fe632020-01-17 19:15:53 +01004038// Ensure FakeClockForTest is constructed first (see class for rationale).
4039class PeerConnectionIntegrationIceStatesTestWithFakeClock
4040 : public FakeClockForTest,
4041 public PeerConnectionIntegrationIceStatesTest {};
4042
Steve Antonede9ca52017-10-16 13:04:27 -07004043// Tests that the PeerConnection goes through all the ICE gathering/connection
4044// states over the duration of the call. This includes Disconnected and Failed
4045// states, induced by putting a firewall between the peers and waiting for them
4046// to time out.
Yves Gerey100fe632020-01-17 19:15:53 +01004047TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock, VerifyIceStates) {
Steve Antonede9ca52017-10-16 13:04:27 -07004048 const SocketAddress kStunServerAddress =
4049 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
4050 StartStunServer(kStunServerAddress);
4051
4052 PeerConnectionInterface::RTCConfiguration config;
4053 PeerConnectionInterface::IceServer ice_stun_server;
4054 ice_stun_server.urls.push_back(
4055 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4056 kStunServerAddress.PortAsString());
4057 config.servers.push_back(ice_stun_server);
4058
4059 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4060 ConnectFakeSignaling();
4061 SetPortAllocatorFlags();
4062 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004063 caller()->AddAudioVideoTracks();
4064 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004065
4066 // Initial state before anything happens.
4067 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4068 caller()->ice_gathering_state());
4069 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4070 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004071 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4072 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004073
4074 // Start the call by creating the offer, setting it as the local description,
4075 // then sending it to the peer who will respond with an answer. This happens
4076 // asynchronously so that we can watch the states as it runs in the
4077 // background.
4078 caller()->CreateAndSetAndSignalOffer();
4079
Steve Antona9b67ce2020-01-16 14:00:44 -08004080 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4081 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004082 FakeClock());
Steve Antona9b67ce2020-01-16 14:00:44 -08004083 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4084 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004085 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004086
4087 // Verify that the observer was notified of the intermediate transitions.
4088 EXPECT_THAT(caller()->ice_connection_state_history(),
4089 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4090 PeerConnectionInterface::kIceConnectionConnected,
4091 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004092 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4093 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4094 PeerConnectionInterface::kIceConnectionConnected,
4095 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004096 EXPECT_THAT(
4097 caller()->peer_connection_state_history(),
4098 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004099 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004100 EXPECT_THAT(caller()->ice_gathering_state_history(),
4101 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4102 PeerConnectionInterface::kIceGatheringComplete));
4103
4104 // Block connections to/from the caller and wait for ICE to become
4105 // disconnected.
4106 for (const auto& caller_address : CallerAddresses()) {
4107 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4108 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004110 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4111 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004112 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004113 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4114 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004115 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004116
4117 // Let ICE re-establish by removing the firewall rules.
4118 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004119 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004120 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4121 caller()->ice_connection_state(), kDefaultTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004122 FakeClock());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004123 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004124 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004125 kDefaultTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004126
4127 // According to RFC7675, if there is no response within 30 seconds then the
4128 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004129 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004130 constexpr int kConsentTimeout = 30000;
4131 for (const auto& caller_address : CallerAddresses()) {
4132 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4133 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004134 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004135 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4136 caller()->ice_connection_state(), kConsentTimeout,
Yves Gerey100fe632020-01-17 19:15:53 +01004137 FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004138 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4139 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004140 kConsentTimeout, FakeClock());
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004141}
4142
4143// Tests that if the connection doesn't get set up properly we eventually reach
4144// the "failed" iceConnectionState.
Yves Gerey100fe632020-01-17 19:15:53 +01004145TEST_P(PeerConnectionIntegrationIceStatesTestWithFakeClock,
4146 IceStateSetupFailure) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004147 // Block connections to/from the caller and wait for ICE to become
4148 // disconnected.
4149 for (const auto& caller_address : CallerAddresses()) {
4150 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4151 }
4152
4153 ASSERT_TRUE(CreatePeerConnectionWrappers());
4154 ConnectFakeSignaling();
4155 SetPortAllocatorFlags();
4156 SetUpNetworkInterfaces();
4157 caller()->AddAudioVideoTracks();
4158 caller()->CreateAndSetAndSignalOffer();
4159
4160 // According to RFC7675, if there is no response within 30 seconds then the
4161 // peer should consider the other side to have rejected the connection. This
4162 // is signaled by the state transitioning to "failed".
4163 constexpr int kConsentTimeout = 30000;
4164 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4165 caller()->standardized_ice_connection_state(),
Yves Gerey100fe632020-01-17 19:15:53 +01004166 kConsentTimeout, FakeClock());
Steve Antonede9ca52017-10-16 13:04:27 -07004167}
4168
4169// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4170// and that the statistics in the metric observers are updated correctly.
4171TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4172 ASSERT_TRUE(CreatePeerConnectionWrappers());
4173 ConnectFakeSignaling();
4174 SetPortAllocatorFlags();
4175 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004176 caller()->AddAudioVideoTracks();
4177 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004178 caller()->CreateAndSetAndSignalOffer();
4179
4180 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton692f3c72020-01-16 14:12:31 -08004181 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4182 caller()->ice_connection_state(), kDefaultTimeout);
4183 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4184 callee()->ice_connection_state(), kDefaultTimeout);
Steve Antonede9ca52017-10-16 13:04:27 -07004185
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004186 // TODO(bugs.webrtc.org/9456): Fix it.
4187 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4188 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4189 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4190 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004191 if (TestIPv6()) {
4192 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4193 // connection.
Ying Wangef3998f2019-12-09 13:06:53 +01004194 EXPECT_METRIC_EQ(0, num_best_ipv4);
4195 EXPECT_METRIC_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004196 } else {
Ying Wangef3998f2019-12-09 13:06:53 +01004197 EXPECT_METRIC_EQ(1, num_best_ipv4);
4198 EXPECT_METRIC_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004199 }
4200
Ying Wangef3998f2019-12-09 13:06:53 +01004201 EXPECT_METRIC_EQ(0, webrtc::metrics::NumEvents(
4202 "WebRTC.PeerConnection.CandidatePairType_UDP",
4203 webrtc::kIceCandidatePairHostHost));
4204 EXPECT_METRIC_EQ(1, webrtc::metrics::NumEvents(
4205 "WebRTC.PeerConnection.CandidatePairType_UDP",
4206 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004207}
4208
4209constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4210 cricket::PORTALLOCATOR_DISABLE_STUN |
4211 cricket::PORTALLOCATOR_DISABLE_RELAY;
4212constexpr uint32_t kFlagsIPv6NoStun =
4213 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4214 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4215constexpr uint32_t kFlagsIPv4Stun =
4216 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4217
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004218INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004219 PeerConnectionIntegrationTest,
4220 PeerConnectionIntegrationIceStatesTest,
4221 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4222 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4223 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4224 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004225
Yves Gerey100fe632020-01-17 19:15:53 +01004226INSTANTIATE_TEST_SUITE_P(
4227 PeerConnectionIntegrationTest,
4228 PeerConnectionIntegrationIceStatesTestWithFakeClock,
4229 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4230 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4231 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4232 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
4233
deadbeef1dcb1642017-03-29 21:08:16 -07004234// This test sets up a call between two parties with audio and video.
4235// During the call, the caller restarts ICE and the test verifies that
4236// new ICE candidates are generated and audio and video still can flow, and the
4237// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004238TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004239 ASSERT_TRUE(CreatePeerConnectionWrappers());
4240 ConnectFakeSignaling();
4241 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004242 caller()->AddAudioVideoTracks();
4243 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004244 caller()->CreateAndSetAndSignalOffer();
4245 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4246 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4247 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004248 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4249 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004250
4251 // To verify that the ICE restart actually occurs, get
4252 // ufrag/password/candidates before and after restart.
4253 // Create an SDP string of the first audio candidate for both clients.
4254 const webrtc::IceCandidateCollection* audio_candidates_caller =
4255 caller()->pc()->local_description()->candidates(0);
4256 const webrtc::IceCandidateCollection* audio_candidates_callee =
4257 callee()->pc()->local_description()->candidates(0);
4258 ASSERT_GT(audio_candidates_caller->count(), 0u);
4259 ASSERT_GT(audio_candidates_callee->count(), 0u);
4260 std::string caller_candidate_pre_restart;
4261 ASSERT_TRUE(
4262 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4263 std::string callee_candidate_pre_restart;
4264 ASSERT_TRUE(
4265 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4266 const cricket::SessionDescription* desc =
4267 caller()->pc()->local_description()->description();
4268 std::string caller_ufrag_pre_restart =
4269 desc->transport_infos()[0].description.ice_ufrag;
4270 desc = callee()->pc()->local_description()->description();
4271 std::string callee_ufrag_pre_restart =
4272 desc->transport_infos()[0].description.ice_ufrag;
4273
Alex Drake00c7ecf2019-08-06 10:54:47 -07004274 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004275 // Have the caller initiate an ICE restart.
4276 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4277 caller()->CreateAndSetAndSignalOffer();
4278 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4279 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4280 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004281 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004282 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4283
4284 // Grab the ufrags/candidates again.
4285 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4286 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4287 ASSERT_GT(audio_candidates_caller->count(), 0u);
4288 ASSERT_GT(audio_candidates_callee->count(), 0u);
4289 std::string caller_candidate_post_restart;
4290 ASSERT_TRUE(
4291 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4292 std::string callee_candidate_post_restart;
4293 ASSERT_TRUE(
4294 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4295 desc = caller()->pc()->local_description()->description();
4296 std::string caller_ufrag_post_restart =
4297 desc->transport_infos()[0].description.ice_ufrag;
4298 desc = callee()->pc()->local_description()->description();
4299 std::string callee_ufrag_post_restart =
4300 desc->transport_infos()[0].description.ice_ufrag;
4301 // Sanity check that an ICE restart was actually negotiated in SDP.
4302 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4303 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4304 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4305 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07004306 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004307
4308 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004309 MediaExpectations media_expectations;
4310 media_expectations.ExpectBidirectionalAudioAndVideo();
4311 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004312}
4313
4314// Verify that audio/video can be received end-to-end when ICE renomination is
4315// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004316TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004317 PeerConnectionInterface::RTCConfiguration config;
4318 config.enable_ice_renomination = true;
4319 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4320 ConnectFakeSignaling();
4321 // Do normal offer/answer and wait for some frames to be received in each
4322 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004323 caller()->AddAudioVideoTracks();
4324 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004325 caller()->CreateAndSetAndSignalOffer();
4326 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4327 // Sanity check that ICE renomination was actually negotiated.
4328 const cricket::SessionDescription* desc =
4329 caller()->pc()->local_description()->description();
4330 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004331 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004332 }
4333 desc = callee()->pc()->local_description()->description();
4334 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004335 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004336 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004337 MediaExpectations media_expectations;
4338 media_expectations.ExpectBidirectionalAudioAndVideo();
4339 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004340}
4341
Steve Anton6f25b092017-10-23 09:39:20 -07004342// With a max bundle policy and RTCP muxing, adding a new media description to
4343// the connection should not affect ICE at all because the new media will use
4344// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004345TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004346 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004347 PeerConnectionInterface::RTCConfiguration config;
4348 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4349 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4350 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4351 config, PeerConnectionInterface::RTCConfiguration()));
4352 ConnectFakeSignaling();
4353
Steve Anton15324772018-01-16 10:26:49 -08004354 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004355 caller()->CreateAndSetAndSignalOffer();
4356 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004357 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4358 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004359
4360 caller()->clear_ice_connection_state_history();
4361
Steve Anton15324772018-01-16 10:26:49 -08004362 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004363 caller()->CreateAndSetAndSignalOffer();
4364 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4365
4366 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4367}
4368
deadbeef1dcb1642017-03-29 21:08:16 -07004369// This test sets up a call between two parties with audio and video. It then
4370// renegotiates setting the video m-line to "port 0", then later renegotiates
4371// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004372TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004373 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4374 ASSERT_TRUE(CreatePeerConnectionWrappers());
4375 ConnectFakeSignaling();
4376
4377 // Do initial negotiation, only sending media from the caller. Will result in
4378 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004379 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004380 caller()->CreateAndSetAndSignalOffer();
4381 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4382
4383 // Negotiate again, disabling the video "m=" section (the callee will set the
4384 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004385 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4386 PeerConnectionInterface::RTCOfferAnswerOptions options;
4387 options.offer_to_receive_video = 0;
4388 callee()->SetOfferAnswerOptions(options);
4389 } else {
4390 callee()->SetRemoteOfferHandler([this] {
Harald Alvestrand6060df52020-08-11 09:54:02 +02004391 callee()
4392 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
4393 ->StopInternal();
Seth Hampson2f0d7022018-02-20 11:54:42 -08004394 });
4395 }
deadbeef1dcb1642017-03-29 21:08:16 -07004396 caller()->CreateAndSetAndSignalOffer();
4397 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4398 // Sanity check that video "m=" section was actually rejected.
4399 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4400 callee()->pc()->local_description()->description());
4401 ASSERT_NE(nullptr, answer_video_content);
4402 ASSERT_TRUE(answer_video_content->rejected);
4403
4404 // Enable video and do negotiation again, making sure video is received
4405 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004406 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4407 PeerConnectionInterface::RTCOfferAnswerOptions options;
4408 options.offer_to_receive_video = 1;
4409 callee()->SetOfferAnswerOptions(options);
4410 } else {
4411 // The caller's transceiver is stopped, so we need to add another track.
4412 auto caller_transceiver =
4413 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
Harald Alvestrand6060df52020-08-11 09:54:02 +02004414 EXPECT_EQ(nullptr, caller_transceiver.get());
Seth Hampson2f0d7022018-02-20 11:54:42 -08004415 caller()->AddVideoTrack();
4416 }
4417 callee()->AddVideoTrack();
4418 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004419 caller()->CreateAndSetAndSignalOffer();
4420 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004421
deadbeef1dcb1642017-03-29 21:08:16 -07004422 // Verify the caller receives frames from the newly added stream, and the
4423 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004424 MediaExpectations media_expectations;
4425 media_expectations.CalleeExpectsSomeAudio();
4426 media_expectations.ExpectBidirectionalVideo();
4427 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004428}
4429
deadbeef1dcb1642017-03-29 21:08:16 -07004430// This tests that if we negotiate after calling CreateSender but before we
4431// have a track, then set a track later, frames from the newly-set track are
4432// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004433TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004434 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4435 ASSERT_TRUE(CreatePeerConnectionWrappers());
4436 ConnectFakeSignaling();
4437 auto caller_audio_sender =
4438 caller()->pc()->CreateSender("audio", "caller_stream");
4439 auto caller_video_sender =
4440 caller()->pc()->CreateSender("video", "caller_stream");
4441 auto callee_audio_sender =
4442 callee()->pc()->CreateSender("audio", "callee_stream");
4443 auto callee_video_sender =
4444 callee()->pc()->CreateSender("video", "callee_stream");
4445 caller()->CreateAndSetAndSignalOffer();
4446 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4447 // Wait for ICE to complete, without any tracks being set.
4448 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4449 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4450 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4451 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4452 // Now set the tracks, and expect frames to immediately start flowing.
4453 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4454 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4455 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4456 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004457 MediaExpectations media_expectations;
4458 media_expectations.ExpectBidirectionalAudioAndVideo();
4459 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4460}
4461
4462// This tests that if we negotiate after calling AddTransceiver but before we
4463// have a track, then set a track later, frames from the newly-set tracks are
4464// received end-to-end.
4465TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4466 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4467 ASSERT_TRUE(CreatePeerConnectionWrappers());
4468 ConnectFakeSignaling();
4469 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4470 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4471 auto caller_audio_sender = audio_result.MoveValue()->sender();
4472 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4473 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4474 auto caller_video_sender = video_result.MoveValue()->sender();
4475 callee()->SetRemoteOfferHandler([this] {
4476 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
Harald Alvestrand6060df52020-08-11 09:54:02 +02004477 callee()->pc()->GetTransceivers()[0]->SetDirectionWithError(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004478 RtpTransceiverDirection::kSendRecv);
Harald Alvestrand6060df52020-08-11 09:54:02 +02004479 callee()->pc()->GetTransceivers()[1]->SetDirectionWithError(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004480 RtpTransceiverDirection::kSendRecv);
4481 });
4482 caller()->CreateAndSetAndSignalOffer();
4483 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4484 // Wait for ICE to complete, without any tracks being set.
4485 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4486 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4487 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4488 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4489 // Now set the tracks, and expect frames to immediately start flowing.
4490 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4491 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4492 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4493 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4494 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4495 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4496 MediaExpectations media_expectations;
4497 media_expectations.ExpectBidirectionalAudioAndVideo();
4498 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004499}
4500
4501// This test verifies that a remote video track can be added via AddStream,
4502// and sent end-to-end. For this particular test, it's simply echoed back
4503// from the caller to the callee, rather than being forwarded to a third
4504// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004505TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004506 ASSERT_TRUE(CreatePeerConnectionWrappers());
4507 ConnectFakeSignaling();
4508 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004509 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004510 caller()->CreateAndSetAndSignalOffer();
4511 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004512 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004513
4514 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4515 // time).
4516 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4517 callee()->CreateAndSetAndSignalOffer();
4518 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4519
Seth Hampson2f0d7022018-02-20 11:54:42 -08004520 MediaExpectations media_expectations;
4521 media_expectations.ExpectBidirectionalVideo();
4522 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004523}
4524
4525// Test that we achieve the expected end-to-end connection time, using a
4526// fake clock and simulated latency on the media and signaling paths.
4527// We use a TURN<->TURN connection because this is usually the quickest to
4528// set up initially, especially when we're confident the connection will work
4529// and can start sending media before we get a STUN response.
4530//
4531// With various optimizations enabled, here are the network delays we expect to
4532// be on the critical path:
4533// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4534// signaling answer (with DTLS fingerprint).
4535// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4536// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4537// the first of which should have arrived before the answer.
Yves Gerey100fe632020-01-17 19:15:53 +01004538TEST_P(PeerConnectionIntegrationTestWithFakeClock,
4539 EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004540 static constexpr int media_hop_delay_ms = 50;
4541 static constexpr int signaling_trip_delay_ms = 500;
4542 // For explanation of these values, see comment above.
4543 static constexpr int required_media_hops = 9;
4544 static constexpr int required_signaling_trips = 2;
4545 // For internal delays (such as posting an event asychronously).
4546 static constexpr int allowed_internal_delay_ms = 20;
4547 static constexpr int total_connection_time_ms =
4548 media_hop_delay_ms * required_media_hops +
4549 signaling_trip_delay_ms * required_signaling_trips +
4550 allowed_internal_delay_ms;
4551
4552 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4553 3478};
4554 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4555 0};
4556 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4557 3478};
4558 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4559 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004560 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4561 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004562
Seth Hampsonaed71642018-06-11 07:41:32 -07004563 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4564 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004565 // Bypass permission check on received packets so media can be sent before
4566 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004567 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4568 turn_server_1->set_enable_permission_checks(false);
4569 });
4570 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4571 turn_server_2->set_enable_permission_checks(false);
4572 });
deadbeef1dcb1642017-03-29 21:08:16 -07004573
4574 PeerConnectionInterface::RTCConfiguration client_1_config;
4575 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4576 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4577 ice_server_1.username = "test";
4578 ice_server_1.password = "test";
4579 client_1_config.servers.push_back(ice_server_1);
4580 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4581 client_1_config.presume_writable_when_fully_relayed = true;
4582
4583 PeerConnectionInterface::RTCConfiguration client_2_config;
4584 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4585 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4586 ice_server_2.username = "test";
4587 ice_server_2.password = "test";
4588 client_2_config.servers.push_back(ice_server_2);
4589 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4590 client_2_config.presume_writable_when_fully_relayed = true;
4591
4592 ASSERT_TRUE(
4593 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4594 // Set up the simulated delays.
4595 SetSignalingDelayMs(signaling_trip_delay_ms);
4596 ConnectFakeSignaling();
4597 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4598 virtual_socket_server()->UpdateDelayDistribution();
4599
4600 // Set "offer to receive audio/video" without adding any tracks, so we just
4601 // set up ICE/DTLS with no media.
4602 PeerConnectionInterface::RTCOfferAnswerOptions options;
4603 options.offer_to_receive_audio = 1;
4604 options.offer_to_receive_video = 1;
4605 caller()->SetOfferAnswerOptions(options);
4606 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004607 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
Yves Gerey100fe632020-01-17 19:15:53 +01004608 FakeClock());
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004609 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4610 // If this is not done a DCHECK can be hit in ports.cc, because a large
4611 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07004612 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07004613}
4614
Jonas Orelandbdcee282017-10-10 14:01:40 +02004615// Verify that a TurnCustomizer passed in through RTCConfiguration
4616// is actually used by the underlying TURN candidate pair.
4617// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004618TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004619 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4620 3478};
4621 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4622 0};
4623 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4624 3478};
4625 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4626 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004627 CreateTurnServer(turn_server_1_internal_address,
4628 turn_server_1_external_address);
4629 CreateTurnServer(turn_server_2_internal_address,
4630 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004631
4632 PeerConnectionInterface::RTCConfiguration client_1_config;
4633 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4634 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4635 ice_server_1.username = "test";
4636 ice_server_1.password = "test";
4637 client_1_config.servers.push_back(ice_server_1);
4638 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004639 auto* customizer1 = CreateTurnCustomizer();
4640 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004641
4642 PeerConnectionInterface::RTCConfiguration client_2_config;
4643 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4644 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4645 ice_server_2.username = "test";
4646 ice_server_2.password = "test";
4647 client_2_config.servers.push_back(ice_server_2);
4648 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004649 auto* customizer2 = CreateTurnCustomizer();
4650 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004651
4652 ASSERT_TRUE(
4653 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4654 ConnectFakeSignaling();
4655
4656 // Set "offer to receive audio/video" without adding any tracks, so we just
4657 // set up ICE/DTLS with no media.
4658 PeerConnectionInterface::RTCOfferAnswerOptions options;
4659 options.offer_to_receive_audio = 1;
4660 options.offer_to_receive_video = 1;
4661 caller()->SetOfferAnswerOptions(options);
4662 caller()->CreateAndSetAndSignalOffer();
4663 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4664
Seth Hampsonaed71642018-06-11 07:41:32 -07004665 ExpectTurnCustomizerCountersIncremented(customizer1);
4666 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004667}
4668
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004669// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4670// send media between the caller and the callee.
4671TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4672 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4673 3478};
4674 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4675
4676 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004677 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4678 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004679
4680 webrtc::PeerConnectionInterface::IceServer ice_server;
4681 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4682 ice_server.username = "test";
4683 ice_server.password = "test";
4684
4685 PeerConnectionInterface::RTCConfiguration client_1_config;
4686 client_1_config.servers.push_back(ice_server);
4687 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4688
4689 PeerConnectionInterface::RTCConfiguration client_2_config;
4690 client_2_config.servers.push_back(ice_server);
4691 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4692
4693 ASSERT_TRUE(
4694 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4695
4696 // Do normal offer/answer and wait for ICE to complete.
4697 ConnectFakeSignaling();
4698 caller()->AddAudioVideoTracks();
4699 callee()->AddAudioVideoTracks();
4700 caller()->CreateAndSetAndSignalOffer();
4701 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4702 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4703 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4704
4705 MediaExpectations media_expectations;
4706 media_expectations.ExpectBidirectionalAudioAndVideo();
4707 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4708}
4709
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004710// Verify that a SSLCertificateVerifier passed in through
4711// PeerConnectionDependencies is actually used by the underlying SSL
4712// implementation to determine whether a certificate presented by the TURN
4713// server is accepted by the client. Note that openssladapter_unittest.cc
4714// contains more detailed, lower-level tests.
4715TEST_P(PeerConnectionIntegrationTest,
4716 SSLCertificateVerifierUsedForTurnConnections) {
4717 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4718 3478};
4719 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4720
4721 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4722 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004723 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4724 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004725
4726 webrtc::PeerConnectionInterface::IceServer ice_server;
4727 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4728 ice_server.username = "test";
4729 ice_server.password = "test";
4730
4731 PeerConnectionInterface::RTCConfiguration client_1_config;
4732 client_1_config.servers.push_back(ice_server);
4733 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4734
4735 PeerConnectionInterface::RTCConfiguration client_2_config;
4736 client_2_config.servers.push_back(ice_server);
4737 // Setting the type to kRelay forces the connection to go through a TURN
4738 // server.
4739 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4740
4741 // Get a copy to the pointer so we can verify calls later.
4742 rtc::TestCertificateVerifier* client_1_cert_verifier =
4743 new rtc::TestCertificateVerifier();
4744 client_1_cert_verifier->verify_certificate_ = true;
4745 rtc::TestCertificateVerifier* client_2_cert_verifier =
4746 new rtc::TestCertificateVerifier();
4747 client_2_cert_verifier->verify_certificate_ = true;
4748
4749 // Create the dependencies with the test certificate verifier.
4750 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4751 client_1_deps.tls_cert_verifier =
4752 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4753 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4754 client_2_deps.tls_cert_verifier =
4755 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4756
4757 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4758 client_1_config, std::move(client_1_deps), client_2_config,
4759 std::move(client_2_deps)));
4760 ConnectFakeSignaling();
4761
4762 // Set "offer to receive audio/video" without adding any tracks, so we just
4763 // set up ICE/DTLS with no media.
4764 PeerConnectionInterface::RTCOfferAnswerOptions options;
4765 options.offer_to_receive_audio = 1;
4766 options.offer_to_receive_video = 1;
4767 caller()->SetOfferAnswerOptions(options);
4768 caller()->CreateAndSetAndSignalOffer();
4769 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4770
4771 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4772 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004773}
4774
4775TEST_P(PeerConnectionIntegrationTest,
4776 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4777 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4778 3478};
4779 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4780
4781 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4782 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004783 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4784 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004785
4786 webrtc::PeerConnectionInterface::IceServer ice_server;
4787 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4788 ice_server.username = "test";
4789 ice_server.password = "test";
4790
4791 PeerConnectionInterface::RTCConfiguration client_1_config;
4792 client_1_config.servers.push_back(ice_server);
4793 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4794
4795 PeerConnectionInterface::RTCConfiguration client_2_config;
4796 client_2_config.servers.push_back(ice_server);
4797 // Setting the type to kRelay forces the connection to go through a TURN
4798 // server.
4799 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4800
4801 // Get a copy to the pointer so we can verify calls later.
4802 rtc::TestCertificateVerifier* client_1_cert_verifier =
4803 new rtc::TestCertificateVerifier();
4804 client_1_cert_verifier->verify_certificate_ = false;
4805 rtc::TestCertificateVerifier* client_2_cert_verifier =
4806 new rtc::TestCertificateVerifier();
4807 client_2_cert_verifier->verify_certificate_ = false;
4808
4809 // Create the dependencies with the test certificate verifier.
4810 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4811 client_1_deps.tls_cert_verifier =
4812 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4813 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4814 client_2_deps.tls_cert_verifier =
4815 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4816
4817 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4818 client_1_config, std::move(client_1_deps), client_2_config,
4819 std::move(client_2_deps)));
4820 ConnectFakeSignaling();
4821
4822 // Set "offer to receive audio/video" without adding any tracks, so we just
4823 // set up ICE/DTLS with no media.
4824 PeerConnectionInterface::RTCOfferAnswerOptions options;
4825 options.offer_to_receive_audio = 1;
4826 options.offer_to_receive_video = 1;
4827 caller()->SetOfferAnswerOptions(options);
4828 caller()->CreateAndSetAndSignalOffer();
4829 bool wait_res = true;
4830 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4831 // properly, should be able to just wait for a state of "failed" instead of
4832 // waiting a fixed 10 seconds.
4833 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4834 ASSERT_FALSE(wait_res);
4835
4836 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4837 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004838}
4839
Qingsi Wang25ec8882019-11-15 12:33:05 -08004840// Test that the injected ICE transport factory is used to create ICE transports
4841// for WebRTC connections.
4842TEST_P(PeerConnectionIntegrationTest, IceTransportFactoryUsedForConnections) {
4843 PeerConnectionInterface::RTCConfiguration default_config;
4844 PeerConnectionDependencies dependencies(nullptr);
4845 auto ice_transport_factory = std::make_unique<MockIceTransportFactory>();
4846 EXPECT_CALL(*ice_transport_factory, RecordIceTransportCreated()).Times(1);
4847 dependencies.ice_transport_factory = std::move(ice_transport_factory);
Niels Möller2a707032020-06-16 16:39:13 +02004848 auto wrapper = CreatePeerConnectionWrapper("Caller", nullptr, &default_config,
4849 std::move(dependencies), nullptr,
4850 /*reset_encoder_factory=*/false,
4851 /*reset_decoder_factory=*/false);
Qingsi Wang25ec8882019-11-15 12:33:05 -08004852 ASSERT_TRUE(wrapper);
4853 wrapper->CreateDataChannel();
4854 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
4855 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
4856 wrapper->pc()->SetLocalDescription(observer,
4857 wrapper->CreateOfferAndWait().release());
4858}
4859
deadbeefc964d0b2017-04-03 10:03:35 -07004860// Test that audio and video flow end-to-end when codec names don't use the
4861// expected casing, given that they're supposed to be case insensitive. To test
4862// this, all but one codec is removed from each media description, and its
4863// casing is changed.
4864//
4865// In the past, this has regressed and caused crashes/black video, due to the
4866// fact that code at some layers was doing case-insensitive comparisons and
4867// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004868TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004869 ASSERT_TRUE(CreatePeerConnectionWrappers());
4870 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004871 caller()->AddAudioVideoTracks();
4872 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004873
4874 // Remove all but one audio/video codec (opus and VP8), and change the
4875 // casing of the caller's generated offer.
4876 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4877 cricket::AudioContentDescription* audio =
4878 GetFirstAudioContentDescription(description);
4879 ASSERT_NE(nullptr, audio);
4880 auto audio_codecs = audio->codecs();
4881 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4882 [](const cricket::AudioCodec& codec) {
4883 return codec.name != "opus";
4884 }),
4885 audio_codecs.end());
4886 ASSERT_EQ(1u, audio_codecs.size());
4887 audio_codecs[0].name = "OpUs";
4888 audio->set_codecs(audio_codecs);
4889
4890 cricket::VideoContentDescription* video =
4891 GetFirstVideoContentDescription(description);
4892 ASSERT_NE(nullptr, video);
4893 auto video_codecs = video->codecs();
4894 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4895 [](const cricket::VideoCodec& codec) {
4896 return codec.name != "VP8";
4897 }),
4898 video_codecs.end());
4899 ASSERT_EQ(1u, video_codecs.size());
4900 video_codecs[0].name = "vP8";
4901 video->set_codecs(video_codecs);
4902 });
4903
4904 caller()->CreateAndSetAndSignalOffer();
4905 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4906
4907 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004908 MediaExpectations media_expectations;
4909 media_expectations.ExpectBidirectionalAudioAndVideo();
4910 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004911}
4912
Jonas Oreland49ac5952018-09-26 16:04:32 +02004913TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004914 ASSERT_TRUE(CreatePeerConnectionWrappers());
4915 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004916 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004917 caller()->CreateAndSetAndSignalOffer();
4918 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004919 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004920 MediaExpectations media_expectations;
4921 media_expectations.CalleeExpectsSomeAudio(1);
4922 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004923 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004924 auto receiver = callee()->pc()->GetReceivers()[0];
4925 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004926 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004927 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4928 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004929 sources[0].source_id());
4930 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4931}
4932
4933TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4934 ASSERT_TRUE(CreatePeerConnectionWrappers());
4935 ConnectFakeSignaling();
4936 caller()->AddVideoTrack();
4937 caller()->CreateAndSetAndSignalOffer();
4938 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4939 // Wait for one video frame to be received by the callee.
4940 MediaExpectations media_expectations;
4941 media_expectations.CalleeExpectsSomeVideo(1);
4942 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4943 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4944 auto receiver = callee()->pc()->GetReceivers()[0];
4945 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4946 auto sources = receiver->GetSources();
4947 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02004948 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004949 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4950 sources[0].source_id());
4951 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004952}
4953
deadbeef2f425aa2017-04-14 10:41:32 -07004954// Test that if a track is removed and added again with a different stream ID,
4955// the new stream ID is successfully communicated in SDP and media continues to
4956// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004957// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4958// it will not reuse a transceiver that has already been sending. After creating
4959// a new transceiver it tries to create an offer with two senders of the same
4960// track ids and it fails.
4961TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004962 ASSERT_TRUE(CreatePeerConnectionWrappers());
4963 ConnectFakeSignaling();
4964
deadbeef2f425aa2017-04-14 10:41:32 -07004965 // Add track using stream 1, do offer/answer.
4966 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4967 caller()->CreateLocalAudioTrack();
4968 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004969 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004970 caller()->CreateAndSetAndSignalOffer();
4971 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004972 {
4973 MediaExpectations media_expectations;
4974 media_expectations.CalleeExpectsSomeAudio(1);
4975 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4976 }
deadbeef2f425aa2017-04-14 10:41:32 -07004977 // Remove the sender, and create a new one with the new stream.
4978 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004979 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004980 caller()->CreateAndSetAndSignalOffer();
4981 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4982 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004983 {
4984 MediaExpectations media_expectations;
4985 media_expectations.CalleeExpectsSomeAudio();
4986 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4987 }
deadbeef2f425aa2017-04-14 10:41:32 -07004988}
4989
Seth Hampson2f0d7022018-02-20 11:54:42 -08004990TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004991 ASSERT_TRUE(CreatePeerConnectionWrappers());
4992 ConnectFakeSignaling();
4993
Mirko Bonadei317a1f02019-09-17 17:06:18 +02004994 auto output = std::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02004995 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
4996 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02004997 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004998 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4999 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02005000
Steve Anton15324772018-01-16 10:26:49 -08005001 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02005002 caller()->CreateAndSetAndSignalOffer();
5003 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5004}
5005
Steve Antonede9ca52017-10-16 13:04:27 -07005006// Test that if candidates are only signaled by applying full session
5007// descriptions (instead of using AddIceCandidate), the peers can connect to
5008// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005009TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07005010 ASSERT_TRUE(CreatePeerConnectionWrappers());
5011 // Each side will signal the session descriptions but not candidates.
5012 ConnectFakeSignalingForSdpOnly();
5013
5014 // Add audio video track and exchange the initial offer/answer with media
5015 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08005016 caller()->AddAudioVideoTracks();
5017 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07005018 caller()->CreateAndSetAndSignalOffer();
5019
5020 // Wait for all candidates to be gathered on both the caller and callee.
5021 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5022 caller()->ice_gathering_state(), kDefaultTimeout);
5023 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5024 callee()->ice_gathering_state(), kDefaultTimeout);
5025
5026 // The candidates will now be included in the session description, so
5027 // signaling them will start the ICE connection.
5028 caller()->CreateAndSetAndSignalOffer();
5029 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5030
5031 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005032 MediaExpectations media_expectations;
5033 media_expectations.ExpectBidirectionalAudioAndVideo();
5034 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07005035}
5036
henrika5f6bf242017-11-01 11:06:56 +01005037// Test that SetAudioPlayout can be used to disable audio playout from the
5038// start, then later enable it. This may be useful, for example, if the caller
5039// needs to play a local ringtone until some event occurs, after which it
5040// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005041TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01005042 ASSERT_TRUE(CreatePeerConnectionWrappers());
5043 ConnectFakeSignaling();
5044
5045 // Set up audio-only call where audio playout is disabled on caller's side.
5046 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08005047 caller()->AddAudioTrack();
5048 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005049 caller()->CreateAndSetAndSignalOffer();
5050 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5051
5052 // Pump messages for a second.
5053 WAIT(false, 1000);
5054 // Since audio playout is disabled, the caller shouldn't have received
5055 // anything (at the playout level, at least).
5056 EXPECT_EQ(0, caller()->audio_frames_received());
5057 // As a sanity check, make sure the callee (for which playout isn't disabled)
5058 // did still see frames on its audio level.
5059 ASSERT_GT(callee()->audio_frames_received(), 0);
5060
5061 // Enable playout again, and ensure audio starts flowing.
5062 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005063 MediaExpectations media_expectations;
5064 media_expectations.ExpectBidirectionalAudio();
5065 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01005066}
5067
5068double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5069 auto report = pc->NewGetStats();
5070 auto track_stats_list =
5071 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5072 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5073 for (const auto* track_stats : track_stats_list) {
5074 if (track_stats->remote_source.is_defined() &&
5075 *track_stats->remote_source) {
5076 remote_track_stats = track_stats;
5077 break;
5078 }
5079 }
5080
5081 if (!remote_track_stats->total_audio_energy.is_defined()) {
5082 return 0.0;
5083 }
5084 return *remote_track_stats->total_audio_energy;
5085}
5086
5087// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5088// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005089TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005090 DisableAudioPlayoutStillGeneratesAudioStats) {
5091 ASSERT_TRUE(CreatePeerConnectionWrappers());
5092 ConnectFakeSignaling();
5093
5094 // Set up audio-only call where playout is disabled but audio-processing is
5095 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005096 caller()->AddAudioTrack();
5097 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005098 caller()->pc()->SetAudioPlayout(false);
5099
5100 caller()->CreateAndSetAndSignalOffer();
5101 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5102
5103 // Wait for the callee to receive audio stats.
5104 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5105}
5106
henrika4f167df2017-11-01 14:45:55 +01005107// Test that SetAudioRecording can be used to disable audio recording from the
5108// start, then later enable it. This may be useful, for example, if the caller
5109// wants to ensure that no audio resources are active before a certain state
5110// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005111TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005112 ASSERT_TRUE(CreatePeerConnectionWrappers());
5113 ConnectFakeSignaling();
5114
5115 // Set up audio-only call where audio recording is disabled on caller's side.
5116 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005117 caller()->AddAudioTrack();
5118 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005119 caller()->CreateAndSetAndSignalOffer();
5120 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5121
5122 // Pump messages for a second.
5123 WAIT(false, 1000);
5124 // Since caller has disabled audio recording, the callee shouldn't have
5125 // received anything.
5126 EXPECT_EQ(0, callee()->audio_frames_received());
5127 // As a sanity check, make sure the caller did still see frames on its
5128 // audio level since audio recording is enabled on the calle side.
5129 ASSERT_GT(caller()->audio_frames_received(), 0);
5130
5131 // Enable audio recording again, and ensure audio starts flowing.
5132 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005133 MediaExpectations media_expectations;
5134 media_expectations.ExpectBidirectionalAudio();
5135 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005136}
5137
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005138// Test that after closing PeerConnections, they stop sending any packets (ICE,
5139// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005140TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005141 // Set up audio/video/data, wait for some frames to be received.
5142 ASSERT_TRUE(CreatePeerConnectionWrappers());
5143 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005144 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005145#ifdef HAVE_SCTP
5146 caller()->CreateDataChannel();
5147#endif
5148 caller()->CreateAndSetAndSignalOffer();
5149 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005150 MediaExpectations media_expectations;
5151 media_expectations.CalleeExpectsSomeAudioAndVideo();
5152 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005153 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005154 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005155 // Pump messages for a second, and ensure no new packets end up sent.
5156 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5157 WAIT(false, 1000);
5158 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5159 EXPECT_EQ(sent_packets_a, sent_packets_b);
5160}
5161
Steve Anton7eca0932018-03-30 15:18:41 -07005162// Test that transport stats are generated by the RTCStatsCollector for a
5163// connection that only involves data channels. This is a regression test for
5164// crbug.com/826972.
5165#ifdef HAVE_SCTP
5166TEST_P(PeerConnectionIntegrationTest,
5167 TransportStatsReportedForDataChannelOnlyConnection) {
5168 ASSERT_TRUE(CreatePeerConnectionWrappers());
5169 ConnectFakeSignaling();
5170 caller()->CreateDataChannel();
5171
5172 caller()->CreateAndSetAndSignalOffer();
5173 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5174 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5175
5176 auto caller_report = caller()->NewGetStats();
5177 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5178 auto callee_report = callee()->NewGetStats();
5179 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5180}
5181#endif // HAVE_SCTP
5182
Qingsi Wang7685e862018-06-11 20:15:46 -07005183TEST_P(PeerConnectionIntegrationTest,
5184 IceEventsGeneratedAndLoggedInRtcEventLog) {
5185 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5186 ConnectFakeSignaling();
5187 PeerConnectionInterface::RTCOfferAnswerOptions options;
5188 options.offer_to_receive_audio = 1;
5189 caller()->SetOfferAnswerOptions(options);
5190 caller()->CreateAndSetAndSignalOffer();
5191 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5192 ASSERT_NE(nullptr, caller()->event_log_factory());
5193 ASSERT_NE(nullptr, callee()->event_log_factory());
5194 webrtc::FakeRtcEventLog* caller_event_log =
5195 static_cast<webrtc::FakeRtcEventLog*>(
5196 caller()->event_log_factory()->last_log_created());
5197 webrtc::FakeRtcEventLog* callee_event_log =
5198 static_cast<webrtc::FakeRtcEventLog*>(
5199 callee()->event_log_factory()->last_log_created());
5200 ASSERT_NE(nullptr, caller_event_log);
5201 ASSERT_NE(nullptr, callee_event_log);
5202 int caller_ice_config_count = caller_event_log->GetEventCount(
5203 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5204 int caller_ice_event_count = caller_event_log->GetEventCount(
5205 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5206 int callee_ice_config_count = callee_event_log->GetEventCount(
5207 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5208 int callee_ice_event_count = callee_event_log->GetEventCount(
5209 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5210 EXPECT_LT(0, caller_ice_config_count);
5211 EXPECT_LT(0, caller_ice_event_count);
5212 EXPECT_LT(0, callee_ice_config_count);
5213 EXPECT_LT(0, callee_ice_event_count);
5214}
5215
Qingsi Wangc129c352019-04-18 10:41:58 -07005216TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005217 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5218 3478};
5219 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5220
5221 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5222
5223 webrtc::PeerConnectionInterface::IceServer ice_server;
5224 ice_server.urls.push_back("turn:88.88.88.0:3478");
5225 ice_server.username = "test";
5226 ice_server.password = "test";
5227
5228 PeerConnectionInterface::RTCConfiguration caller_config;
5229 caller_config.servers.push_back(ice_server);
5230 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5231 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005232 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005233
5234 PeerConnectionInterface::RTCConfiguration callee_config;
5235 callee_config.servers.push_back(ice_server);
5236 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5237 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005238 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005239
5240 ASSERT_TRUE(
5241 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5242
5243 // Do normal offer/answer and wait for ICE to complete.
5244 ConnectFakeSignaling();
5245 caller()->AddAudioVideoTracks();
5246 callee()->AddAudioVideoTracks();
5247 caller()->CreateAndSetAndSignalOffer();
5248 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5249 // Since we are doing continual gathering, the ICE transport does not reach
5250 // kIceGatheringComplete (see
5251 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5252 // kIceConnectionComplete.
5253 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5254 caller()->ice_connection_state(), kDefaultTimeout);
5255 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5256 callee()->ice_connection_state(), kDefaultTimeout);
5257 // Note that we cannot use the metric
5258 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5259 // metric is only populated when we reach kIceConnectionComplete in the
5260 // current implementation.
5261 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5262 caller()->last_candidate_gathered().type());
5263 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5264 callee()->last_candidate_gathered().type());
5265
5266 // Loosen the caller's candidate filter.
5267 caller_config = caller()->pc()->GetConfiguration();
5268 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5269 caller()->pc()->SetConfiguration(caller_config);
5270 // We should have gathered a new host candidate.
5271 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5272 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5273
5274 // Loosen the callee's candidate filter.
5275 callee_config = callee()->pc()->GetConfiguration();
5276 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5277 callee()->pc()->SetConfiguration(callee_config);
5278 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5279 callee()->last_candidate_gathered().type(), kDefaultTimeout);
Jonas Orelande3096512020-05-27 09:01:05 +02005280
5281 // Create an offer and verify that it does not contain an ICE restart (i.e new
5282 // ice credentials).
5283 std::string caller_ufrag_pre_offer = caller()
5284 ->pc()
5285 ->local_description()
5286 ->description()
5287 ->transport_infos()[0]
5288 .description.ice_ufrag;
5289 caller()->CreateAndSetAndSignalOffer();
5290 std::string caller_ufrag_post_offer = caller()
5291 ->pc()
5292 ->local_description()
5293 ->description()
5294 ->transport_infos()[0]
5295 .description.ice_ufrag;
5296 EXPECT_EQ(caller_ufrag_pre_offer, caller_ufrag_post_offer);
Qingsi Wangc129c352019-04-18 10:41:58 -07005297}
5298
Eldar Relloda13ea22019-06-01 12:23:43 +03005299TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03005300 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5301 3478};
5302 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5303
5304 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5305
5306 webrtc::PeerConnectionInterface::IceServer ice_server;
5307 ice_server.urls.push_back("turn:88.88.88.0:3478");
5308 ice_server.username = "test";
5309 ice_server.password = "123";
5310
5311 PeerConnectionInterface::RTCConfiguration caller_config;
5312 caller_config.servers.push_back(ice_server);
5313 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5314 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5315
5316 PeerConnectionInterface::RTCConfiguration callee_config;
5317 callee_config.servers.push_back(ice_server);
5318 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5319 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5320
5321 ASSERT_TRUE(
5322 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5323
5324 // Do normal offer/answer and wait for ICE to complete.
5325 ConnectFakeSignaling();
5326 caller()->AddAudioVideoTracks();
5327 callee()->AddAudioVideoTracks();
5328 caller()->CreateAndSetAndSignalOffer();
5329 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5330 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5331 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5332 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
Eldar Rello0095d372019-12-02 22:22:07 +02005333 EXPECT_NE(caller()->error_event().address, "");
Eldar Relloda13ea22019-06-01 12:23:43 +03005334}
5335
Eldar Rellofa8019c2020-05-14 11:59:33 +03005336TEST_P(PeerConnectionIntegrationTest, OnIceCandidateErrorWithEmptyAddress) {
5337 webrtc::PeerConnectionInterface::IceServer ice_server;
5338 ice_server.urls.push_back("turn:127.0.0.1:3478?transport=tcp");
5339 ice_server.username = "test";
5340 ice_server.password = "test";
5341
5342 PeerConnectionInterface::RTCConfiguration caller_config;
5343 caller_config.servers.push_back(ice_server);
5344 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5345 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5346
5347 PeerConnectionInterface::RTCConfiguration callee_config;
5348 callee_config.servers.push_back(ice_server);
5349 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5350 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5351
5352 ASSERT_TRUE(
5353 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5354
5355 // Do normal offer/answer and wait for ICE to complete.
5356 ConnectFakeSignaling();
5357 caller()->AddAudioVideoTracks();
5358 callee()->AddAudioVideoTracks();
5359 caller()->CreateAndSetAndSignalOffer();
5360 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5361 EXPECT_EQ_WAIT(701, caller()->error_event().error_code, kDefaultTimeout);
5362 EXPECT_EQ(caller()->error_event().address, "");
5363}
5364
Eldar Rello5ab79e62019-10-09 18:29:44 +03005365TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5366 AudioKeepsFlowingAfterImplicitRollback) {
5367 PeerConnectionInterface::RTCConfiguration config;
5368 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5369 config.enable_implicit_rollback = true;
5370 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5371 ConnectFakeSignaling();
5372 caller()->AddAudioTrack();
5373 callee()->AddAudioTrack();
5374 caller()->CreateAndSetAndSignalOffer();
5375 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5376 MediaExpectations media_expectations;
5377 media_expectations.ExpectBidirectionalAudio();
5378 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5379 SetSignalIceCandidates(false); // Workaround candidate outrace sdp.
5380 caller()->AddVideoTrack();
5381 callee()->AddVideoTrack();
5382 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
5383 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5384 callee()->pc()->SetLocalDescription(observer,
5385 callee()->CreateOfferAndWait().release());
5386 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
5387 caller()->CreateAndSetAndSignalOffer(); // Implicit rollback.
5388 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5389 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5390}
5391
5392TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5393 ImplicitRollbackVisitsStableState) {
5394 RTCConfiguration config;
5395 config.sdp_semantics = SdpSemantics::kUnifiedPlan;
5396 config.enable_implicit_rollback = true;
5397
5398 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5399
5400 rtc::scoped_refptr<MockSetSessionDescriptionObserver> sld_observer(
5401 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5402 callee()->pc()->SetLocalDescription(sld_observer,
5403 callee()->CreateOfferAndWait().release());
5404 EXPECT_TRUE_WAIT(sld_observer->called(), kDefaultTimeout);
5405 EXPECT_EQ(sld_observer->error(), "");
5406
5407 rtc::scoped_refptr<MockSetSessionDescriptionObserver> srd_observer(
5408 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
5409 callee()->pc()->SetRemoteDescription(
5410 srd_observer, caller()->CreateOfferAndWait().release());
5411 EXPECT_TRUE_WAIT(srd_observer->called(), kDefaultTimeout);
5412 EXPECT_EQ(srd_observer->error(), "");
5413
5414 EXPECT_THAT(callee()->peer_connection_signaling_state_history(),
5415 ElementsAre(PeerConnectionInterface::kHaveLocalOffer,
5416 PeerConnectionInterface::kStable,
5417 PeerConnectionInterface::kHaveRemoteOffer));
5418}
5419
Eldar Rellobd9c33a2020-10-01 17:52:45 +03005420TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5421 H264FmtpSpsPpsIdrInKeyframeParameterUsage) {
5422 ASSERT_TRUE(CreatePeerConnectionWrappers());
5423 ConnectFakeSignaling();
5424 caller()->AddVideoTrack();
5425 callee()->AddVideoTrack();
5426 auto munger = [](cricket::SessionDescription* desc) {
5427 cricket::VideoContentDescription* video =
5428 GetFirstVideoContentDescription(desc);
5429 auto codecs = video->codecs();
5430 for (auto&& codec : codecs) {
5431 if (codec.name == "H264") {
5432 std::string value;
5433 // The parameter is not supposed to be present in SDP by default.
5434 EXPECT_FALSE(
5435 codec.GetParam(cricket::kH264FmtpSpsPpsIdrInKeyframe, &value));
5436 codec.SetParam(std::string(cricket::kH264FmtpSpsPpsIdrInKeyframe),
5437 std::string(""));
5438 }
5439 }
5440 video->set_codecs(codecs);
5441 };
5442 // Munge local offer for SLD.
5443 caller()->SetGeneratedSdpMunger(munger);
5444 // Munge remote answer for SRD.
5445 caller()->SetReceivedSdpMunger(munger);
5446 caller()->CreateAndSetAndSignalOffer();
5447 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5448 // Observe that after munging the parameter is present in generated SDP.
5449 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* desc) {
5450 cricket::VideoContentDescription* video =
5451 GetFirstVideoContentDescription(desc);
5452 for (auto&& codec : video->codecs()) {
5453 if (codec.name == "H264") {
5454 std::string value;
5455 EXPECT_TRUE(
5456 codec.GetParam(cricket::kH264FmtpSpsPpsIdrInKeyframe, &value));
5457 }
5458 }
5459 });
5460 caller()->CreateOfferAndWait();
5461}
5462
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005463INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5464 PeerConnectionIntegrationTest,
5465 Values(SdpSemantics::kPlanB,
5466 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005467
Yves Gerey100fe632020-01-17 19:15:53 +01005468INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5469 PeerConnectionIntegrationTestWithFakeClock,
5470 Values(SdpSemantics::kPlanB,
5471 SdpSemantics::kUnifiedPlan));
5472
Steve Anton74255ff2018-01-24 18:32:57 -08005473// Tests that verify interoperability between Plan B and Unified Plan
5474// PeerConnections.
5475class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08005476 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08005477 public ::testing::WithParamInterface<
5478 std::tuple<SdpSemantics, SdpSemantics>> {
5479 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08005480 // Setting the SdpSemantics for the base test to kDefault does not matter
5481 // because we specify not to use the test semantics when creating
5482 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08005483 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07005484 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08005485 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08005486 callee_semantics_(std::get<1>(GetParam())) {}
5487
5488 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07005489 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5490 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08005491 }
5492
5493 const SdpSemantics caller_semantics_;
5494 const SdpSemantics callee_semantics_;
5495};
5496
5497TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5498 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5499 ConnectFakeSignaling();
5500
5501 caller()->CreateAndSetAndSignalOffer();
5502 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5503}
5504
5505TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
5506 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5507 ConnectFakeSignaling();
5508 auto audio_sender = caller()->AddAudioTrack();
5509
5510 caller()->CreateAndSetAndSignalOffer();
5511 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5512
5513 // Verify that one audio receiver has been created on the remote and that it
5514 // has the same track ID as the sending track.
5515 auto receivers = callee()->pc()->GetReceivers();
5516 ASSERT_EQ(1u, receivers.size());
5517 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
5518 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
5519
Seth Hampson2f0d7022018-02-20 11:54:42 -08005520 MediaExpectations media_expectations;
5521 media_expectations.CalleeExpectsSomeAudio();
5522 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005523}
5524
5525TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
5526 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5527 ConnectFakeSignaling();
5528 auto video_sender = caller()->AddVideoTrack();
5529 auto audio_sender = caller()->AddAudioTrack();
5530
5531 caller()->CreateAndSetAndSignalOffer();
5532 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5533
5534 // Verify that one audio and one video receiver have been created on the
5535 // remote and that they have the same track IDs as the sending tracks.
5536 auto audio_receivers =
5537 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5538 ASSERT_EQ(1u, audio_receivers.size());
5539 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5540 auto video_receivers =
5541 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5542 ASSERT_EQ(1u, video_receivers.size());
5543 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5544
Seth Hampson2f0d7022018-02-20 11:54:42 -08005545 MediaExpectations media_expectations;
5546 media_expectations.CalleeExpectsSomeAudioAndVideo();
5547 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005548}
5549
5550TEST_P(PeerConnectionIntegrationInteropTest,
5551 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5552 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5553 ConnectFakeSignaling();
5554 caller()->AddAudioVideoTracks();
5555 callee()->AddAudioVideoTracks();
5556
5557 caller()->CreateAndSetAndSignalOffer();
5558 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5559
Seth Hampson2f0d7022018-02-20 11:54:42 -08005560 MediaExpectations media_expectations;
5561 media_expectations.ExpectBidirectionalAudioAndVideo();
5562 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005563}
5564
5565TEST_P(PeerConnectionIntegrationInteropTest,
5566 ReverseRolesOneAudioLocalToOneVideoRemote) {
5567 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5568 ConnectFakeSignaling();
5569 caller()->AddAudioTrack();
5570 callee()->AddVideoTrack();
5571
5572 caller()->CreateAndSetAndSignalOffer();
5573 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5574
5575 // Verify that only the audio track has been negotiated.
5576 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5577 // Might also check that the callee's NegotiationNeeded flag is set.
5578
5579 // Reverse roles.
5580 callee()->CreateAndSetAndSignalOffer();
5581 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5582
Seth Hampson2f0d7022018-02-20 11:54:42 -08005583 MediaExpectations media_expectations;
5584 media_expectations.CallerExpectsSomeVideo();
5585 media_expectations.CalleeExpectsSomeAudio();
5586 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005587}
5588
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005589INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07005590 PeerConnectionIntegrationTest,
5591 PeerConnectionIntegrationInteropTest,
5592 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5593 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5594
5595// Test that if the Unified Plan side offers two video tracks then the Plan B
5596// side will only see the first one and ignore the second.
5597TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005598 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5599 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005600 ConnectFakeSignaling();
5601 auto first_sender = caller()->AddVideoTrack();
5602 caller()->AddVideoTrack();
5603
5604 caller()->CreateAndSetAndSignalOffer();
5605 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5606
5607 // Verify that there is only one receiver and it corresponds to the first
5608 // added track.
5609 auto receivers = callee()->pc()->GetReceivers();
5610 ASSERT_EQ(1u, receivers.size());
5611 EXPECT_TRUE(receivers[0]->track()->enabled());
5612 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5613
Seth Hampson2f0d7022018-02-20 11:54:42 -08005614 MediaExpectations media_expectations;
5615 media_expectations.CalleeExpectsSomeVideo();
5616 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005617}
5618
Steve Anton2bed3972019-01-04 17:04:30 -08005619// Test that if the initial offer tagged BUNDLE section is rejected due to its
5620// associated RtpTransceiver being stopped and another transceiver is added,
5621// then renegotiation causes the callee to receive the new video track without
5622// error.
5623// This is a regression test for bugs.webrtc.org/9954
5624TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5625 ReOfferWithStoppedBundleTaggedTransceiver) {
5626 RTCConfiguration config;
5627 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5628 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5629 ConnectFakeSignaling();
5630 auto audio_transceiver_or_error =
5631 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5632 ASSERT_TRUE(audio_transceiver_or_error.ok());
5633 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5634
5635 caller()->CreateAndSetAndSignalOffer();
5636 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5637 {
5638 MediaExpectations media_expectations;
5639 media_expectations.CalleeExpectsSomeAudio();
5640 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5641 }
5642
Harald Alvestrand6060df52020-08-11 09:54:02 +02005643 audio_transceiver->StopInternal();
Steve Anton2bed3972019-01-04 17:04:30 -08005644 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5645
5646 caller()->CreateAndSetAndSignalOffer();
5647 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5648 {
5649 MediaExpectations media_expectations;
5650 media_expectations.CalleeExpectsSomeVideo();
5651 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5652 }
5653}
5654
Harald Alvestrandbedb6052020-08-20 14:50:10 +02005655TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5656 StopTransceiverRemovesDtlsTransports) {
5657 RTCConfiguration config;
5658 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5659 ConnectFakeSignaling();
5660 auto audio_transceiver_or_error =
5661 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5662 ASSERT_TRUE(audio_transceiver_or_error.ok());
5663 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5664
5665 caller()->CreateAndSetAndSignalOffer();
5666 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5667
5668 audio_transceiver->StopStandard();
5669 caller()->CreateAndSetAndSignalOffer();
5670 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5671 ASSERT_EQ(0U, caller()->pc()->GetTransceivers().size());
5672 EXPECT_EQ(PeerConnectionInterface::kIceGatheringNew,
5673 caller()->pc()->ice_gathering_state());
5674 EXPECT_THAT(caller()->ice_gathering_state_history(),
5675 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
5676 PeerConnectionInterface::kIceGatheringComplete,
5677 PeerConnectionInterface::kIceGatheringNew));
5678}
5679
Harald Alvestrand1ee33252020-09-24 13:31:15 +00005680TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
Harald Alvestrand45be0a92020-09-30 06:55:23 +00005681 StopTransceiverStopsAndRemovesTransceivers) {
5682 RTCConfiguration config;
5683 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5684 ConnectFakeSignaling();
5685 auto audio_transceiver_or_error =
5686 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5687 ASSERT_TRUE(audio_transceiver_or_error.ok());
5688 auto caller_transceiver = audio_transceiver_or_error.MoveValue();
5689
5690 caller()->CreateAndSetAndSignalOffer();
5691 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5692 caller_transceiver->StopStandard();
5693
5694 auto callee_transceiver = callee()->pc()->GetTransceivers()[0];
5695 caller()->CreateAndSetAndSignalOffer();
5696 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5697 EXPECT_EQ(0U, caller()->pc()->GetTransceivers().size());
5698 EXPECT_EQ(0U, callee()->pc()->GetTransceivers().size());
5699 EXPECT_EQ(0U, caller()->pc()->GetSenders().size());
5700 EXPECT_EQ(0U, callee()->pc()->GetSenders().size());
5701 EXPECT_EQ(0U, caller()->pc()->GetReceivers().size());
5702 EXPECT_EQ(0U, callee()->pc()->GetReceivers().size());
5703 EXPECT_TRUE(caller_transceiver->stopped());
5704 EXPECT_TRUE(callee_transceiver->stopped());
5705}
5706
5707TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
Harald Alvestrand1ee33252020-09-24 13:31:15 +00005708 StopTransceiverEndsIncomingAudioTrack) {
5709 RTCConfiguration config;
5710 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5711 ConnectFakeSignaling();
5712 auto audio_transceiver_or_error =
5713 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5714 ASSERT_TRUE(audio_transceiver_or_error.ok());
5715 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5716
5717 caller()->CreateAndSetAndSignalOffer();
5718 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5719 auto caller_track = audio_transceiver->receiver()->track();
5720 auto callee_track = callee()->pc()->GetReceivers()[0]->track();
5721 audio_transceiver->StopStandard();
5722 EXPECT_EQ(MediaStreamTrackInterface::TrackState::kEnded,
5723 caller_track->state());
5724 caller()->CreateAndSetAndSignalOffer();
5725 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5726 EXPECT_EQ(MediaStreamTrackInterface::TrackState::kEnded,
5727 callee_track->state());
5728}
5729
5730TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5731 StopTransceiverEndsIncomingVideoTrack) {
5732 RTCConfiguration config;
5733 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5734 ConnectFakeSignaling();
5735 auto audio_transceiver_or_error =
5736 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5737 ASSERT_TRUE(audio_transceiver_or_error.ok());
5738 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5739
5740 caller()->CreateAndSetAndSignalOffer();
5741 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5742 auto caller_track = audio_transceiver->receiver()->track();
5743 auto callee_track = callee()->pc()->GetReceivers()[0]->track();
5744 audio_transceiver->StopStandard();
5745 EXPECT_EQ(MediaStreamTrackInterface::TrackState::kEnded,
5746 caller_track->state());
5747 caller()->CreateAndSetAndSignalOffer();
5748 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5749 EXPECT_EQ(MediaStreamTrackInterface::TrackState::kEnded,
5750 callee_track->state());
5751}
5752
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005753#ifdef HAVE_SCTP
5754
5755TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5756 EndToEndCallWithBundledSctpDataChannel) {
5757 ASSERT_TRUE(CreatePeerConnectionWrappers());
5758 ConnectFakeSignaling();
5759 caller()->CreateDataChannel();
5760 caller()->AddAudioVideoTracks();
5761 callee()->AddAudioVideoTracks();
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005762 caller()->CreateAndSetAndSignalOffer();
5763 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Harald Alvestrand17ea0682019-12-13 11:51:04 +01005764 ASSERT_EQ_WAIT(SctpTransportState::kConnected,
5765 caller()->pc()->GetSctpTransport()->Information().state(),
5766 kDefaultTimeout);
5767 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5768 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5769}
5770
5771TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5772 EndToEndCallWithDataChannelOnlyConnects) {
5773 ASSERT_TRUE(CreatePeerConnectionWrappers());
5774 ConnectFakeSignaling();
5775 caller()->CreateDataChannel();
5776 caller()->CreateAndSetAndSignalOffer();
5777 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5778 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5779 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5780 ASSERT_TRUE(caller()->data_observer()->IsOpen());
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005781}
5782
Harald Alvestrand2697ac12019-12-16 10:37:04 +01005783TEST_F(PeerConnectionIntegrationTestUnifiedPlan, DataChannelClosesWhenClosed) {
5784 ASSERT_TRUE(CreatePeerConnectionWrappers());
5785 ConnectFakeSignaling();
5786 caller()->CreateDataChannel();
5787 caller()->CreateAndSetAndSignalOffer();
5788 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5789 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
5790 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5791 caller()->data_channel()->Close();
5792 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
5793}
5794
5795TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5796 DataChannelClosesWhenClosedReverse) {
5797 ASSERT_TRUE(CreatePeerConnectionWrappers());
5798 ConnectFakeSignaling();
5799 caller()->CreateDataChannel();
5800 caller()->CreateAndSetAndSignalOffer();
5801 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5802 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
5803 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5804 callee()->data_channel()->Close();
5805 ASSERT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
5806}
5807
5808TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5809 DataChannelClosesWhenPeerConnectionClosed) {
5810 ASSERT_TRUE(CreatePeerConnectionWrappers());
5811 ConnectFakeSignaling();
5812 caller()->CreateDataChannel();
5813 caller()->CreateAndSetAndSignalOffer();
5814 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5815 ASSERT_TRUE_WAIT(callee()->data_observer(), kDefaultTimeout);
5816 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
5817 caller()->pc()->Close();
5818 ASSERT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
5819}
5820
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005821#endif // HAVE_SCTP
5822
deadbeef1dcb1642017-03-29 21:08:16 -07005823} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01005824} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07005825
5826#endif // if !defined(THREAD_SANITIZER)