blob: 2151b5ef18a30fcd02f41ae4fa8804b1719a7019 [file] [log] [blame]
deadbeef1dcb1642017-03-29 21:08:16 -07001/*
2 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11// Disable for TSan v2, see
12// https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
13#if !defined(THREAD_SANITIZER)
14
15#include <stdio.h>
16
deadbeef1dcb1642017-03-29 21:08:16 -070017#include <functional>
18#include <list>
19#include <map>
20#include <memory>
21#include <utility>
22#include <vector>
23
Steve Anton64b626b2019-01-28 17:25:26 -080024#include "absl/algorithm/container.h"
Qingsi Wang1dac6d82018-12-12 15:28:47 -080025#include "absl/memory/memory.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"
Bjorn Mellem175aa2e2018-11-08 11:23:22 -080032#include "api/test/loopback_media_transport.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"
Steve Anton10542f22019-01-11 09:11:00 -080040#include "p2p/base/mock_async_resolver.h"
41#include "p2p/base/p2p_constants.h"
42#include "p2p/base/port_interface.h"
43#include "p2p/base/test_stun_server.h"
44#include "p2p/base/test_turn_customizer.h"
45#include "p2p/base/test_turn_server.h"
46#include "p2p/client/basic_port_allocator.h"
47#include "pc/dtmf_sender.h"
48#include "pc/local_audio_source.h"
49#include "pc/media_session.h"
50#include "pc/peer_connection.h"
51#include "pc/peer_connection_factory.h"
52#include "pc/rtp_media_utils.h"
53#include "pc/session_description.h"
54#include "pc/test/fake_audio_capture_module.h"
55#include "pc/test/fake_periodic_video_track_source.h"
56#include "pc/test/fake_rtc_certificate_generator.h"
57#include "pc/test/fake_video_track_renderer.h"
58#include "pc/test/mock_peer_connection_observers.h"
Jonas Olssonb75d9e92019-02-22 10:33:29 +010059#include "rtc_base/fake_clock.h"
Qingsi Wangecd30542019-05-22 14:34:56 -070060#include "rtc_base/fake_mdns_responder.h"
Steve Anton10542f22019-01-11 09:11:00 -080061#include "rtc_base/fake_network.h"
62#include "rtc_base/firewall_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020063#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020064#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080065#include "rtc_base/test_certificate_verifier.h"
66#include "rtc_base/time_utils.h"
67#include "rtc_base/virtual_socket_server.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020068#include "system_wrappers/include/metrics.h"
Qingsi Wangc129c352019-04-18 10:41:58 -070069#include "test/field_trial.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020070#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070071
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010072namespace webrtc {
73namespace {
74
75using ::cricket::ContentInfo;
76using ::cricket::StreamParams;
77using ::rtc::SocketAddress;
78using ::testing::_;
Seth Hampson2f0d7022018-02-20 11:54:42 -080079using ::testing::Combine;
Steve Anton64b626b2019-01-28 17:25:26 -080080using ::testing::Contains;
Mirko Bonadeie46f5db2019-03-26 20:14:46 +010081using ::testing::DoAll;
Steve Antonede9ca52017-10-16 13:04:27 -070082using ::testing::ElementsAre;
Qingsi Wang1dac6d82018-12-12 15:28:47 -080083using ::testing::NiceMock;
Steve Anton64b626b2019-01-28 17:25:26 -080084using ::testing::Return;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070085using ::testing::SetArgPointee;
Steve Antonffa6ce42018-11-30 09:26:08 -080086using ::testing::UnorderedElementsAreArray;
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010087using ::testing::Values;
Steve Anton74255ff2018-01-24 18:32:57 -080088using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -070089
90static const int kDefaultTimeout = 10000;
91static const int kMaxWaitForStatsMs = 3000;
92static const int kMaxWaitForActivationMs = 5000;
93static const int kMaxWaitForFramesMs = 10000;
94// Default number of audio/video frames to wait for before considering a test
95// successful.
96static const int kDefaultExpectedAudioFrameCount = 3;
97static const int kDefaultExpectedVideoFrameCount = 3;
98
deadbeef1dcb1642017-03-29 21:08:16 -070099static const char kDataChannelLabel[] = "data_channel";
100
101// SRTP cipher name negotiated by the tests. This must be updated if the
102// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700103static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700104static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
105
Steve Antonede9ca52017-10-16 13:04:27 -0700106static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
107
deadbeef1dcb1642017-03-29 21:08:16 -0700108// Helper function for constructing offer/answer options to initiate an ICE
109// restart.
110PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
111 PeerConnectionInterface::RTCOfferAnswerOptions options;
112 options.ice_restart = true;
113 return options;
114}
115
deadbeefd8ad7882017-04-18 16:01:17 -0700116// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
117// attribute from received SDP, simulating a legacy endpoint.
118void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
119 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800120 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700121 }
122 desc->set_msid_supported(false);
Henrik Boström5b147782018-12-04 11:25:05 +0100123 desc->set_msid_signaling(0);
deadbeefd8ad7882017-04-18 16:01:17 -0700124}
125
Seth Hampson5897a6e2018-04-03 11:16:33 -0700126// Removes all stream information besides the stream ids, simulating an
127// endpoint that only signals a=msid lines to convey stream_ids.
128void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
129 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700130 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700131 std::vector<std::string> stream_ids;
132 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700133 const StreamParams& first_stream =
134 content.media_description()->streams()[0];
135 track_id = first_stream.id;
136 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700137 }
138 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700139 StreamParams new_stream;
140 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700141 new_stream.set_stream_ids(stream_ids);
142 content.media_description()->AddStream(new_stream);
143 }
144}
145
zhihuangf8164932017-05-19 13:09:47 -0700146int FindFirstMediaStatsIndexByKind(
147 const std::string& kind,
148 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
149 media_stats_vec) {
150 for (size_t i = 0; i < media_stats_vec.size(); i++) {
151 if (media_stats_vec[i]->kind.ValueToString() == kind) {
152 return i;
153 }
154 }
155 return -1;
156}
157
deadbeef1dcb1642017-03-29 21:08:16 -0700158class SignalingMessageReceiver {
159 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800160 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700161 virtual void ReceiveIceMessage(const std::string& sdp_mid,
162 int sdp_mline_index,
163 const std::string& msg) = 0;
164
165 protected:
166 SignalingMessageReceiver() {}
167 virtual ~SignalingMessageReceiver() {}
168};
169
170class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
171 public:
172 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
173 : expected_media_type_(media_type) {}
174
175 void OnFirstPacketReceived(cricket::MediaType media_type) override {
176 ASSERT_EQ(expected_media_type_, media_type);
177 first_packet_received_ = true;
178 }
179
180 bool first_packet_received() const { return first_packet_received_; }
181
182 virtual ~MockRtpReceiverObserver() {}
183
184 private:
185 bool first_packet_received_ = false;
186 cricket::MediaType expected_media_type_;
187};
188
189// Helper class that wraps a peer connection, observes it, and can accept
190// signaling messages from another wrapper.
191//
192// Uses a fake network, fake A/V capture, and optionally fake
193// encoders/decoders, though they aren't used by default since they don't
194// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700195// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800196// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700197class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800198 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700199 public:
200 // Different factory methods for convenience.
201 // TODO(deadbeef): Could use the pattern of:
202 //
203 // PeerConnectionWrapper =
204 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
205 //
206 // To reduce some code duplication.
207 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
208 const std::string& debug_name,
209 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
210 rtc::Thread* network_thread,
211 rtc::Thread* worker_thread) {
212 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700213 webrtc::PeerConnectionDependencies dependencies(nullptr);
214 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200215 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800216 worker_thread, nullptr,
217 /*media_transport_factory=*/nullptr)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700218 delete client;
219 return nullptr;
220 }
221 return client;
222 }
223
deadbeef2f425aa2017-04-14 10:41:32 -0700224 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
225 return peer_connection_factory_.get();
226 }
227
deadbeef1dcb1642017-03-29 21:08:16 -0700228 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
229
230 // If a signaling message receiver is set (via ConnectFakeSignaling), this
231 // will set the whole offer/answer exchange in motion. Just need to wait for
232 // the signaling state to reach "stable".
233 void CreateAndSetAndSignalOffer() {
234 auto offer = CreateOffer();
235 ASSERT_NE(nullptr, offer);
236 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
237 }
238
239 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
240 // when a remote offer is received (via fake signaling) and an answer is
241 // generated. By default, uses default options.
242 void SetOfferAnswerOptions(
243 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
244 offer_answer_options_ = options;
245 }
246
247 // Set a callback to be invoked when SDP is received via the fake signaling
248 // channel, which provides an opportunity to munge (modify) the SDP. This is
249 // used to test SDP being applied that a PeerConnection would normally not
250 // generate, but a non-JSEP endpoint might.
251 void SetReceivedSdpMunger(
252 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100253 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700254 }
255
deadbeefc964d0b2017-04-03 10:03:35 -0700256 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700257 // generated.
258 void SetGeneratedSdpMunger(
259 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100260 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700261 }
262
Seth Hampson2f0d7022018-02-20 11:54:42 -0800263 // Set a callback to be invoked when a remote offer is received via the fake
264 // signaling channel. This provides an opportunity to change the
265 // PeerConnection state before an answer is created and sent to the caller.
266 void SetRemoteOfferHandler(std::function<void()> handler) {
267 remote_offer_handler_ = std::move(handler);
268 }
269
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800270 void SetRemoteAsyncResolver(rtc::MockAsyncResolver* resolver) {
271 remote_async_resolver_ = resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700272 }
273
Steve Antonede9ca52017-10-16 13:04:27 -0700274 // Every ICE connection state in order that has been seen by the observer.
275 std::vector<PeerConnectionInterface::IceConnectionState>
276 ice_connection_state_history() const {
277 return ice_connection_state_history_;
278 }
Steve Anton6f25b092017-10-23 09:39:20 -0700279 void clear_ice_connection_state_history() {
280 ice_connection_state_history_.clear();
281 }
Steve Antonede9ca52017-10-16 13:04:27 -0700282
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100283 // Every standardized ICE connection state in order that has been seen by the
284 // observer.
285 std::vector<PeerConnectionInterface::IceConnectionState>
286 standardized_ice_connection_state_history() const {
287 return standardized_ice_connection_state_history_;
288 }
289
Jonas Olsson635474e2018-10-18 15:58:17 +0200290 // Every PeerConnection state in order that has been seen by the observer.
291 std::vector<PeerConnectionInterface::PeerConnectionState>
292 peer_connection_state_history() const {
293 return peer_connection_state_history_;
294 }
295
Steve Antonede9ca52017-10-16 13:04:27 -0700296 // Every ICE gathering state in order that has been seen by the observer.
297 std::vector<PeerConnectionInterface::IceGatheringState>
298 ice_gathering_state_history() const {
299 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700300 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700301 std::vector<cricket::CandidatePairChangeEvent>
302 ice_candidate_pair_change_history() const {
303 return ice_candidate_pair_change_history_;
304 }
deadbeef1dcb1642017-03-29 21:08:16 -0700305
Steve Anton15324772018-01-16 10:26:49 -0800306 void AddAudioVideoTracks() {
307 AddAudioTrack();
308 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700309 }
310
Steve Anton74255ff2018-01-24 18:32:57 -0800311 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
312 return AddTrack(CreateLocalAudioTrack());
313 }
deadbeef1dcb1642017-03-29 21:08:16 -0700314
Steve Anton74255ff2018-01-24 18:32:57 -0800315 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
316 return AddTrack(CreateLocalVideoTrack());
317 }
deadbeef1dcb1642017-03-29 21:08:16 -0700318
319 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200320 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700321 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200322 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700323 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200324 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700325 // TODO(perkj): Test audio source when it is implemented. Currently audio
326 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700327 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700328 source);
329 }
330
331 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200332 webrtc::FakePeriodicVideoSource::Config config;
333 config.timestamp_offset_ms = rtc::TimeMillis();
334 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700335 }
336
337 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200338 CreateLocalVideoTrackWithConfig(
339 webrtc::FakePeriodicVideoSource::Config config) {
340 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700341 }
342
343 rtc::scoped_refptr<webrtc::VideoTrackInterface>
344 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200345 webrtc::FakePeriodicVideoSource::Config config;
346 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200347 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200348 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700349 }
350
Steve Anton74255ff2018-01-24 18:32:57 -0800351 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
352 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800353 const std::vector<std::string>& stream_ids = {}) {
354 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800355 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800356 return result.MoveValue();
357 }
358
359 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
360 cricket::MediaType media_type) {
361 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +0100362 for (const auto& receiver : pc()->GetReceivers()) {
Steve Anton74255ff2018-01-24 18:32:57 -0800363 if (receiver->media_type() == media_type) {
364 receivers.push_back(receiver);
365 }
366 }
367 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700368 }
369
Seth Hampson2f0d7022018-02-20 11:54:42 -0800370 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
371 cricket::MediaType media_type) {
372 for (auto transceiver : pc()->GetTransceivers()) {
373 if (transceiver->receiver()->media_type() == media_type) {
374 return transceiver;
375 }
376 }
377 return nullptr;
378 }
379
deadbeef1dcb1642017-03-29 21:08:16 -0700380 bool SignalingStateStable() {
381 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
382 }
383
384 void CreateDataChannel() { CreateDataChannel(nullptr); }
385
386 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700387 CreateDataChannel(kDataChannelLabel, init);
388 }
389
390 void CreateDataChannel(const std::string& label,
391 const webrtc::DataChannelInit* init) {
392 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700393 ASSERT_TRUE(data_channel_.get() != nullptr);
394 data_observer_.reset(new MockDataChannelObserver(data_channel_));
395 }
396
397 DataChannelInterface* data_channel() { return data_channel_; }
398 const MockDataChannelObserver* data_observer() const {
399 return data_observer_.get();
400 }
401
402 int audio_frames_received() const {
403 return fake_audio_capture_module_->frames_received();
404 }
405
406 // Takes minimum of video frames received for each track.
407 //
408 // Can be used like:
409 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
410 //
411 // To ensure that all video tracks received at least a certain number of
412 // frames.
413 int min_video_frames_received_per_track() const {
414 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200415 if (fake_video_renderers_.empty()) {
416 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700417 }
deadbeef1dcb1642017-03-29 21:08:16 -0700418
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200419 for (const auto& pair : fake_video_renderers_) {
420 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700421 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200422 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700423 }
424
425 // Returns a MockStatsObserver in a state after stats gathering finished,
426 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700427 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700428 webrtc::MediaStreamTrackInterface* track) {
429 rtc::scoped_refptr<MockStatsObserver> observer(
430 new rtc::RefCountedObject<MockStatsObserver>());
431 EXPECT_TRUE(peer_connection_->GetStats(
432 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
433 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
434 return observer;
435 }
436
437 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700438 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
439 return OldGetStatsForTrack(nullptr);
440 }
441
442 // Synchronously gets stats and returns them. If it times out, fails the test
443 // and returns null.
444 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
445 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
446 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
447 peer_connection_->GetStats(callback);
448 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
449 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700450 }
451
452 int rendered_width() {
453 EXPECT_FALSE(fake_video_renderers_.empty());
454 return fake_video_renderers_.empty()
455 ? 0
456 : fake_video_renderers_.begin()->second->width();
457 }
458
459 int rendered_height() {
460 EXPECT_FALSE(fake_video_renderers_.empty());
461 return fake_video_renderers_.empty()
462 ? 0
463 : fake_video_renderers_.begin()->second->height();
464 }
465
466 double rendered_aspect_ratio() {
467 if (rendered_height() == 0) {
468 return 0.0;
469 }
470 return static_cast<double>(rendered_width()) / rendered_height();
471 }
472
473 webrtc::VideoRotation rendered_rotation() {
474 EXPECT_FALSE(fake_video_renderers_.empty());
475 return fake_video_renderers_.empty()
476 ? webrtc::kVideoRotation_0
477 : fake_video_renderers_.begin()->second->rotation();
478 }
479
480 int local_rendered_width() {
481 return local_video_renderer_ ? local_video_renderer_->width() : 0;
482 }
483
484 int local_rendered_height() {
485 return local_video_renderer_ ? local_video_renderer_->height() : 0;
486 }
487
488 double local_rendered_aspect_ratio() {
489 if (local_rendered_height() == 0) {
490 return 0.0;
491 }
492 return static_cast<double>(local_rendered_width()) /
493 local_rendered_height();
494 }
495
496 size_t number_of_remote_streams() {
497 if (!pc()) {
498 return 0;
499 }
500 return pc()->remote_streams()->count();
501 }
502
503 StreamCollectionInterface* remote_streams() const {
504 if (!pc()) {
505 ADD_FAILURE();
506 return nullptr;
507 }
508 return pc()->remote_streams();
509 }
510
511 StreamCollectionInterface* local_streams() {
512 if (!pc()) {
513 ADD_FAILURE();
514 return nullptr;
515 }
516 return pc()->local_streams();
517 }
518
519 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
520 return pc()->signaling_state();
521 }
522
523 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
524 return pc()->ice_connection_state();
525 }
526
Jonas Olsson7a6739e2019-01-15 16:31:55 +0100527 webrtc::PeerConnectionInterface::IceConnectionState
528 standardized_ice_connection_state() {
529 return pc()->standardized_ice_connection_state();
530 }
531
deadbeef1dcb1642017-03-29 21:08:16 -0700532 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
533 return pc()->ice_gathering_state();
534 }
535
536 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
537 // GetReceivers. They're updated automatically when a remote offer/answer
538 // from the fake signaling channel is applied, or when
539 // ResetRtpReceiverObservers below is called.
540 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
541 rtp_receiver_observers() {
542 return rtp_receiver_observers_;
543 }
544
545 void ResetRtpReceiverObservers() {
546 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100547 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
548 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700549 std::unique_ptr<MockRtpReceiverObserver> observer(
550 new MockRtpReceiverObserver(receiver->media_type()));
551 receiver->SetObserver(observer.get());
552 rtp_receiver_observers_.push_back(std::move(observer));
553 }
554 }
555
Qingsi Wangecd30542019-05-22 14:34:56 -0700556 rtc::FakeNetworkManager* network_manager() const {
Steve Antonede9ca52017-10-16 13:04:27 -0700557 return fake_network_manager_.get();
558 }
559 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
560
Qingsi Wang7685e862018-06-11 20:15:46 -0700561 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
562 return event_log_factory_;
563 }
564
Qingsi Wangc129c352019-04-18 10:41:58 -0700565 const cricket::Candidate& last_candidate_gathered() const {
566 return last_candidate_gathered_;
567 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300568 const cricket::IceCandidateErrorEvent& error_event() const {
569 return error_event_;
570 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700571
Qingsi Wangecd30542019-05-22 14:34:56 -0700572 // Sets the mDNS responder for the owned fake network manager and keeps a
573 // reference to the responder.
574 void SetMdnsResponder(
575 std::unique_ptr<webrtc::FakeMdnsResponder> mdns_responder) {
576 RTC_DCHECK(mdns_responder != nullptr);
577 mdns_responder_ = mdns_responder.get();
578 network_manager()->set_mdns_responder(std::move(mdns_responder));
579 }
580
deadbeef1dcb1642017-03-29 21:08:16 -0700581 private:
582 explicit PeerConnectionWrapper(const std::string& debug_name)
583 : debug_name_(debug_name) {}
584
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800585 bool Init(
586 const PeerConnectionFactory::Options* options,
587 const PeerConnectionInterface::RTCConfiguration* config,
588 webrtc::PeerConnectionDependencies dependencies,
589 rtc::Thread* network_thread,
590 rtc::Thread* worker_thread,
591 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
592 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700593 // There's an error in this test code if Init ends up being called twice.
594 RTC_DCHECK(!peer_connection_);
595 RTC_DCHECK(!peer_connection_factory_);
596
597 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700598 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700599
600 std::unique_ptr<cricket::PortAllocator> port_allocator(
601 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700602 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700603 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
604 if (!fake_audio_capture_module_) {
605 return false;
606 }
deadbeef1dcb1642017-03-29 21:08:16 -0700607 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700608
609 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
610 pc_factory_dependencies.network_thread = network_thread;
611 pc_factory_dependencies.worker_thread = worker_thread;
612 pc_factory_dependencies.signaling_thread = signaling_thread;
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200613 pc_factory_dependencies.task_queue_factory =
614 webrtc::CreateDefaultTaskQueueFactory();
615 cricket::MediaEngineDependencies media_deps;
616 media_deps.task_queue_factory =
617 pc_factory_dependencies.task_queue_factory.get();
618 media_deps.adm = fake_audio_capture_module_;
619 webrtc::SetMediaEngineDefaults(&media_deps);
Qingsi Wang7685e862018-06-11 20:15:46 -0700620 pc_factory_dependencies.media_engine =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200621 cricket::CreateMediaEngine(std::move(media_deps));
Qingsi Wang7685e862018-06-11 20:15:46 -0700622 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
623 if (event_log_factory) {
624 event_log_factory_ = event_log_factory.get();
625 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
626 } else {
627 pc_factory_dependencies.event_log_factory =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200628 absl::make_unique<webrtc::RtcEventLogFactory>(
629 pc_factory_dependencies.task_queue_factory.get());
Qingsi Wang7685e862018-06-11 20:15:46 -0700630 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800631 if (media_transport_factory) {
632 pc_factory_dependencies.media_transport_factory =
633 std::move(media_transport_factory);
634 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700635 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
636 std::move(pc_factory_dependencies));
637
deadbeef1dcb1642017-03-29 21:08:16 -0700638 if (!peer_connection_factory_) {
639 return false;
640 }
641 if (options) {
642 peer_connection_factory_->SetOptions(*options);
643 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800644 if (config) {
645 sdp_semantics_ = config->sdp_semantics;
646 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700647
648 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200649 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700650 return peer_connection_.get() != nullptr;
651 }
652
653 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700654 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700655 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700656 PeerConnectionInterface::RTCConfiguration modified_config;
657 // If |config| is null, this will result in a default configuration being
658 // used.
659 if (config) {
660 modified_config = *config;
661 }
662 // Disable resolution adaptation; we don't want it interfering with the
663 // test results.
664 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
665 // ratios and not specific resolutions, is this even necessary?
666 modified_config.set_cpu_adaptation(false);
667
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700668 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700669 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700670 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700671 }
672
673 void set_signaling_message_receiver(
674 SignalingMessageReceiver* signaling_message_receiver) {
675 signaling_message_receiver_ = signaling_message_receiver;
676 }
677
678 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
679
Steve Antonede9ca52017-10-16 13:04:27 -0700680 void set_signal_ice_candidates(bool signal) {
681 signal_ice_candidates_ = signal;
682 }
683
deadbeef1dcb1642017-03-29 21:08:16 -0700684 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200685 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700686 // Set max frame rate to 10fps to reduce the risk of test flakiness.
687 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200688 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700689
Niels Möller5c7efe72018-05-11 10:34:46 +0200690 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200691 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
692 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700693 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200694 peer_connection_factory_->CreateVideoTrack(
695 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700696 if (!local_video_renderer_) {
697 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
698 }
699 return track;
700 }
701
702 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100703 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800704 std::unique_ptr<SessionDescriptionInterface> desc =
705 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700706 if (received_sdp_munger_) {
707 received_sdp_munger_(desc->description());
708 }
709
710 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
711 // Setting a remote description may have changed the number of receivers,
712 // so reset the receiver observers.
713 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800714 if (remote_offer_handler_) {
715 remote_offer_handler_();
716 }
deadbeef1dcb1642017-03-29 21:08:16 -0700717 auto answer = CreateAnswer();
718 ASSERT_NE(nullptr, answer);
719 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
720 }
721
722 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100723 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800724 std::unique_ptr<SessionDescriptionInterface> desc =
725 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700726 if (received_sdp_munger_) {
727 received_sdp_munger_(desc->description());
728 }
729
730 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
731 // Set the RtpReceiverObserver after receivers are created.
732 ResetRtpReceiverObservers();
733 }
734
735 // Returns null on failure.
736 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
737 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
738 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
739 pc()->CreateOffer(observer, offer_answer_options_);
740 return WaitForDescriptionFromObserver(observer);
741 }
742
743 // Returns null on failure.
744 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
745 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
746 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
747 pc()->CreateAnswer(observer, offer_answer_options_);
748 return WaitForDescriptionFromObserver(observer);
749 }
750
751 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100752 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700753 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
754 if (!observer->result()) {
755 return nullptr;
756 }
757 auto description = observer->MoveDescription();
758 if (generated_sdp_munger_) {
759 generated_sdp_munger_(description->description());
760 }
761 return description;
762 }
763
764 // Setting the local description and sending the SDP message over the fake
765 // signaling channel are combined into the same method because the SDP
766 // message needs to be sent as soon as SetLocalDescription finishes, without
767 // waiting for the observer to be called. This ensures that ICE candidates
768 // don't outrace the description.
769 bool SetLocalDescriptionAndSendSdpMessage(
770 std::unique_ptr<SessionDescriptionInterface> desc) {
771 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
772 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100773 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800774 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700775 std::string sdp;
776 EXPECT_TRUE(desc->ToString(&sdp));
Bjorn A Mellemb689af42019-08-21 10:44:59 -0700777 RTC_LOG(LS_INFO) << debug_name_ << ": local SDP contents=\n" << sdp;
deadbeef1dcb1642017-03-29 21:08:16 -0700778 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800779 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
780 RemoveUnusedVideoRenderers();
781 }
deadbeef1dcb1642017-03-29 21:08:16 -0700782 // As mentioned above, we need to send the message immediately after
783 // SetLocalDescription.
784 SendSdpMessage(type, sdp);
785 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
786 return true;
787 }
788
789 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
790 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
791 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100792 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700793 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800794 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
795 RemoveUnusedVideoRenderers();
796 }
deadbeef1dcb1642017-03-29 21:08:16 -0700797 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
798 return observer->result();
799 }
800
Seth Hampson2f0d7022018-02-20 11:54:42 -0800801 // This is a work around to remove unused fake_video_renderers from
802 // transceivers that have either stopped or are no longer receiving.
803 void RemoveUnusedVideoRenderers() {
804 auto transceivers = pc()->GetTransceivers();
805 for (auto& transceiver : transceivers) {
806 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
807 continue;
808 }
809 // Remove fake video renderers from any stopped transceivers.
810 if (transceiver->stopped()) {
811 auto it =
812 fake_video_renderers_.find(transceiver->receiver()->track()->id());
813 if (it != fake_video_renderers_.end()) {
814 fake_video_renderers_.erase(it);
815 }
816 }
817 // Remove fake video renderers from any transceivers that are no longer
818 // receiving.
819 if ((transceiver->current_direction() &&
820 !webrtc::RtpTransceiverDirectionHasRecv(
821 *transceiver->current_direction()))) {
822 auto it =
823 fake_video_renderers_.find(transceiver->receiver()->track()->id());
824 if (it != fake_video_renderers_.end()) {
825 fake_video_renderers_.erase(it);
826 }
827 }
828 }
829 }
830
deadbeef1dcb1642017-03-29 21:08:16 -0700831 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
832 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800833 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700834 if (signaling_delay_ms_ == 0) {
835 RelaySdpMessageIfReceiverExists(type, msg);
836 } else {
837 invoker_.AsyncInvokeDelayed<void>(
838 RTC_FROM_HERE, rtc::Thread::Current(),
839 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
840 this, type, msg),
841 signaling_delay_ms_);
842 }
843 }
844
Steve Antona3a92c22017-12-07 10:27:41 -0800845 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700846 if (signaling_message_receiver_) {
847 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
848 }
849 }
850
851 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
852 // default).
853 void SendIceMessage(const std::string& sdp_mid,
854 int sdp_mline_index,
855 const std::string& msg) {
856 if (signaling_delay_ms_ == 0) {
857 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
858 } else {
859 invoker_.AsyncInvokeDelayed<void>(
860 RTC_FROM_HERE, rtc::Thread::Current(),
861 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
862 this, sdp_mid, sdp_mline_index, msg),
863 signaling_delay_ms_);
864 }
865 }
866
867 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
868 int sdp_mline_index,
869 const std::string& msg) {
870 if (signaling_message_receiver_) {
871 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
872 msg);
873 }
874 }
875
876 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800877 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
878 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700879 HandleIncomingOffer(msg);
880 } else {
881 HandleIncomingAnswer(msg);
882 }
883 }
884
885 void ReceiveIceMessage(const std::string& sdp_mid,
886 int sdp_mline_index,
887 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100888 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700889 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
890 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
891 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
892 }
893
894 // PeerConnectionObserver callbacks.
895 void OnSignalingChange(
896 webrtc::PeerConnectionInterface::SignalingState new_state) override {
897 EXPECT_EQ(pc()->signaling_state(), new_state);
898 }
Steve Anton15324772018-01-16 10:26:49 -0800899 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
900 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
901 streams) override {
902 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
903 rtc::scoped_refptr<VideoTrackInterface> video_track(
904 static_cast<VideoTrackInterface*>(receiver->track().get()));
905 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700906 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800907 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200908 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700909 }
910 }
Steve Anton15324772018-01-16 10:26:49 -0800911 void OnRemoveTrack(
912 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
913 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
914 auto it = fake_video_renderers_.find(receiver->track()->id());
915 RTC_DCHECK(it != fake_video_renderers_.end());
916 fake_video_renderers_.erase(it);
917 }
918 }
deadbeef1dcb1642017-03-29 21:08:16 -0700919 void OnRenegotiationNeeded() override {}
920 void OnIceConnectionChange(
921 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
922 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700923 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700924 }
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100925 void OnStandardizedIceConnectionChange(
926 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
927 standardized_ice_connection_state_history_.push_back(new_state);
928 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200929 void OnConnectionChange(
930 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
931 peer_connection_state_history_.push_back(new_state);
932 }
933
deadbeef1dcb1642017-03-29 21:08:16 -0700934 void OnIceGatheringChange(
935 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700936 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700937 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700938 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700939
940 void OnIceSelectedCandidatePairChanged(
941 const cricket::CandidatePairChangeEvent& event) {
942 ice_candidate_pair_change_history_.push_back(event);
943 }
Alex Drake43faee02019-08-12 16:27:34 -0700944
deadbeef1dcb1642017-03-29 21:08:16 -0700945 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100946 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700947
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800948 if (remote_async_resolver_) {
949 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800950 if (local_candidate.address().IsUnresolvedIP()) {
951 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
952 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700953 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800954 local_candidate.address().hostname());
955 RTC_DCHECK(!resolved_ip.IsNil());
956 resolved_addr.SetResolvedIP(resolved_ip);
957 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
958 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
959 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700960 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700961 }
962
deadbeef1dcb1642017-03-29 21:08:16 -0700963 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800964 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700965 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700966 // Remote party may be deleted.
967 return;
968 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800969 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700970 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700971 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300972 void OnIceCandidateError(const std::string& host_candidate,
973 const std::string& url,
974 int error_code,
975 const std::string& error_text) override {
976 error_event_ = cricket::IceCandidateErrorEvent(host_candidate, url,
977 error_code, error_text);
978 }
deadbeef1dcb1642017-03-29 21:08:16 -0700979 void OnDataChannel(
980 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100981 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700982 data_channel_ = data_channel;
983 data_observer_.reset(new MockDataChannelObserver(data_channel));
984 }
985
deadbeef1dcb1642017-03-29 21:08:16 -0700986 std::string debug_name_;
987
988 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -0700989 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
990 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -0700991
992 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
993 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
994 peer_connection_factory_;
995
Steve Antonede9ca52017-10-16 13:04:27 -0700996 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700997 // Needed to keep track of number of frames sent.
998 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
999 // Needed to keep track of number of frames received.
1000 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1001 fake_video_renderers_;
1002 // Needed to ensure frames aren't received for removed tracks.
1003 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1004 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001005
1006 // For remote peer communication.
1007 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1008 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001009 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001010 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001011 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001012
Niels Möller5c7efe72018-05-11 10:34:46 +02001013 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001014 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001015 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1016 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001017 // |local_video_renderer_| attached to the first created local video track.
1018 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1019
Seth Hampson2f0d7022018-02-20 11:54:42 -08001020 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001021 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1022 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1023 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001024 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001025 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001026 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1027 std::unique_ptr<MockDataChannelObserver> data_observer_;
1028
1029 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1030
Steve Antonede9ca52017-10-16 13:04:27 -07001031 std::vector<PeerConnectionInterface::IceConnectionState>
1032 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001033 std::vector<PeerConnectionInterface::IceConnectionState>
1034 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001035 std::vector<PeerConnectionInterface::PeerConnectionState>
1036 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001037 std::vector<PeerConnectionInterface::IceGatheringState>
1038 ice_gathering_state_history_;
Alex Drake00c7ecf2019-08-06 10:54:47 -07001039 std::vector<cricket::CandidatePairChangeEvent>
1040 ice_candidate_pair_change_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001041
Qingsi Wang7685e862018-06-11 20:15:46 -07001042 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1043
deadbeef1dcb1642017-03-29 21:08:16 -07001044 rtc::AsyncInvoker invoker_;
1045
Seth Hampson2f0d7022018-02-20 11:54:42 -08001046 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001047};
1048
Elad Alon99c3fe52017-10-13 16:29:40 +02001049class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1050 public:
1051 virtual ~MockRtcEventLogOutput() = default;
1052 MOCK_CONST_METHOD0(IsActive, bool());
1053 MOCK_METHOD1(Write, bool(const std::string&));
1054};
1055
Seth Hampson2f0d7022018-02-20 11:54:42 -08001056// This helper object is used for both specifying how many audio/video frames
1057// are expected to be received for a caller/callee. It provides helper functions
1058// to specify these expectations. The object initially starts in a state of no
1059// expectations.
1060class MediaExpectations {
1061 public:
1062 enum ExpectFrames {
1063 kExpectSomeFrames,
1064 kExpectNoFrames,
1065 kNoExpectation,
1066 };
1067
1068 void ExpectBidirectionalAudioAndVideo() {
1069 ExpectBidirectionalAudio();
1070 ExpectBidirectionalVideo();
1071 }
1072
1073 void ExpectBidirectionalAudio() {
1074 CallerExpectsSomeAudio();
1075 CalleeExpectsSomeAudio();
1076 }
1077
1078 void ExpectNoAudio() {
1079 CallerExpectsNoAudio();
1080 CalleeExpectsNoAudio();
1081 }
1082
1083 void ExpectBidirectionalVideo() {
1084 CallerExpectsSomeVideo();
1085 CalleeExpectsSomeVideo();
1086 }
1087
1088 void ExpectNoVideo() {
1089 CallerExpectsNoVideo();
1090 CalleeExpectsNoVideo();
1091 }
1092
1093 void CallerExpectsSomeAudioAndVideo() {
1094 CallerExpectsSomeAudio();
1095 CallerExpectsSomeVideo();
1096 }
1097
1098 void CalleeExpectsSomeAudioAndVideo() {
1099 CalleeExpectsSomeAudio();
1100 CalleeExpectsSomeVideo();
1101 }
1102
1103 // Caller's audio functions.
1104 void CallerExpectsSomeAudio(
1105 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1106 caller_audio_expectation_ = kExpectSomeFrames;
1107 caller_audio_frames_expected_ = expected_audio_frames;
1108 }
1109
1110 void CallerExpectsNoAudio() {
1111 caller_audio_expectation_ = kExpectNoFrames;
1112 caller_audio_frames_expected_ = 0;
1113 }
1114
1115 // Caller's video functions.
1116 void CallerExpectsSomeVideo(
1117 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1118 caller_video_expectation_ = kExpectSomeFrames;
1119 caller_video_frames_expected_ = expected_video_frames;
1120 }
1121
1122 void CallerExpectsNoVideo() {
1123 caller_video_expectation_ = kExpectNoFrames;
1124 caller_video_frames_expected_ = 0;
1125 }
1126
1127 // Callee's audio functions.
1128 void CalleeExpectsSomeAudio(
1129 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1130 callee_audio_expectation_ = kExpectSomeFrames;
1131 callee_audio_frames_expected_ = expected_audio_frames;
1132 }
1133
1134 void CalleeExpectsNoAudio() {
1135 callee_audio_expectation_ = kExpectNoFrames;
1136 callee_audio_frames_expected_ = 0;
1137 }
1138
1139 // Callee's video functions.
1140 void CalleeExpectsSomeVideo(
1141 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1142 callee_video_expectation_ = kExpectSomeFrames;
1143 callee_video_frames_expected_ = expected_video_frames;
1144 }
1145
1146 void CalleeExpectsNoVideo() {
1147 callee_video_expectation_ = kExpectNoFrames;
1148 callee_video_frames_expected_ = 0;
1149 }
1150
1151 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1152 ExpectFrames caller_video_expectation_ = kNoExpectation;
1153 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1154 ExpectFrames callee_video_expectation_ = kNoExpectation;
1155 int caller_audio_frames_expected_ = 0;
1156 int caller_video_frames_expected_ = 0;
1157 int callee_audio_frames_expected_ = 0;
1158 int callee_video_frames_expected_ = 0;
1159};
1160
deadbeef1dcb1642017-03-29 21:08:16 -07001161// Tests two PeerConnections connecting to each other end-to-end, using a
1162// virtual network, fake A/V capture and fake encoder/decoders. The
1163// PeerConnections share the threads/socket servers, but use separate versions
1164// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001165class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001166 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001167 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1168 : sdp_semantics_(sdp_semantics),
1169 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001170 fss_(new rtc::FirewallSocketServer(ss_.get())),
1171 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001172 worker_thread_(rtc::Thread::Create()),
1173 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001174 network_thread_->SetName("PCNetworkThread", this);
1175 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001176 RTC_CHECK(network_thread_->Start());
1177 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001178 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001179 }
1180
Seth Hampson2f0d7022018-02-20 11:54:42 -08001181 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001182 // The PeerConnections should deleted before the TurnCustomizers.
1183 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1184 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1185 // that the TurnCustomizer outlives the life of the PeerConnection or else
1186 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001187 if (caller_) {
1188 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001189 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001190 }
1191 if (callee_) {
1192 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001193 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001194 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001195
1196 // If turn servers were created for the test they need to be destroyed on
1197 // the network thread.
1198 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1199 turn_servers_.clear();
1200 turn_customizers_.clear();
1201 });
deadbeef1dcb1642017-03-29 21:08:16 -07001202 }
1203
1204 bool SignalingStateStable() {
1205 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1206 }
1207
deadbeef71452802017-05-07 17:21:01 -07001208 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001209 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1210 // are connected. This is an important distinction. Once we have separate
1211 // ICE and DTLS state, this check needs to use the DTLS state.
1212 return (callee()->ice_connection_state() ==
1213 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1214 callee()->ice_connection_state() ==
1215 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1216 (caller()->ice_connection_state() ==
1217 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1218 caller()->ice_connection_state() ==
1219 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001220 }
1221
Qingsi Wang7685e862018-06-11 20:15:46 -07001222 // When |event_log_factory| is null, the default implementation of the event
1223 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001224 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1225 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001226 const PeerConnectionFactory::Options* options,
1227 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001228 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001229 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1230 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001231 RTCConfiguration modified_config;
1232 if (config) {
1233 modified_config = *config;
1234 }
Steve Anton3acffc32018-04-12 17:21:03 -07001235 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001236 if (!dependencies.cert_generator) {
1237 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001238 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001239 }
1240 std::unique_ptr<PeerConnectionWrapper> client(
1241 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001242
Niels Möllerf06f9232018-08-07 12:32:18 +02001243 if (!client->Init(options, &modified_config, std::move(dependencies),
1244 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001245 std::move(event_log_factory),
1246 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001247 return nullptr;
1248 }
1249 return client;
1250 }
1251
Qingsi Wang7685e862018-06-11 20:15:46 -07001252 std::unique_ptr<PeerConnectionWrapper>
1253 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1254 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001255 const PeerConnectionFactory::Options* options,
1256 const RTCConfiguration* config,
1257 webrtc::PeerConnectionDependencies dependencies) {
1258 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1259 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001260 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001261 std::move(dependencies),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001262 std::move(event_log_factory),
1263 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001264 }
1265
deadbeef1dcb1642017-03-29 21:08:16 -07001266 bool CreatePeerConnectionWrappers() {
1267 return CreatePeerConnectionWrappersWithConfig(
1268 PeerConnectionInterface::RTCConfiguration(),
1269 PeerConnectionInterface::RTCConfiguration());
1270 }
1271
Steve Anton3acffc32018-04-12 17:21:03 -07001272 bool CreatePeerConnectionWrappersWithSdpSemantics(
1273 SdpSemantics caller_semantics,
1274 SdpSemantics callee_semantics) {
1275 // Can't specify the sdp_semantics in the passed-in configuration since it
1276 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1277 // stored in sdp_semantics_. So get around this by modifying the instance
1278 // variable before calling CreatePeerConnectionWrapper for the caller and
1279 // callee PeerConnections.
1280 SdpSemantics original_semantics = sdp_semantics_;
1281 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001282 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001283 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001284 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001285 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001286 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001287 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001288 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001289 sdp_semantics_ = original_semantics;
1290 return caller_ && callee_;
1291 }
1292
deadbeef1dcb1642017-03-29 21:08:16 -07001293 bool CreatePeerConnectionWrappersWithConfig(
1294 const PeerConnectionInterface::RTCConfiguration& caller_config,
1295 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001296 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001297 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001298 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1299 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001300 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001301 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001302 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1303 /*media_transport_factory=*/nullptr);
1304 return caller_ && callee_;
1305 }
1306
1307 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1308 const PeerConnectionInterface::RTCConfiguration& caller_config,
1309 const PeerConnectionInterface::RTCConfiguration& callee_config,
1310 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1311 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
1312 caller_ =
1313 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1314 webrtc::PeerConnectionDependencies(nullptr),
1315 nullptr, std::move(caller_factory));
1316 callee_ =
1317 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1318 webrtc::PeerConnectionDependencies(nullptr),
1319 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001320 return caller_ && callee_;
1321 }
1322
1323 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1324 const PeerConnectionInterface::RTCConfiguration& caller_config,
1325 webrtc::PeerConnectionDependencies caller_dependencies,
1326 const PeerConnectionInterface::RTCConfiguration& callee_config,
1327 webrtc::PeerConnectionDependencies callee_dependencies) {
1328 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001329 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001330 std::move(caller_dependencies), nullptr,
1331 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001332 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001333 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001334 std::move(callee_dependencies), nullptr,
1335 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001336 return caller_ && callee_;
1337 }
1338
1339 bool CreatePeerConnectionWrappersWithOptions(
1340 const PeerConnectionFactory::Options& caller_options,
1341 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001342 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001343 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001344 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1345 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001346 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001347 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001348 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1349 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001350 return caller_ && callee_;
1351 }
1352
1353 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1354 PeerConnectionInterface::RTCConfiguration default_config;
1355 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001356 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001357 webrtc::PeerConnectionDependencies(nullptr));
1358 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001359 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001360 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001361 return caller_ && callee_;
1362 }
1363
Seth Hampson2f0d7022018-02-20 11:54:42 -08001364 std::unique_ptr<PeerConnectionWrapper>
1365 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001366 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1367 new FakeRTCCertificateGenerator());
1368 cert_generator->use_alternate_key();
1369
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001370 webrtc::PeerConnectionDependencies dependencies(nullptr);
1371 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001372 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001373 std::move(dependencies), nullptr,
1374 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001375 }
1376
Seth Hampsonaed71642018-06-11 07:41:32 -07001377 cricket::TestTurnServer* CreateTurnServer(
1378 rtc::SocketAddress internal_address,
1379 rtc::SocketAddress external_address,
1380 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1381 const std::string& common_name = "test turn server") {
1382 rtc::Thread* thread = network_thread();
1383 std::unique_ptr<cricket::TestTurnServer> turn_server =
1384 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1385 RTC_FROM_HERE,
1386 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001387 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001388 thread, internal_address, external_address, type,
1389 /*ignore_bad_certs=*/true, common_name);
1390 });
1391 turn_servers_.push_back(std::move(turn_server));
1392 // Interactions with the turn server should be done on the network thread.
1393 return turn_servers_.back().get();
1394 }
1395
1396 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1397 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1398 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1399 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001400 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001401 turn_customizers_.push_back(std::move(turn_customizer));
1402 // Interactions with the turn customizer should be done on the network
1403 // thread.
1404 return turn_customizers_.back().get();
1405 }
1406
1407 // Checks that the function counters for a TestTurnCustomizer are greater than
1408 // 0.
1409 void ExpectTurnCustomizerCountersIncremented(
1410 cricket::TestTurnCustomizer* turn_customizer) {
1411 unsigned int allow_channel_data_counter =
1412 network_thread()->Invoke<unsigned int>(
1413 RTC_FROM_HERE, [turn_customizer] {
1414 return turn_customizer->allow_channel_data_cnt_;
1415 });
1416 EXPECT_GT(allow_channel_data_counter, 0u);
1417 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1418 RTC_FROM_HERE,
1419 [turn_customizer] { return turn_customizer->modify_cnt_; });
1420 EXPECT_GT(modify_counter, 0u);
1421 }
1422
deadbeef1dcb1642017-03-29 21:08:16 -07001423 // Once called, SDP blobs and ICE candidates will be automatically signaled
1424 // between PeerConnections.
1425 void ConnectFakeSignaling() {
1426 caller_->set_signaling_message_receiver(callee_.get());
1427 callee_->set_signaling_message_receiver(caller_.get());
1428 }
1429
Steve Antonede9ca52017-10-16 13:04:27 -07001430 // Once called, SDP blobs will be automatically signaled between
1431 // PeerConnections. Note that ICE candidates will not be signaled unless they
1432 // are in the exchanged SDP blobs.
1433 void ConnectFakeSignalingForSdpOnly() {
1434 ConnectFakeSignaling();
1435 SetSignalIceCandidates(false);
1436 }
1437
deadbeef1dcb1642017-03-29 21:08:16 -07001438 void SetSignalingDelayMs(int delay_ms) {
1439 caller_->set_signaling_delay_ms(delay_ms);
1440 callee_->set_signaling_delay_ms(delay_ms);
1441 }
1442
Steve Antonede9ca52017-10-16 13:04:27 -07001443 void SetSignalIceCandidates(bool signal) {
1444 caller_->set_signal_ice_candidates(signal);
1445 callee_->set_signal_ice_candidates(signal);
1446 }
1447
deadbeef1dcb1642017-03-29 21:08:16 -07001448 // Messages may get lost on the unreliable DataChannel, so we send multiple
1449 // times to avoid test flakiness.
1450 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1451 const std::string& data,
1452 int retries) {
1453 for (int i = 0; i < retries; ++i) {
1454 dc->Send(DataBuffer(data));
1455 }
1456 }
1457
1458 rtc::Thread* network_thread() { return network_thread_.get(); }
1459
1460 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1461
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001462 webrtc::MediaTransportPair* loopback_media_transports() {
1463 return &loopback_media_transports_;
1464 }
1465
deadbeef1dcb1642017-03-29 21:08:16 -07001466 PeerConnectionWrapper* caller() { return caller_.get(); }
1467
1468 // Set the |caller_| to the |wrapper| passed in and return the
1469 // original |caller_|.
1470 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1471 PeerConnectionWrapper* wrapper) {
1472 PeerConnectionWrapper* old = caller_.release();
1473 caller_.reset(wrapper);
1474 return old;
1475 }
1476
1477 PeerConnectionWrapper* callee() { return callee_.get(); }
1478
1479 // Set the |callee_| to the |wrapper| passed in and return the
1480 // original |callee_|.
1481 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1482 PeerConnectionWrapper* wrapper) {
1483 PeerConnectionWrapper* old = callee_.release();
1484 callee_.reset(wrapper);
1485 return old;
1486 }
1487
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001488 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1489 network_thread()->Invoke<void>(
1490 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1491 caller()->port_allocator(), caller_flags));
1492 network_thread()->Invoke<void>(
1493 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1494 callee()->port_allocator(), callee_flags));
1495 }
1496
Steve Antonede9ca52017-10-16 13:04:27 -07001497 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1498
Seth Hampson2f0d7022018-02-20 11:54:42 -08001499 // Expects the provided number of new frames to be received within
1500 // kMaxWaitForFramesMs. The new expected frames are specified in
1501 // |media_expectations|. Returns false if any of the expectations were
1502 // not met.
1503 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1504 // First initialize the expected frame counts based upon the current
1505 // frame count.
1506 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1507 if (media_expectations.caller_audio_expectation_ ==
1508 MediaExpectations::kExpectSomeFrames) {
1509 total_caller_audio_frames_expected +=
1510 media_expectations.caller_audio_frames_expected_;
1511 }
1512 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001513 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001514 if (media_expectations.caller_video_expectation_ ==
1515 MediaExpectations::kExpectSomeFrames) {
1516 total_caller_video_frames_expected +=
1517 media_expectations.caller_video_frames_expected_;
1518 }
1519 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1520 if (media_expectations.callee_audio_expectation_ ==
1521 MediaExpectations::kExpectSomeFrames) {
1522 total_callee_audio_frames_expected +=
1523 media_expectations.callee_audio_frames_expected_;
1524 }
1525 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001526 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001527 if (media_expectations.callee_video_expectation_ ==
1528 MediaExpectations::kExpectSomeFrames) {
1529 total_callee_video_frames_expected +=
1530 media_expectations.callee_video_frames_expected_;
1531 }
deadbeef1dcb1642017-03-29 21:08:16 -07001532
Seth Hampson2f0d7022018-02-20 11:54:42 -08001533 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001534 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001535 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001536 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001537 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001538 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001539 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001540 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001541 total_callee_video_frames_expected,
1542 kMaxWaitForFramesMs);
1543 bool expectations_correct =
1544 caller()->audio_frames_received() >=
1545 total_caller_audio_frames_expected &&
1546 caller()->min_video_frames_received_per_track() >=
1547 total_caller_video_frames_expected &&
1548 callee()->audio_frames_received() >=
1549 total_callee_audio_frames_expected &&
1550 callee()->min_video_frames_received_per_track() >=
1551 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001552
Seth Hampson2f0d7022018-02-20 11:54:42 -08001553 // After the combined wait, print out a more detailed message upon
1554 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001555 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001556 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001557 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001558 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001559 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001560 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001561 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001562 total_callee_video_frames_expected);
1563
1564 // We want to make sure nothing unexpected was received.
1565 if (media_expectations.caller_audio_expectation_ ==
1566 MediaExpectations::kExpectNoFrames) {
1567 EXPECT_EQ(caller()->audio_frames_received(),
1568 total_caller_audio_frames_expected);
1569 if (caller()->audio_frames_received() !=
1570 total_caller_audio_frames_expected) {
1571 expectations_correct = false;
1572 }
1573 }
1574 if (media_expectations.caller_video_expectation_ ==
1575 MediaExpectations::kExpectNoFrames) {
1576 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1577 total_caller_video_frames_expected);
1578 if (caller()->min_video_frames_received_per_track() !=
1579 total_caller_video_frames_expected) {
1580 expectations_correct = false;
1581 }
1582 }
1583 if (media_expectations.callee_audio_expectation_ ==
1584 MediaExpectations::kExpectNoFrames) {
1585 EXPECT_EQ(callee()->audio_frames_received(),
1586 total_callee_audio_frames_expected);
1587 if (callee()->audio_frames_received() !=
1588 total_callee_audio_frames_expected) {
1589 expectations_correct = false;
1590 }
1591 }
1592 if (media_expectations.callee_video_expectation_ ==
1593 MediaExpectations::kExpectNoFrames) {
1594 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1595 total_callee_video_frames_expected);
1596 if (callee()->min_video_frames_received_per_track() !=
1597 total_callee_video_frames_expected) {
1598 expectations_correct = false;
1599 }
1600 }
1601 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001602 }
1603
Steve Antond91969e2019-05-30 12:27:03 -07001604 void ClosePeerConnections() {
1605 caller()->pc()->Close();
1606 callee()->pc()->Close();
1607 }
1608
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001609 void TestNegotiatedCipherSuite(
1610 const PeerConnectionFactory::Options& caller_options,
1611 const PeerConnectionFactory::Options& callee_options,
1612 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001613 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1614 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001615 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001616 caller()->AddAudioVideoTracks();
1617 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001618 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001619 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001620 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001621 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001622 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00001623 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001624 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1625 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001626 }
1627
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001628 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1629 bool remote_gcm_enabled,
1630 int expected_cipher_suite) {
1631 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001632 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1633 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001634 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001635 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1636 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001637 TestNegotiatedCipherSuite(caller_options, callee_options,
1638 expected_cipher_suite);
1639 }
1640
Seth Hampson2f0d7022018-02-20 11:54:42 -08001641 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001642 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001643
deadbeef1dcb1642017-03-29 21:08:16 -07001644 private:
1645 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001646 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001647 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001648 // |network_thread_| and |worker_thread_| are used by both
1649 // |caller_| and |callee_| so they must be destroyed
1650 // later.
1651 std::unique_ptr<rtc::Thread> network_thread_;
1652 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001653 // The turn servers and turn customizers should be accessed & deleted on the
1654 // network thread to avoid a race with the socket read/write that occurs
1655 // on the network thread.
1656 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1657 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001658 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001659 std::unique_ptr<PeerConnectionWrapper> caller_;
1660 std::unique_ptr<PeerConnectionWrapper> callee_;
1661};
1662
Seth Hampson2f0d7022018-02-20 11:54:42 -08001663class PeerConnectionIntegrationTest
1664 : public PeerConnectionIntegrationBaseTest,
1665 public ::testing::WithParamInterface<SdpSemantics> {
1666 protected:
1667 PeerConnectionIntegrationTest()
1668 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1669};
1670
1671class PeerConnectionIntegrationTestPlanB
1672 : public PeerConnectionIntegrationBaseTest {
1673 protected:
1674 PeerConnectionIntegrationTestPlanB()
1675 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1676};
1677
1678class PeerConnectionIntegrationTestUnifiedPlan
1679 : public PeerConnectionIntegrationBaseTest {
1680 protected:
1681 PeerConnectionIntegrationTestUnifiedPlan()
1682 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1683};
1684
deadbeef1dcb1642017-03-29 21:08:16 -07001685// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1686// includes testing that the callback is invoked if an observer is connected
1687// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001688TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001689 RtpReceiverObserverOnFirstPacketReceived) {
1690 ASSERT_TRUE(CreatePeerConnectionWrappers());
1691 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001692 caller()->AddAudioVideoTracks();
1693 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001694 // Start offer/answer exchange and wait for it to complete.
1695 caller()->CreateAndSetAndSignalOffer();
1696 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1697 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001698 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1699 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001700 // Wait for all "first packet received" callbacks to be fired.
1701 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001702 absl::c_all_of(caller()->rtp_receiver_observers(),
1703 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1704 return o->first_packet_received();
1705 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001706 kMaxWaitForFramesMs);
1707 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001708 absl::c_all_of(callee()->rtp_receiver_observers(),
1709 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1710 return o->first_packet_received();
1711 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001712 kMaxWaitForFramesMs);
1713 // If new observers are set after the first packet was already received, the
1714 // callback should still be invoked.
1715 caller()->ResetRtpReceiverObservers();
1716 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001717 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1718 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001719 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001720 absl::c_all_of(caller()->rtp_receiver_observers(),
1721 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1722 return o->first_packet_received();
1723 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001724 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001725 absl::c_all_of(callee()->rtp_receiver_observers(),
1726 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1727 return o->first_packet_received();
1728 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001729}
1730
1731class DummyDtmfObserver : public DtmfSenderObserverInterface {
1732 public:
1733 DummyDtmfObserver() : completed_(false) {}
1734
1735 // Implements DtmfSenderObserverInterface.
1736 void OnToneChange(const std::string& tone) override {
1737 tones_.push_back(tone);
1738 if (tone.empty()) {
1739 completed_ = true;
1740 }
1741 }
1742
1743 const std::vector<std::string>& tones() const { return tones_; }
1744 bool completed() const { return completed_; }
1745
1746 private:
1747 bool completed_;
1748 std::vector<std::string> tones_;
1749};
1750
1751// Assumes |sender| already has an audio track added and the offer/answer
1752// exchange is done.
1753void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1754 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001755 // We should be able to get a DTMF sender from the local sender.
1756 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1757 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1758 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001759 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001760 dtmf_sender->RegisterObserver(&observer);
1761
1762 // Test the DtmfSender object just created.
1763 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1764 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1765
1766 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1767 std::vector<std::string> tones = {"1", "a", ""};
1768 EXPECT_EQ(tones, observer.tones());
1769 dtmf_sender->UnregisterObserver();
1770 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1771}
1772
1773// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1774// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001775TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001776 ASSERT_TRUE(CreatePeerConnectionWrappers());
1777 ConnectFakeSignaling();
1778 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001779 caller()->AddAudioTrack();
1780 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001781 caller()->CreateAndSetAndSignalOffer();
1782 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001783 // DTLS must finish before the DTMF sender can be used reliably.
1784 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001785 TestDtmfFromSenderToReceiver(caller(), callee());
1786 TestDtmfFromSenderToReceiver(callee(), caller());
1787}
1788
1789// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1790// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001791TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001792 ASSERT_TRUE(CreatePeerConnectionWrappers());
1793 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001794
deadbeef1dcb1642017-03-29 21:08:16 -07001795 // Do normal offer/answer and wait for some frames to be received in each
1796 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001797 caller()->AddAudioVideoTracks();
1798 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001799 caller()->CreateAndSetAndSignalOffer();
1800 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001801 MediaExpectations media_expectations;
1802 media_expectations.ExpectBidirectionalAudioAndVideo();
1803 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001804 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1805 webrtc::kEnumCounterKeyProtocolDtls));
1806 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1807 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001808}
1809
1810// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001811TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001812 PeerConnectionInterface::RTCConfiguration sdes_config;
1813 sdes_config.enable_dtls_srtp.emplace(false);
1814 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1815 ConnectFakeSignaling();
1816
1817 // Do normal offer/answer and wait for some frames to be received in each
1818 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001819 caller()->AddAudioVideoTracks();
1820 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001821 caller()->CreateAndSetAndSignalOffer();
1822 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001823 MediaExpectations media_expectations;
1824 media_expectations.ExpectBidirectionalAudioAndVideo();
1825 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001826 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1827 webrtc::kEnumCounterKeyProtocolSdes));
1828 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1829 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001830}
1831
Steve Anton9a44b2d2019-07-12 12:58:30 -07001832// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1833// option to offer encrypted versions of all header extensions alongside the
1834// unencrypted versions.
1835TEST_P(PeerConnectionIntegrationTest,
1836 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1837 CryptoOptions crypto_options;
1838 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1839 PeerConnectionInterface::RTCConfiguration config;
1840 config.crypto_options = crypto_options;
1841 // Note: This allows offering >14 RTP header extensions.
1842 config.offer_extmap_allow_mixed = true;
1843 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1844 ConnectFakeSignaling();
1845
1846 // Do normal offer/answer and wait for some frames to be received in each
1847 // direction.
1848 caller()->AddAudioVideoTracks();
1849 callee()->AddAudioVideoTracks();
1850 caller()->CreateAndSetAndSignalOffer();
1851 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1852 MediaExpectations media_expectations;
1853 media_expectations.ExpectBidirectionalAudioAndVideo();
1854 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1855}
1856
Steve Anton8c0f7a72017-10-03 10:03:10 -07001857// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1858// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001859TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001860 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1861 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1862 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1863 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1864 return pc->GetRemoteAudioSSLCertificate();
1865 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001866 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1867 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1868 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1869 return pc->GetRemoteAudioSSLCertChain();
1870 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001871
1872 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1873 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1874
1875 // Configure each side with a known certificate so they can be compared later.
1876 PeerConnectionInterface::RTCConfiguration caller_config;
1877 caller_config.enable_dtls_srtp.emplace(true);
1878 caller_config.certificates.push_back(caller_cert);
1879 PeerConnectionInterface::RTCConfiguration callee_config;
1880 callee_config.enable_dtls_srtp.emplace(true);
1881 callee_config.certificates.push_back(callee_cert);
1882 ASSERT_TRUE(
1883 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1884 ConnectFakeSignaling();
1885
1886 // When first initialized, there should not be a remote SSL certificate (and
1887 // calling this method should not crash).
1888 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1889 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001890 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1891 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001892
Steve Anton15324772018-01-16 10:26:49 -08001893 caller()->AddAudioTrack();
1894 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001895 caller()->CreateAndSetAndSignalOffer();
1896 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1897 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1898
1899 // Once DTLS has been connected, each side should return the other's SSL
1900 // certificate when calling GetRemoteAudioSSLCertificate.
1901
1902 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1903 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001904 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001905 caller_remote_cert->ToPEMString());
1906
1907 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1908 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001909 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001910 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001911
1912 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1913 ASSERT_TRUE(caller_remote_cert_chain);
1914 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1915 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001916 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001917 remote_cert->ToPEMString());
1918
1919 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1920 ASSERT_TRUE(callee_remote_cert_chain);
1921 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1922 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001923 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001924 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001925}
1926
deadbeef1dcb1642017-03-29 21:08:16 -07001927// This test sets up a call between two parties with a source resolution of
1928// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001929TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001930 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1931 ASSERT_TRUE(CreatePeerConnectionWrappers());
1932 ConnectFakeSignaling();
1933
Niels Möller5c7efe72018-05-11 10:34:46 +02001934 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1935 webrtc::FakePeriodicVideoSource::Config config;
1936 config.width = 1280;
1937 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001938 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001939 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1940 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001941
1942 // Do normal offer/answer and wait for at least one frame to be received in
1943 // each direction.
1944 caller()->CreateAndSetAndSignalOffer();
1945 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1946 callee()->min_video_frames_received_per_track() > 0,
1947 kMaxWaitForFramesMs);
1948
1949 // Check rendered aspect ratio.
1950 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1951 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1952 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1953 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1954}
1955
1956// This test sets up an one-way call, with media only from caller to
1957// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001958TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001959 ASSERT_TRUE(CreatePeerConnectionWrappers());
1960 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001961 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001962 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001963 MediaExpectations media_expectations;
1964 media_expectations.CalleeExpectsSomeAudioAndVideo();
1965 media_expectations.CallerExpectsNoAudio();
1966 media_expectations.CallerExpectsNoVideo();
1967 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001968}
1969
1970// This test sets up a audio call initially, with the callee rejecting video
1971// initially. Then later the callee decides to upgrade to audio/video, and
1972// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001973TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001974 ASSERT_TRUE(CreatePeerConnectionWrappers());
1975 ConnectFakeSignaling();
1976 // Initially, offer an audio/video stream from the caller, but refuse to
1977 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001978 caller()->AddAudioVideoTracks();
1979 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001980 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1981 PeerConnectionInterface::RTCOfferAnswerOptions options;
1982 options.offer_to_receive_video = 0;
1983 callee()->SetOfferAnswerOptions(options);
1984 } else {
1985 callee()->SetRemoteOfferHandler([this] {
1986 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1987 });
1988 }
deadbeef1dcb1642017-03-29 21:08:16 -07001989 // Do offer/answer and make sure audio is still received end-to-end.
1990 caller()->CreateAndSetAndSignalOffer();
1991 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001992 {
1993 MediaExpectations media_expectations;
1994 media_expectations.ExpectBidirectionalAudio();
1995 media_expectations.ExpectNoVideo();
1996 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1997 }
deadbeef1dcb1642017-03-29 21:08:16 -07001998 // Sanity check that the callee's description has a rejected video section.
1999 ASSERT_NE(nullptr, callee()->pc()->local_description());
2000 const ContentInfo* callee_video_content =
2001 GetFirstVideoContent(callee()->pc()->local_description()->description());
2002 ASSERT_NE(nullptr, callee_video_content);
2003 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002004
deadbeef1dcb1642017-03-29 21:08:16 -07002005 // Now negotiate with video and ensure negotiation succeeds, with video
2006 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002007 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002008 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2009 PeerConnectionInterface::RTCOfferAnswerOptions options;
2010 options.offer_to_receive_video = 1;
2011 callee()->SetOfferAnswerOptions(options);
2012 } else {
2013 callee()->SetRemoteOfferHandler(nullptr);
2014 caller()->SetRemoteOfferHandler([this] {
2015 // The caller creates a new transceiver to receive video on when receiving
2016 // the offer, but by default it is send only.
2017 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002018 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002019 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
2020 transceivers[2]->receiver()->media_type());
2021 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2022 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
2023 });
2024 }
deadbeef1dcb1642017-03-29 21:08:16 -07002025 callee()->CreateAndSetAndSignalOffer();
2026 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002027 {
2028 // Expect additional audio frames to be received after the upgrade.
2029 MediaExpectations media_expectations;
2030 media_expectations.ExpectBidirectionalAudioAndVideo();
2031 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2032 }
deadbeef1dcb1642017-03-29 21:08:16 -07002033}
2034
deadbeef4389b4d2017-09-07 09:07:36 -07002035// Simpler than the above test; just add an audio track to an established
2036// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002037TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002038 ASSERT_TRUE(CreatePeerConnectionWrappers());
2039 ConnectFakeSignaling();
2040 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002041 caller()->AddVideoTrack();
2042 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002043 caller()->CreateAndSetAndSignalOffer();
2044 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2045 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002046 caller()->AddAudioTrack();
2047 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002048 caller()->CreateAndSetAndSignalOffer();
2049 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2050 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002051 MediaExpectations media_expectations;
2052 media_expectations.ExpectBidirectionalAudioAndVideo();
2053 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002054}
2055
deadbeef1dcb1642017-03-29 21:08:16 -07002056// This test sets up a call that's transferred to a new caller with a different
2057// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002058TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002059 ASSERT_TRUE(CreatePeerConnectionWrappers());
2060 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002061 caller()->AddAudioVideoTracks();
2062 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002063 caller()->CreateAndSetAndSignalOffer();
2064 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2065
2066 // Keep the original peer around which will still send packets to the
2067 // receiving client. These SRTP packets will be dropped.
2068 std::unique_ptr<PeerConnectionWrapper> original_peer(
2069 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002070 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002071 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2072 // directly above.
2073 original_peer->pc()->Close();
2074
2075 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002076 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002077 caller()->CreateAndSetAndSignalOffer();
2078 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2079 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002080 MediaExpectations media_expectations;
2081 media_expectations.ExpectBidirectionalAudioAndVideo();
2082 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002083}
2084
2085// This test sets up a call that's transferred to a new callee with a different
2086// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002087TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002088 ASSERT_TRUE(CreatePeerConnectionWrappers());
2089 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002090 caller()->AddAudioVideoTracks();
2091 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002092 caller()->CreateAndSetAndSignalOffer();
2093 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2094
2095 // Keep the original peer around which will still send packets to the
2096 // receiving client. These SRTP packets will be dropped.
2097 std::unique_ptr<PeerConnectionWrapper> original_peer(
2098 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002099 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002100 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2101 // directly above.
2102 original_peer->pc()->Close();
2103
2104 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002105 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002106 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2107 caller()->CreateAndSetAndSignalOffer();
2108 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2109 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002110 MediaExpectations media_expectations;
2111 media_expectations.ExpectBidirectionalAudioAndVideo();
2112 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002113}
2114
2115// This test sets up a non-bundled call and negotiates bundling at the same
2116// time as starting an ICE restart. When bundling is in effect in the restart,
2117// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002118TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002119 ASSERT_TRUE(CreatePeerConnectionWrappers());
2120 ConnectFakeSignaling();
2121
Steve Anton15324772018-01-16 10:26:49 -08002122 caller()->AddAudioVideoTracks();
2123 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002124 // Remove the bundle group from the SDP received by the callee.
2125 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2126 desc->RemoveGroupByName("BUNDLE");
2127 });
2128 caller()->CreateAndSetAndSignalOffer();
2129 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002130 {
2131 MediaExpectations media_expectations;
2132 media_expectations.ExpectBidirectionalAudioAndVideo();
2133 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2134 }
deadbeef1dcb1642017-03-29 21:08:16 -07002135 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2136 callee()->SetReceivedSdpMunger(nullptr);
2137 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2138 caller()->CreateAndSetAndSignalOffer();
2139 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2140
2141 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002142 {
2143 MediaExpectations media_expectations;
2144 media_expectations.ExpectBidirectionalAudioAndVideo();
2145 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2146 }
deadbeef1dcb1642017-03-29 21:08:16 -07002147}
2148
2149// Test CVO (Coordination of Video Orientation). If a video source is rotated
2150// and both peers support the CVO RTP header extension, the actual video frames
2151// don't need to be encoded in different resolutions, since the rotation is
2152// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002153TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002154 ASSERT_TRUE(CreatePeerConnectionWrappers());
2155 ConnectFakeSignaling();
2156 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002157 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002158 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002159 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002160 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2161
2162 // Wait for video frames to be received by both sides.
2163 caller()->CreateAndSetAndSignalOffer();
2164 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2165 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2166 callee()->min_video_frames_received_per_track() > 0,
2167 kMaxWaitForFramesMs);
2168
2169 // Ensure that the aspect ratio is unmodified.
2170 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2171 // not just assumed.
2172 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2173 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2174 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2175 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2176 // Ensure that the CVO bits were surfaced to the renderer.
2177 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2178 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2179}
2180
2181// Test that when the CVO extension isn't supported, video is rotated the
2182// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002183TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002184 ASSERT_TRUE(CreatePeerConnectionWrappers());
2185 ConnectFakeSignaling();
2186 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002187 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002188 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002189 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002190 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2191
2192 // Remove the CVO extension from the offered SDP.
2193 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2194 cricket::VideoContentDescription* video =
2195 GetFirstVideoContentDescription(desc);
2196 video->ClearRtpHeaderExtensions();
2197 });
2198 // Wait for video frames to be received by both sides.
2199 caller()->CreateAndSetAndSignalOffer();
2200 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2201 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2202 callee()->min_video_frames_received_per_track() > 0,
2203 kMaxWaitForFramesMs);
2204
2205 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2206 // rotation.
2207 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2208 // not just assumed.
2209 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2210 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2211 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2212 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2213 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2214 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2215 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2216}
2217
deadbeef1dcb1642017-03-29 21:08:16 -07002218// Test that if the answerer rejects the audio m= section, no audio is sent or
2219// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002220TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002221 ASSERT_TRUE(CreatePeerConnectionWrappers());
2222 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002223 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002224 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2225 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2226 // it will reject the audio m= section completely.
2227 PeerConnectionInterface::RTCOfferAnswerOptions options;
2228 options.offer_to_receive_audio = 0;
2229 callee()->SetOfferAnswerOptions(options);
2230 } else {
2231 // Stopping the audio RtpTransceiver will cause the media section to be
2232 // rejected in the answer.
2233 callee()->SetRemoteOfferHandler([this] {
2234 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2235 });
2236 }
Steve Anton15324772018-01-16 10:26:49 -08002237 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002238 // Do offer/answer and wait for successful end-to-end video frames.
2239 caller()->CreateAndSetAndSignalOffer();
2240 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002241 MediaExpectations media_expectations;
2242 media_expectations.ExpectBidirectionalVideo();
2243 media_expectations.ExpectNoAudio();
2244 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2245
deadbeef1dcb1642017-03-29 21:08:16 -07002246 // Sanity check that the callee's description has a rejected audio section.
2247 ASSERT_NE(nullptr, callee()->pc()->local_description());
2248 const ContentInfo* callee_audio_content =
2249 GetFirstAudioContent(callee()->pc()->local_description()->description());
2250 ASSERT_NE(nullptr, callee_audio_content);
2251 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002252 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2253 // The caller's transceiver should have stopped after receiving the answer.
2254 EXPECT_TRUE(caller()
2255 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2256 ->stopped());
2257 }
deadbeef1dcb1642017-03-29 21:08:16 -07002258}
2259
2260// Test that if the answerer rejects the video m= section, no video is sent or
2261// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002262TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002263 ASSERT_TRUE(CreatePeerConnectionWrappers());
2264 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002265 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002266 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2267 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2268 // it will reject the video m= section completely.
2269 PeerConnectionInterface::RTCOfferAnswerOptions options;
2270 options.offer_to_receive_video = 0;
2271 callee()->SetOfferAnswerOptions(options);
2272 } else {
2273 // Stopping the video RtpTransceiver will cause the media section to be
2274 // rejected in the answer.
2275 callee()->SetRemoteOfferHandler([this] {
2276 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2277 });
2278 }
Steve Anton15324772018-01-16 10:26:49 -08002279 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002280 // Do offer/answer and wait for successful end-to-end audio frames.
2281 caller()->CreateAndSetAndSignalOffer();
2282 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002283 MediaExpectations media_expectations;
2284 media_expectations.ExpectBidirectionalAudio();
2285 media_expectations.ExpectNoVideo();
2286 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2287
deadbeef1dcb1642017-03-29 21:08:16 -07002288 // Sanity check that the callee's description has a rejected video section.
2289 ASSERT_NE(nullptr, callee()->pc()->local_description());
2290 const ContentInfo* callee_video_content =
2291 GetFirstVideoContent(callee()->pc()->local_description()->description());
2292 ASSERT_NE(nullptr, callee_video_content);
2293 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002294 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2295 // The caller's transceiver should have stopped after receiving the answer.
2296 EXPECT_TRUE(caller()
2297 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2298 ->stopped());
2299 }
deadbeef1dcb1642017-03-29 21:08:16 -07002300}
2301
2302// Test that if the answerer rejects both audio and video m= sections, nothing
2303// bad happens.
2304// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2305// test anything but the fact that negotiation succeeds, which doesn't mean
2306// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002307TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002308 ASSERT_TRUE(CreatePeerConnectionWrappers());
2309 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002310 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002311 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2312 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2313 // will reject both audio and video m= sections.
2314 PeerConnectionInterface::RTCOfferAnswerOptions options;
2315 options.offer_to_receive_audio = 0;
2316 options.offer_to_receive_video = 0;
2317 callee()->SetOfferAnswerOptions(options);
2318 } else {
2319 callee()->SetRemoteOfferHandler([this] {
2320 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002321 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002322 transceiver->Stop();
2323 }
2324 });
2325 }
deadbeef1dcb1642017-03-29 21:08:16 -07002326 // Do offer/answer and wait for stable signaling state.
2327 caller()->CreateAndSetAndSignalOffer();
2328 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002329
deadbeef1dcb1642017-03-29 21:08:16 -07002330 // Sanity check that the callee's description has rejected m= sections.
2331 ASSERT_NE(nullptr, callee()->pc()->local_description());
2332 const ContentInfo* callee_audio_content =
2333 GetFirstAudioContent(callee()->pc()->local_description()->description());
2334 ASSERT_NE(nullptr, callee_audio_content);
2335 EXPECT_TRUE(callee_audio_content->rejected);
2336 const ContentInfo* callee_video_content =
2337 GetFirstVideoContent(callee()->pc()->local_description()->description());
2338 ASSERT_NE(nullptr, callee_video_content);
2339 EXPECT_TRUE(callee_video_content->rejected);
2340}
2341
2342// This test sets up an audio and video call between two parties. After the
2343// call runs for a while, the caller sends an updated offer with video being
2344// rejected. Once the re-negotiation is done, the video flow should stop and
2345// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002346TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002347 ASSERT_TRUE(CreatePeerConnectionWrappers());
2348 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002349 caller()->AddAudioVideoTracks();
2350 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002351 caller()->CreateAndSetAndSignalOffer();
2352 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002353 {
2354 MediaExpectations media_expectations;
2355 media_expectations.ExpectBidirectionalAudioAndVideo();
2356 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2357 }
deadbeef1dcb1642017-03-29 21:08:16 -07002358 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002359 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2360 caller()->SetGeneratedSdpMunger(
2361 [](cricket::SessionDescription* description) {
2362 for (cricket::ContentInfo& content : description->contents()) {
2363 if (cricket::IsVideoContent(&content)) {
2364 content.rejected = true;
2365 }
2366 }
2367 });
2368 } else {
2369 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2370 }
deadbeef1dcb1642017-03-29 21:08:16 -07002371 caller()->CreateAndSetAndSignalOffer();
2372 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2373
2374 // Sanity check that the caller's description has a rejected video section.
2375 ASSERT_NE(nullptr, caller()->pc()->local_description());
2376 const ContentInfo* caller_video_content =
2377 GetFirstVideoContent(caller()->pc()->local_description()->description());
2378 ASSERT_NE(nullptr, caller_video_content);
2379 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002380 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002381 {
2382 MediaExpectations media_expectations;
2383 media_expectations.ExpectBidirectionalAudio();
2384 media_expectations.ExpectNoVideo();
2385 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2386 }
deadbeef1dcb1642017-03-29 21:08:16 -07002387}
2388
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002389// Do one offer/answer with audio, another that disables it (rejecting the m=
2390// section), and another that re-enables it. Regression test for:
2391// bugs.webrtc.org/6023
2392TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2393 ASSERT_TRUE(CreatePeerConnectionWrappers());
2394 ConnectFakeSignaling();
2395
2396 // Add audio track, do normal offer/answer.
2397 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2398 caller()->CreateLocalAudioTrack();
2399 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2400 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2401 caller()->CreateAndSetAndSignalOffer();
2402 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2403
2404 // Remove audio track, and set offer_to_receive_audio to false to cause the
2405 // m= section to be completely disabled, not just "recvonly".
2406 caller()->pc()->RemoveTrack(sender);
2407 PeerConnectionInterface::RTCOfferAnswerOptions options;
2408 options.offer_to_receive_audio = 0;
2409 caller()->SetOfferAnswerOptions(options);
2410 caller()->CreateAndSetAndSignalOffer();
2411 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2412
2413 // Add the audio track again, expecting negotiation to succeed and frames to
2414 // flow.
2415 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2416 options.offer_to_receive_audio = 1;
2417 caller()->SetOfferAnswerOptions(options);
2418 caller()->CreateAndSetAndSignalOffer();
2419 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2420
2421 MediaExpectations media_expectations;
2422 media_expectations.CalleeExpectsSomeAudio();
2423 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2424}
2425
deadbeef1dcb1642017-03-29 21:08:16 -07002426// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2427// is needed to support legacy endpoints.
2428// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2429// add a test for an end-to-end test without MID signaling either (basically,
2430// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002431TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002432 ASSERT_TRUE(CreatePeerConnectionWrappers());
2433 ConnectFakeSignaling();
2434 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002435 caller()->AddAudioVideoTracks();
2436 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002437 // Remove SSRCs and MSIDs from the received offer SDP.
2438 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002439 caller()->CreateAndSetAndSignalOffer();
2440 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002441 MediaExpectations media_expectations;
2442 media_expectations.ExpectBidirectionalAudioAndVideo();
2443 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002444}
2445
Seth Hampson5897a6e2018-04-03 11:16:33 -07002446// Basic end-to-end test, without SSRC signaling. This means that the track
2447// was created properly and frames are delivered when the MSIDs are communicated
2448// with a=msid lines and no a=ssrc lines.
2449TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2450 EndToEndCallWithoutSsrcSignaling) {
2451 const char kStreamId[] = "streamId";
2452 ASSERT_TRUE(CreatePeerConnectionWrappers());
2453 ConnectFakeSignaling();
2454 // Add just audio tracks.
2455 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2456 callee()->AddAudioTrack();
2457
2458 // Remove SSRCs from the received offer SDP.
2459 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2460 caller()->CreateAndSetAndSignalOffer();
2461 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2462 MediaExpectations media_expectations;
2463 media_expectations.ExpectBidirectionalAudio();
2464 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2465}
2466
Steve Antondf527fd2018-04-27 15:52:03 -07002467// Tests that video flows between multiple video tracks when SSRCs are not
2468// signaled. This exercises the MID RTP header extension which is needed to
2469// demux the incoming video tracks.
2470TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2471 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2472 ASSERT_TRUE(CreatePeerConnectionWrappers());
2473 ConnectFakeSignaling();
2474 caller()->AddVideoTrack();
2475 caller()->AddVideoTrack();
2476 callee()->AddVideoTrack();
2477 callee()->AddVideoTrack();
2478
2479 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2480 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2481 caller()->CreateAndSetAndSignalOffer();
2482 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2483 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2484 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2485
2486 // Expect video to be received in both directions on both tracks.
2487 MediaExpectations media_expectations;
2488 media_expectations.ExpectBidirectionalVideo();
2489 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2490}
2491
Henrik Boström5b147782018-12-04 11:25:05 +01002492TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2493 ASSERT_TRUE(CreatePeerConnectionWrappers());
2494 ConnectFakeSignaling();
2495 caller()->AddAudioTrack();
2496 caller()->AddVideoTrack();
2497 caller()->CreateAndSetAndSignalOffer();
2498 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2499 auto callee_receivers = callee()->pc()->GetReceivers();
2500 ASSERT_EQ(2u, callee_receivers.size());
2501 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2502 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2503}
2504
2505TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2506 ASSERT_TRUE(CreatePeerConnectionWrappers());
2507 ConnectFakeSignaling();
2508 caller()->AddAudioTrack();
2509 caller()->AddVideoTrack();
2510 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2511 caller()->CreateAndSetAndSignalOffer();
2512 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2513 auto callee_receivers = callee()->pc()->GetReceivers();
2514 ASSERT_EQ(2u, callee_receivers.size());
2515 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2516 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2517 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2518 callee_receivers[1]->stream_ids()[0]);
2519 EXPECT_EQ(callee_receivers[0]->streams()[0],
2520 callee_receivers[1]->streams()[0]);
2521}
2522
deadbeef1dcb1642017-03-29 21:08:16 -07002523// Test that if two video tracks are sent (from caller to callee, in this test),
2524// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002525TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002526 ASSERT_TRUE(CreatePeerConnectionWrappers());
2527 ConnectFakeSignaling();
2528 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002529 caller()->AddAudioVideoTracks();
2530 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002531 caller()->CreateAndSetAndSignalOffer();
2532 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002533 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002534
2535 MediaExpectations media_expectations;
2536 media_expectations.CalleeExpectsSomeAudioAndVideo();
2537 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002538}
2539
2540static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2541 bool first = true;
2542 for (cricket::ContentInfo& content : desc->contents()) {
2543 if (first) {
2544 first = false;
2545 continue;
2546 }
2547 content.bundle_only = true;
2548 }
2549 first = true;
2550 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2551 if (first) {
2552 first = false;
2553 continue;
2554 }
2555 transport.description.ice_ufrag.clear();
2556 transport.description.ice_pwd.clear();
2557 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2558 transport.description.identity_fingerprint.reset(nullptr);
2559 }
2560}
2561
2562// Test that if applying a true "max bundle" offer, which uses ports of 0,
2563// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2564// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2565// successfully and media flows.
2566// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2567// TODO(deadbeef): Won't need this test once we start generating actual
2568// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002569TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002570 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2571 ASSERT_TRUE(CreatePeerConnectionWrappers());
2572 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002573 caller()->AddAudioVideoTracks();
2574 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002575 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2576 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2577 // but the first m= section.
2578 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2579 caller()->CreateAndSetAndSignalOffer();
2580 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002581 MediaExpectations media_expectations;
2582 media_expectations.ExpectBidirectionalAudioAndVideo();
2583 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002584}
2585
2586// Test that we can receive the audio output level from a remote audio track.
2587// TODO(deadbeef): Use a fake audio source and verify that the output level is
2588// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002589TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002590 ASSERT_TRUE(CreatePeerConnectionWrappers());
2591 ConnectFakeSignaling();
2592 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002593 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002594 caller()->CreateAndSetAndSignalOffer();
2595 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2596
2597 // Get the audio output level stats. Note that the level is not available
2598 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002599 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002600 kMaxWaitForFramesMs);
2601}
2602
2603// Test that an audio input level is reported.
2604// TODO(deadbeef): Use a fake audio source and verify that the input level is
2605// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002606TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002607 ASSERT_TRUE(CreatePeerConnectionWrappers());
2608 ConnectFakeSignaling();
2609 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002610 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002611 caller()->CreateAndSetAndSignalOffer();
2612 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2613
2614 // Get the audio input level stats. The level should be available very
2615 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002616 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002617 kMaxWaitForStatsMs);
2618}
2619
2620// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002621TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002622 ASSERT_TRUE(CreatePeerConnectionWrappers());
2623 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002624 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002625 // Do offer/answer, wait for the callee to receive some frames.
2626 caller()->CreateAndSetAndSignalOffer();
2627 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002628
2629 MediaExpectations media_expectations;
2630 media_expectations.CalleeExpectsSomeAudioAndVideo();
2631 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002632
2633 // Get a handle to the remote tracks created, so they can be used as GetStats
2634 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002635 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002636 // We received frames, so we definitely should have nonzero "received bytes"
2637 // stats at this point.
2638 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2639 0);
2640 }
deadbeef1dcb1642017-03-29 21:08:16 -07002641}
2642
2643// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002644TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002645 ASSERT_TRUE(CreatePeerConnectionWrappers());
2646 ConnectFakeSignaling();
2647 auto audio_track = caller()->CreateLocalAudioTrack();
2648 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002649 caller()->AddTrack(audio_track);
2650 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002651 // Do offer/answer, wait for the callee to receive some frames.
2652 caller()->CreateAndSetAndSignalOffer();
2653 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002654 MediaExpectations media_expectations;
2655 media_expectations.CalleeExpectsSomeAudioAndVideo();
2656 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002657
2658 // The callee received frames, so we definitely should have nonzero "sent
2659 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002660 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2661 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2662}
2663
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002664// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002665TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002666 ASSERT_TRUE(CreatePeerConnectionWrappers());
2667 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002668 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002669
Steve Anton15324772018-01-16 10:26:49 -08002670 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002671
2672 // Do offer/answer, wait for the callee to receive some frames.
2673 caller()->CreateAndSetAndSignalOffer();
2674 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2675
2676 // Get the remote audio track created on the receiver, so they can be used as
2677 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002678 auto receivers = callee()->pc()->GetReceivers();
2679 ASSERT_EQ(1u, receivers.size());
2680 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002681
2682 // Get the audio output level stats. Note that the level is not available
2683 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002684 EXPECT_TRUE_WAIT(
2685 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2686 0,
2687 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002688}
2689
Steve Antona41959e2018-11-28 11:15:33 -08002690// Test that the track ID is associated with all local and remote SSRC stats
2691// using the old GetStats() and more than 1 audio and more than 1 video track.
2692// This is a regression test for crbug.com/906988
2693TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2694 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2695 ASSERT_TRUE(CreatePeerConnectionWrappers());
2696 ConnectFakeSignaling();
2697 auto audio_sender_1 = caller()->AddAudioTrack();
2698 auto video_sender_1 = caller()->AddVideoTrack();
2699 auto audio_sender_2 = caller()->AddAudioTrack();
2700 auto video_sender_2 = caller()->AddVideoTrack();
2701 caller()->CreateAndSetAndSignalOffer();
2702 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2703
2704 MediaExpectations media_expectations;
2705 media_expectations.CalleeExpectsSomeAudioAndVideo();
2706 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2707
2708 std::vector<std::string> track_ids = {
2709 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2710 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2711
2712 auto caller_stats = caller()->OldGetStats();
2713 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2714 auto callee_stats = callee()->OldGetStats();
2715 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2716}
2717
Steve Antonffa6ce42018-11-30 09:26:08 -08002718// Test that the new GetStats() returns stats for all outgoing/incoming streams
2719// with the correct track IDs if there are more than one audio and more than one
2720// video senders/receivers.
2721TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2722 ASSERT_TRUE(CreatePeerConnectionWrappers());
2723 ConnectFakeSignaling();
2724 auto audio_sender_1 = caller()->AddAudioTrack();
2725 auto video_sender_1 = caller()->AddVideoTrack();
2726 auto audio_sender_2 = caller()->AddAudioTrack();
2727 auto video_sender_2 = caller()->AddVideoTrack();
2728 caller()->CreateAndSetAndSignalOffer();
2729 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2730
2731 MediaExpectations media_expectations;
2732 media_expectations.CalleeExpectsSomeAudioAndVideo();
2733 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2734
2735 std::vector<std::string> track_ids = {
2736 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2737 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2738
2739 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2740 caller()->NewGetStats();
2741 ASSERT_TRUE(caller_report);
2742 auto outbound_stream_stats =
2743 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2744 ASSERT_EQ(4u, outbound_stream_stats.size());
2745 std::vector<std::string> outbound_track_ids;
2746 for (const auto& stat : outbound_stream_stats) {
2747 ASSERT_TRUE(stat->bytes_sent.is_defined());
2748 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002749 if (*stat->kind == "video") {
2750 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
2751 EXPECT_GT(*stat->key_frames_encoded, 0u);
2752 ASSERT_TRUE(stat->frames_encoded.is_defined());
2753 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
2754 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002755 ASSERT_TRUE(stat->track_id.is_defined());
2756 const auto* track_stat =
2757 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2758 ASSERT_TRUE(track_stat);
2759 outbound_track_ids.push_back(*track_stat->track_identifier);
2760 }
2761 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2762
2763 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2764 callee()->NewGetStats();
2765 ASSERT_TRUE(callee_report);
2766 auto inbound_stream_stats =
2767 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2768 ASSERT_EQ(4u, inbound_stream_stats.size());
2769 std::vector<std::string> inbound_track_ids;
2770 for (const auto& stat : inbound_stream_stats) {
2771 ASSERT_TRUE(stat->bytes_received.is_defined());
2772 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002773 if (*stat->kind == "video") {
2774 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
2775 EXPECT_GT(*stat->key_frames_decoded, 0u);
2776 ASSERT_TRUE(stat->frames_decoded.is_defined());
2777 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
2778 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002779 ASSERT_TRUE(stat->track_id.is_defined());
2780 const auto* track_stat =
2781 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2782 ASSERT_TRUE(track_stat);
2783 inbound_track_ids.push_back(*track_stat->track_identifier);
2784 }
2785 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2786}
2787
2788// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002789// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2790// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002791TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002792 GetStatsForUnsignaledStreamWithNewStatsApi) {
2793 ASSERT_TRUE(CreatePeerConnectionWrappers());
2794 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002795 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002796 // Remove SSRCs and MSIDs from the received offer SDP.
2797 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2798 caller()->CreateAndSetAndSignalOffer();
2799 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002800 MediaExpectations media_expectations;
2801 media_expectations.CalleeExpectsSomeAudio(1);
2802 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002803
2804 // We received a frame, so we should have nonzero "bytes received" stats for
2805 // the unsignaled stream, if stats are working for it.
2806 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2807 callee()->NewGetStats();
2808 ASSERT_NE(nullptr, report);
2809 auto inbound_stream_stats =
2810 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2811 ASSERT_EQ(1U, inbound_stream_stats.size());
2812 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2813 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002814 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2815}
2816
Taylor Brandstettera4653442018-06-19 09:44:26 -07002817// Same as above but for the legacy stats implementation.
2818TEST_P(PeerConnectionIntegrationTest,
2819 GetStatsForUnsignaledStreamWithOldStatsApi) {
2820 ASSERT_TRUE(CreatePeerConnectionWrappers());
2821 ConnectFakeSignaling();
2822 caller()->AddAudioTrack();
2823 // Remove SSRCs and MSIDs from the received offer SDP.
2824 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2825 caller()->CreateAndSetAndSignalOffer();
2826 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2827
2828 // Note that, since the old stats implementation associates SSRCs with tracks
2829 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2830 // associated track ID. So we can't use the track "selector" argument.
2831 //
2832 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2833 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002834 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002835 kDefaultTimeout);
2836}
2837
zhihuangf8164932017-05-19 13:09:47 -07002838// Test that we can successfully get the media related stats (audio level
2839// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002840TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002841 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2842 ASSERT_TRUE(CreatePeerConnectionWrappers());
2843 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002844 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002845 // Remove SSRCs and MSIDs from the received offer SDP.
2846 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2847 caller()->CreateAndSetAndSignalOffer();
2848 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002849 MediaExpectations media_expectations;
2850 media_expectations.CalleeExpectsSomeAudio(1);
2851 media_expectations.CalleeExpectsSomeVideo(1);
2852 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002853
2854 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2855 callee()->NewGetStats();
2856 ASSERT_NE(nullptr, report);
2857
2858 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2859 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2860 ASSERT_GE(audio_index, 0);
2861 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002862}
2863
deadbeef4e2deab2017-09-20 13:56:21 -07002864// Helper for test below.
2865void ModifySsrcs(cricket::SessionDescription* desc) {
2866 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002867 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002868 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002869 for (uint32_t& ssrc : stream.ssrcs) {
2870 ssrc = rtc::CreateRandomId();
2871 }
2872 }
2873 }
2874}
2875
2876// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2877// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2878// This should result in two "RTCInboundRTPStreamStats", but only one
2879// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2880// being reset to 0 once the SSRC change occurs.
2881//
2882// Regression test for this bug:
2883// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2884//
2885// The bug causes the track stats to only represent one of the two streams:
2886// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2887// that the track stat counters would reset to 0 when the new stream is
2888// received, and a 50% chance that they'll stop updating (while
2889// "concealed_samples" continues increasing, due to silence being generated for
2890// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002891TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002892 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002893 ASSERT_TRUE(CreatePeerConnectionWrappers());
2894 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002895 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002896 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2897 // that doesn't signal SSRCs (from the callee's perspective).
2898 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2899 caller()->CreateAndSetAndSignalOffer();
2900 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2901 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002902 {
2903 MediaExpectations media_expectations;
2904 media_expectations.CalleeExpectsSomeAudio(50);
2905 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2906 }
deadbeef4e2deab2017-09-20 13:56:21 -07002907 // Some audio frames were received, so we should have nonzero "samples
2908 // received" for the track.
2909 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2910 callee()->NewGetStats();
2911 ASSERT_NE(nullptr, report);
2912 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2913 ASSERT_EQ(1U, track_stats.size());
2914 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2915 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2916 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2917
2918 // Create a new offer and munge it to cause the caller to use a new SSRC.
2919 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2920 caller()->CreateAndSetAndSignalOffer();
2921 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2922 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2923 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002924 {
2925 MediaExpectations media_expectations;
2926 media_expectations.CalleeExpectsSomeAudio(25);
2927 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2928 }
deadbeef4e2deab2017-09-20 13:56:21 -07002929
2930 report = callee()->NewGetStats();
2931 ASSERT_NE(nullptr, report);
2932 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2933 ASSERT_EQ(1U, track_stats.size());
2934 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2935 // The "total samples received" stat should only be greater than it was
2936 // before.
2937 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2938 // Right now, the new SSRC will cause the counters to reset to 0.
2939 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2940
2941 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002942 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002943 // good sign that we're seeing stats from the old stream that's no longer
2944 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002945 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002946 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2947 EXPECT_LT(*track_stats[0]->concealed_samples,
2948 *track_stats[0]->total_samples_received *
2949 kAcceptableConcealedSamplesPercentage);
2950
2951 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2952 // sanity check that the SSRC really changed.
2953 // TODO(deadbeef): This isn't working right now, because we're not returning
2954 // *any* stats for the inactive stream. Uncomment when the bug is completely
2955 // fixed.
2956 // auto inbound_stream_stats =
2957 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2958 // ASSERT_EQ(2U, inbound_stream_stats.size());
2959}
2960
deadbeef1dcb1642017-03-29 21:08:16 -07002961// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002962TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002963 PeerConnectionFactory::Options dtls_10_options;
2964 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2965 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2966 dtls_10_options));
2967 ConnectFakeSignaling();
2968 // Do normal offer/answer and wait for some frames to be received in each
2969 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002970 caller()->AddAudioVideoTracks();
2971 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002972 caller()->CreateAndSetAndSignalOffer();
2973 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002974 MediaExpectations media_expectations;
2975 media_expectations.ExpectBidirectionalAudioAndVideo();
2976 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002977}
2978
2979// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002980TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002981 PeerConnectionFactory::Options dtls_10_options;
2982 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2983 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2984 dtls_10_options));
2985 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002986 caller()->AddAudioVideoTracks();
2987 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002988 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002989 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002990 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002991 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002992 kDefaultTimeout);
2993 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002994 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002995 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002996 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002997 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2998 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002999}
3000
3001// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003002TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003003 PeerConnectionFactory::Options dtls_12_options;
3004 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3005 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3006 dtls_12_options));
3007 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003008 caller()->AddAudioVideoTracks();
3009 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003010 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003011 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003012 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003013 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003014 kDefaultTimeout);
3015 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003016 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003017 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00003018 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003019 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3020 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003021}
3022
3023// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3024// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003025TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003026 PeerConnectionFactory::Options caller_options;
3027 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3028 PeerConnectionFactory::Options callee_options;
3029 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3030 ASSERT_TRUE(
3031 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3032 ConnectFakeSignaling();
3033 // Do normal offer/answer and wait for some frames to be received in each
3034 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003035 caller()->AddAudioVideoTracks();
3036 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003037 caller()->CreateAndSetAndSignalOffer();
3038 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003039 MediaExpectations media_expectations;
3040 media_expectations.ExpectBidirectionalAudioAndVideo();
3041 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003042}
3043
3044// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3045// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003046TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003047 PeerConnectionFactory::Options caller_options;
3048 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3049 PeerConnectionFactory::Options callee_options;
3050 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3051 ASSERT_TRUE(
3052 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3053 ConnectFakeSignaling();
3054 // Do normal offer/answer and wait for some frames to be received in each
3055 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003056 caller()->AddAudioVideoTracks();
3057 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003058 caller()->CreateAndSetAndSignalOffer();
3059 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003060 MediaExpectations media_expectations;
3061 media_expectations.ExpectBidirectionalAudioAndVideo();
3062 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003063}
3064
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003065// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3066// works as expected; the cipher should only be used if enabled by both sides.
3067TEST_P(PeerConnectionIntegrationTest,
3068 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3069 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003070 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003071 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003072 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3073 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003074 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3075 TestNegotiatedCipherSuite(caller_options, callee_options,
3076 expected_cipher_suite);
3077}
3078
3079TEST_P(PeerConnectionIntegrationTest,
3080 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3081 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003082 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3083 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003084 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003085 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003086 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3087 TestNegotiatedCipherSuite(caller_options, callee_options,
3088 expected_cipher_suite);
3089}
3090
3091TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3092 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003093 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003094 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003095 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003096 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3097 TestNegotiatedCipherSuite(caller_options, callee_options,
3098 expected_cipher_suite);
3099}
3100
deadbeef1dcb1642017-03-29 21:08:16 -07003101// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003102TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003103 bool local_gcm_enabled = false;
3104 bool remote_gcm_enabled = false;
3105 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3106 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3107 expected_cipher_suite);
3108}
3109
3110// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003111TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003112 bool local_gcm_enabled = true;
3113 bool remote_gcm_enabled = true;
3114 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3115 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3116 expected_cipher_suite);
3117}
3118
3119// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003120TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003121 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
3122 bool local_gcm_enabled = true;
3123 bool remote_gcm_enabled = false;
3124 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3125 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3126 expected_cipher_suite);
3127}
3128
3129// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003130TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003131 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
3132 bool local_gcm_enabled = false;
3133 bool remote_gcm_enabled = true;
3134 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3135 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3136 expected_cipher_suite);
3137}
3138
deadbeef7914b8c2017-04-21 03:23:33 -07003139// Verify that media can be transmitted end-to-end when GCM crypto suites are
3140// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3141// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3142// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003143TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003144 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003145 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07003146 ASSERT_TRUE(
3147 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3148 ConnectFakeSignaling();
3149 // Do normal offer/answer and wait for some frames to be received in each
3150 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003151 caller()->AddAudioVideoTracks();
3152 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003153 caller()->CreateAndSetAndSignalOffer();
3154 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003155 MediaExpectations media_expectations;
3156 media_expectations.ExpectBidirectionalAudioAndVideo();
3157 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003158}
3159
deadbeef1dcb1642017-03-29 21:08:16 -07003160// This test sets up a call between two parties with audio, video and an RTP
3161// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003162TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003163 PeerConnectionInterface::RTCConfiguration rtc_config;
3164 rtc_config.enable_rtp_data_channel = true;
3165 rtc_config.enable_dtls_srtp = false;
3166 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003167 ConnectFakeSignaling();
3168 // Expect that data channel created on caller side will show up for callee as
3169 // well.
3170 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003171 caller()->AddAudioVideoTracks();
3172 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003173 caller()->CreateAndSetAndSignalOffer();
3174 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3175 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003176 MediaExpectations media_expectations;
3177 media_expectations.ExpectBidirectionalAudioAndVideo();
3178 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003179 ASSERT_NE(nullptr, caller()->data_channel());
3180 ASSERT_NE(nullptr, callee()->data_channel());
3181 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3182 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3183
3184 // Ensure data can be sent in both directions.
3185 std::string data = "hello world";
3186 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3187 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3188 kDefaultTimeout);
3189 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3190 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3191 kDefaultTimeout);
3192}
3193
3194// Ensure that an RTP data channel is signaled as closed for the caller when
3195// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003196TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003197 RtpDataChannelSignaledClosedInCalleeOffer) {
3198 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003199 PeerConnectionInterface::RTCConfiguration rtc_config;
3200 rtc_config.enable_rtp_data_channel = true;
3201 rtc_config.enable_dtls_srtp = false;
3202 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003203 ConnectFakeSignaling();
3204 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003205 caller()->AddAudioVideoTracks();
3206 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003207 caller()->CreateAndSetAndSignalOffer();
3208 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3209 ASSERT_NE(nullptr, caller()->data_channel());
3210 ASSERT_NE(nullptr, callee()->data_channel());
3211 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3212 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3213
3214 // Close the data channel on the callee, and do an updated offer/answer.
3215 callee()->data_channel()->Close();
3216 callee()->CreateAndSetAndSignalOffer();
3217 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3218 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3219 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3220}
3221
3222// Tests that data is buffered in an RTP data channel until an observer is
3223// registered for it.
3224//
3225// NOTE: RTP data channels can receive data before the underlying
3226// transport has detected that a channel is writable and thus data can be
3227// received before the data channel state changes to open. That is hard to test
3228// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003229TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003230 DataBufferedUntilRtpDataChannelObserverRegistered) {
3231 // Use fake clock and simulated network delay so that we predictably can wait
3232 // until an SCTP message has been delivered without "sleep()"ing.
3233 rtc::ScopedFakeClock fake_clock;
3234 // Some things use a time of "0" as a special value, so we need to start out
3235 // the fake clock at a nonzero time.
3236 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003237 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003238 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3239 virtual_socket_server()->UpdateDelayDistribution();
3240
Niels Möllerf06f9232018-08-07 12:32:18 +02003241 PeerConnectionInterface::RTCConfiguration rtc_config;
3242 rtc_config.enable_rtp_data_channel = true;
3243 rtc_config.enable_dtls_srtp = false;
3244 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003245 ConnectFakeSignaling();
3246 caller()->CreateDataChannel();
3247 caller()->CreateAndSetAndSignalOffer();
3248 ASSERT_TRUE(caller()->data_channel() != nullptr);
3249 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3250 kDefaultTimeout, fake_clock);
3251 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3252 kDefaultTimeout, fake_clock);
3253 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3254 callee()->data_channel()->state(), kDefaultTimeout,
3255 fake_clock);
3256
3257 // Unregister the observer which is normally automatically registered.
3258 callee()->data_channel()->UnregisterObserver();
3259 // Send data and advance fake clock until it should have been received.
3260 std::string data = "hello world";
3261 caller()->data_channel()->Send(DataBuffer(data));
3262 SIMULATED_WAIT(false, 50, fake_clock);
3263
3264 // Attach data channel and expect data to be received immediately. Note that
3265 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3266 // further, but data can be received even if the callback is asynchronous.
3267 MockDataChannelObserver new_observer(callee()->data_channel());
3268 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3269 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003270 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3271 // If this is not done a DCHECK can be hit in ports.cc, because a large
3272 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07003273 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07003274}
3275
3276// This test sets up a call between two parties with audio, video and but only
3277// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003278TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003279 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3280 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003281 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003282 rtc_config_1.enable_dtls_srtp = false;
3283 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3284 rtc_config_2.enable_dtls_srtp = false;
3285 rtc_config_2.enable_dtls_srtp = false;
3286 ASSERT_TRUE(
3287 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003288 ConnectFakeSignaling();
3289 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003290 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003291 caller()->AddAudioVideoTracks();
3292 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003293 caller()->CreateAndSetAndSignalOffer();
3294 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3295 // The caller should still have a data channel, but it should be closed, and
3296 // one should ever have been created for the callee.
3297 EXPECT_TRUE(caller()->data_channel() != nullptr);
3298 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3299 EXPECT_EQ(nullptr, callee()->data_channel());
3300}
3301
3302// This test sets up a call between two parties with audio, and video. When
3303// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003304TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003305 PeerConnectionInterface::RTCConfiguration rtc_config;
3306 rtc_config.enable_rtp_data_channel = true;
3307 rtc_config.enable_dtls_srtp = false;
3308 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003309 ConnectFakeSignaling();
3310 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003311 caller()->AddAudioVideoTracks();
3312 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003313 caller()->CreateAndSetAndSignalOffer();
3314 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3315 // Create data channel and do new offer and answer.
3316 caller()->CreateDataChannel();
3317 caller()->CreateAndSetAndSignalOffer();
3318 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3319 ASSERT_NE(nullptr, caller()->data_channel());
3320 ASSERT_NE(nullptr, callee()->data_channel());
3321 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3322 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3323 // Ensure data can be sent in both directions.
3324 std::string data = "hello world";
3325 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3326 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3327 kDefaultTimeout);
3328 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3329 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3330 kDefaultTimeout);
3331}
3332
3333#ifdef HAVE_SCTP
3334
3335// This test sets up a call between two parties with audio, video and an SCTP
3336// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003337TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003338 ASSERT_TRUE(CreatePeerConnectionWrappers());
3339 ConnectFakeSignaling();
3340 // Expect that data channel created on caller side will show up for callee as
3341 // well.
3342 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003343 caller()->AddAudioVideoTracks();
3344 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003345 caller()->CreateAndSetAndSignalOffer();
3346 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3347 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003348 MediaExpectations media_expectations;
3349 media_expectations.ExpectBidirectionalAudioAndVideo();
3350 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003351 // Caller data channel should already exist (it created one). Callee data
3352 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3353 ASSERT_NE(nullptr, caller()->data_channel());
3354 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3355 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3356 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3357
3358 // Ensure data can be sent in both directions.
3359 std::string data = "hello world";
3360 caller()->data_channel()->Send(DataBuffer(data));
3361 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3362 kDefaultTimeout);
3363 callee()->data_channel()->Send(DataBuffer(data));
3364 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3365 kDefaultTimeout);
3366}
3367
3368// Ensure that when the callee closes an SCTP data channel, the closing
3369// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003370TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003371 // Same procedure as above test.
3372 ASSERT_TRUE(CreatePeerConnectionWrappers());
3373 ConnectFakeSignaling();
3374 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003375 caller()->AddAudioVideoTracks();
3376 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003377 caller()->CreateAndSetAndSignalOffer();
3378 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3379 ASSERT_NE(nullptr, caller()->data_channel());
3380 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3381 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3382 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3383
3384 // Close the data channel on the callee side, and wait for it to reach the
3385 // "closed" state on both sides.
3386 callee()->data_channel()->Close();
3387 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3388 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3389}
3390
Seth Hampson2f0d7022018-02-20 11:54:42 -08003391TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003392 ASSERT_TRUE(CreatePeerConnectionWrappers());
3393 ConnectFakeSignaling();
3394 webrtc::DataChannelInit init;
3395 init.id = 53;
3396 init.maxRetransmits = 52;
3397 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003398 caller()->AddAudioVideoTracks();
3399 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003400 caller()->CreateAndSetAndSignalOffer();
3401 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003402 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3403 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003404 // Since "negotiated" is false, the "id" parameter should be ignored.
3405 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003406 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3407 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3408 EXPECT_FALSE(callee()->data_channel()->negotiated());
3409}
3410
deadbeef1dcb1642017-03-29 21:08:16 -07003411// Test usrsctp's ability to process unordered data stream, where data actually
3412// arrives out of order using simulated delays. Previously there have been some
3413// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003414TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003415 // Introduce random network delays.
3416 // Otherwise it's not a true "unordered" test.
3417 virtual_socket_server()->set_delay_mean(20);
3418 virtual_socket_server()->set_delay_stddev(5);
3419 virtual_socket_server()->UpdateDelayDistribution();
3420 // Normal procedure, but with unordered data channel config.
3421 ASSERT_TRUE(CreatePeerConnectionWrappers());
3422 ConnectFakeSignaling();
3423 webrtc::DataChannelInit init;
3424 init.ordered = false;
3425 caller()->CreateDataChannel(&init);
3426 caller()->CreateAndSetAndSignalOffer();
3427 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3428 ASSERT_NE(nullptr, caller()->data_channel());
3429 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3430 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3431 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3432
3433 static constexpr int kNumMessages = 100;
3434 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3435 static constexpr size_t kMaxMessageSize = 4096;
3436 // Create and send random messages.
3437 std::vector<std::string> sent_messages;
3438 for (int i = 0; i < kNumMessages; ++i) {
3439 size_t length =
3440 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3441 std::string message;
3442 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3443 caller()->data_channel()->Send(DataBuffer(message));
3444 callee()->data_channel()->Send(DataBuffer(message));
3445 sent_messages.push_back(message);
3446 }
3447
3448 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003449 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003450 caller()->data_observer()->received_message_count(),
3451 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003452 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003453 callee()->data_observer()->received_message_count(),
3454 kDefaultTimeout);
3455
3456 // Sort and compare to make sure none of the messages were corrupted.
3457 std::vector<std::string> caller_received_messages =
3458 caller()->data_observer()->messages();
3459 std::vector<std::string> callee_received_messages =
3460 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003461 absl::c_sort(sent_messages);
3462 absl::c_sort(caller_received_messages);
3463 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003464 EXPECT_EQ(sent_messages, caller_received_messages);
3465 EXPECT_EQ(sent_messages, callee_received_messages);
3466}
3467
3468// This test sets up a call between two parties with audio, and video. When
3469// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003470TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003471 ASSERT_TRUE(CreatePeerConnectionWrappers());
3472 ConnectFakeSignaling();
3473 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003474 caller()->AddAudioVideoTracks();
3475 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003476 caller()->CreateAndSetAndSignalOffer();
3477 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3478 // Create data channel and do new offer and answer.
3479 caller()->CreateDataChannel();
3480 caller()->CreateAndSetAndSignalOffer();
3481 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3482 // Caller data channel should already exist (it created one). Callee data
3483 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3484 ASSERT_NE(nullptr, caller()->data_channel());
3485 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3486 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3487 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3488 // Ensure data can be sent in both directions.
3489 std::string data = "hello world";
3490 caller()->data_channel()->Send(DataBuffer(data));
3491 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3492 kDefaultTimeout);
3493 callee()->data_channel()->Send(DataBuffer(data));
3494 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3495 kDefaultTimeout);
3496}
3497
deadbeef7914b8c2017-04-21 03:23:33 -07003498// Set up a connection initially just using SCTP data channels, later upgrading
3499// to audio/video, ensuring frames are received end-to-end. Effectively the
3500// inverse of the test above.
3501// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003502TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003503 ASSERT_TRUE(CreatePeerConnectionWrappers());
3504 ConnectFakeSignaling();
3505 // Do initial offer/answer with just data channel.
3506 caller()->CreateDataChannel();
3507 caller()->CreateAndSetAndSignalOffer();
3508 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3509 // Wait until data can be sent over the data channel.
3510 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3511 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3512 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3513
3514 // Do subsequent offer/answer with two-way audio and video. Audio and video
3515 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003516 caller()->AddAudioVideoTracks();
3517 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003518 caller()->CreateAndSetAndSignalOffer();
3519 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003520 MediaExpectations media_expectations;
3521 media_expectations.ExpectBidirectionalAudioAndVideo();
3522 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003523}
3524
deadbeef8b7e9ad2017-05-25 09:38:55 -07003525static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003526 cricket::SctpDataContentDescription* dcd_offer =
3527 GetFirstSctpDataContentDescription(desc);
Steve Antonb1c1de12017-12-21 15:14:30 -08003528 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003529 dcd_offer->set_use_sctpmap(false);
3530 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3531}
3532
3533// Test that the data channel works when a spec-compliant SCTP m= section is
3534// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3535// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003536TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003537 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3538 ASSERT_TRUE(CreatePeerConnectionWrappers());
3539 ConnectFakeSignaling();
3540 caller()->CreateDataChannel();
3541 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3542 caller()->CreateAndSetAndSignalOffer();
3543 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3544 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3545 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3546 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3547
3548 // Ensure data can be sent in both directions.
3549 std::string data = "hello world";
3550 caller()->data_channel()->Send(DataBuffer(data));
3551 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3552 kDefaultTimeout);
3553 callee()->data_channel()->Send(DataBuffer(data));
3554 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3555 kDefaultTimeout);
3556}
3557
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003558// Tests that the datagram transport to SCTP fallback works correctly when
3559// datagram transport negotiation fails.
3560TEST_P(PeerConnectionIntegrationTest,
3561 DatagramTransportDataChannelFallbackToSctp) {
3562 PeerConnectionInterface::RTCConfiguration rtc_config;
3563 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3564 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3565 rtc_config.use_datagram_transport_for_data_channels = true;
3566
3567 // Configure one endpoint to use datagram transport for data channels while
3568 // the other does not.
3569 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3570 rtc_config, RTCConfiguration(),
3571 loopback_media_transports()->first_factory(), nullptr));
3572 ConnectFakeSignaling();
3573
3574 // The caller offers a data channel using either datagram transport or SCTP.
3575 caller()->CreateDataChannel();
3576 caller()->AddAudioVideoTracks();
3577 callee()->AddAudioVideoTracks();
3578 caller()->CreateAndSetAndSignalOffer();
3579 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3580
3581 // Negotiation should fallback to SCTP, allowing the data channel to be
3582 // established.
3583 ASSERT_NE(nullptr, caller()->data_channel());
3584 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3585 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3586 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3587
3588 // Ensure data can be sent in both directions.
3589 std::string data = "hello world";
3590 caller()->data_channel()->Send(DataBuffer(data));
3591 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3592 kDefaultTimeout);
3593 callee()->data_channel()->Send(DataBuffer(data));
3594 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3595 kDefaultTimeout);
3596
3597 // Ensure that failure of the datagram negotiation doesn't impede media flow.
3598 MediaExpectations media_expectations;
3599 media_expectations.ExpectBidirectionalAudioAndVideo();
3600 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3601}
3602
deadbeef1dcb1642017-03-29 21:08:16 -07003603#endif // HAVE_SCTP
3604
Bjorn A Mellemb689af42019-08-21 10:44:59 -07003605// This test sets up a call between two parties with a datagram transport data
3606// channel.
3607TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelEndToEnd) {
3608 PeerConnectionInterface::RTCConfiguration rtc_config;
3609 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3610 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3611 rtc_config.use_datagram_transport_for_data_channels = true;
3612 rtc_config.enable_dtls_srtp = false;
3613 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3614 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3615 loopback_media_transports()->second_factory()));
3616 ConnectFakeSignaling();
3617
3618 // Expect that data channel created on caller side will show up for callee as
3619 // well.
3620 caller()->CreateDataChannel();
3621 caller()->CreateAndSetAndSignalOffer();
3622 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3623
3624 // Ensure that the media transport is ready.
3625 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3626 loopback_media_transports()->FlushAsyncInvokes();
3627
3628 // Caller data channel should already exist (it created one). Callee data
3629 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3630 ASSERT_NE(nullptr, caller()->data_channel());
3631 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3632 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3633 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3634
3635 // Ensure data can be sent in both directions.
3636 std::string data = "hello world";
3637 caller()->data_channel()->Send(DataBuffer(data));
3638 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3639 kDefaultTimeout);
3640 callee()->data_channel()->Send(DataBuffer(data));
3641 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3642 kDefaultTimeout);
3643}
3644
3645// Ensures that when the callee closes a datagram transport data channel, the
3646// closing procedure results in the data channel being closed for the caller
3647// as well.
3648TEST_P(PeerConnectionIntegrationTest,
3649 DatagramTransportDataChannelCalleeCloses) {
3650 PeerConnectionInterface::RTCConfiguration rtc_config;
3651 rtc_config.use_datagram_transport_for_data_channels = true;
3652 rtc_config.enable_dtls_srtp = false;
3653 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3654 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3655 loopback_media_transports()->second_factory()));
3656 ConnectFakeSignaling();
3657
3658 // Create a data channel on the caller and signal it to the callee.
3659 caller()->CreateDataChannel();
3660 caller()->CreateAndSetAndSignalOffer();
3661 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3662
3663 // Ensure that the media transport is ready.
3664 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3665 loopback_media_transports()->FlushAsyncInvokes();
3666
3667 // Data channels exist and open on both ends of the connection.
3668 ASSERT_NE(nullptr, caller()->data_channel());
3669 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3670 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3671 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3672
3673 // Close the data channel on the callee side, and wait for it to reach the
3674 // "closed" state on both sides.
3675 callee()->data_channel()->Close();
3676 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3677 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3678}
3679
3680// Tests that datagram transport data channels can do in-band negotiation.
3681TEST_P(PeerConnectionIntegrationTest,
3682 DatagramTransportDataChannelConfigSentToOtherSide) {
3683 PeerConnectionInterface::RTCConfiguration rtc_config;
3684 rtc_config.use_datagram_transport_for_data_channels = true;
3685 rtc_config.enable_dtls_srtp = false;
3686 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3687 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3688 loopback_media_transports()->second_factory()));
3689 ConnectFakeSignaling();
3690
3691 // Create a data channel with a non-default configuration and signal it to the
3692 // callee.
3693 webrtc::DataChannelInit init;
3694 init.id = 53;
3695 init.maxRetransmits = 52;
3696 caller()->CreateDataChannel("data-channel", &init);
3697 caller()->CreateAndSetAndSignalOffer();
3698 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3699
3700 // Ensure that the media transport is ready.
3701 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3702 loopback_media_transports()->FlushAsyncInvokes();
3703
3704 // Ensure that the data channel exists on the callee with the correct
3705 // configuration.
3706 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3707 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3708 // Since "negotiate" is false, the "id" parameter is ignored.
3709 EXPECT_NE(init.id, callee()->data_channel()->id());
3710 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3711 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3712 EXPECT_FALSE(callee()->data_channel()->negotiated());
3713}
3714
3715TEST_P(PeerConnectionIntegrationTest,
3716 DatagramTransportDataChannelRejectedWithNoFallback) {
3717 PeerConnectionInterface::RTCConfiguration offerer_config;
3718 offerer_config.rtcp_mux_policy =
3719 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3720 offerer_config.bundle_policy =
3721 PeerConnectionInterface::kBundlePolicyMaxBundle;
3722 offerer_config.use_datagram_transport_for_data_channels = true;
3723 // Disabling DTLS precludes a fallback to SCTP.
3724 offerer_config.enable_dtls_srtp = false;
3725
3726 PeerConnectionInterface::RTCConfiguration answerer_config;
3727 answerer_config.rtcp_mux_policy =
3728 PeerConnectionInterface::kRtcpMuxPolicyRequire;
3729 answerer_config.bundle_policy =
3730 PeerConnectionInterface::kBundlePolicyMaxBundle;
3731 // Both endpoints must disable DTLS or SetRemoteDescription will fail.
3732 answerer_config.enable_dtls_srtp = false;
3733
3734 // Configure one endpoint to use datagram transport for data channels while
3735 // the other does not.
3736 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3737 offerer_config, answerer_config,
3738 loopback_media_transports()->first_factory(), nullptr));
3739 ConnectFakeSignaling();
3740
3741 // The caller offers a data channel using either datagram transport or SCTP.
3742 caller()->CreateDataChannel();
3743 caller()->AddAudioVideoTracks();
3744 callee()->AddAudioVideoTracks();
3745 caller()->CreateAndSetAndSignalOffer();
3746 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3747
3748 // Caller data channel should already exist (it created one). Callee data
3749 // channel should not exist, since negotiation happens in-band, not in SDP.
3750 EXPECT_NE(nullptr, caller()->data_channel());
3751 EXPECT_EQ(nullptr, callee()->data_channel());
3752
3753 // The caller's data channel should close when the datagram transport is
3754 // rejected.
3755 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3756
3757 // Media flow should not be impacted by the failed data channel.
3758 MediaExpectations media_expectations;
3759 media_expectations.ExpectBidirectionalAudioAndVideo();
3760 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3761}
3762
Bjorn Mellema2eb0a72018-11-09 10:13:51 -08003763// This test sets up a call between two parties with a media transport data
3764// channel.
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003765TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelEndToEnd) {
3766 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003767 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3768 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003769 rtc_config.use_media_transport_for_data_channels = true;
3770 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3771 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3772 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3773 loopback_media_transports()->second_factory()));
3774 ConnectFakeSignaling();
3775
3776 // Expect that data channel created on caller side will show up for callee as
3777 // well.
3778 caller()->CreateDataChannel();
3779 caller()->CreateAndSetAndSignalOffer();
3780 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3781
3782 // Ensure that the media transport is ready.
3783 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3784 loopback_media_transports()->FlushAsyncInvokes();
3785
3786 // Caller data channel should already exist (it created one). Callee data
3787 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3788 ASSERT_NE(nullptr, caller()->data_channel());
3789 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3790 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3791 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3792
3793 // Ensure data can be sent in both directions.
3794 std::string data = "hello world";
3795 caller()->data_channel()->Send(DataBuffer(data));
3796 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3797 kDefaultTimeout);
3798 callee()->data_channel()->Send(DataBuffer(data));
3799 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3800 kDefaultTimeout);
3801}
3802
3803// Ensure that when the callee closes a media transport data channel, the
3804// closing procedure results in the data channel being closed for the caller
3805// as well.
3806TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelCalleeCloses) {
3807 PeerConnectionInterface::RTCConfiguration rtc_config;
3808 rtc_config.use_media_transport_for_data_channels = true;
3809 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3810 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3811 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3812 loopback_media_transports()->second_factory()));
3813 ConnectFakeSignaling();
3814
3815 // Create a data channel on the caller and signal it to the callee.
3816 caller()->CreateDataChannel();
3817 caller()->CreateAndSetAndSignalOffer();
3818 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3819
3820 // Ensure that the media transport is ready.
3821 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3822 loopback_media_transports()->FlushAsyncInvokes();
3823
3824 // Data channels exist and open on both ends of the connection.
3825 ASSERT_NE(nullptr, caller()->data_channel());
3826 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3827 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3828 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3829
3830 // Close the data channel on the callee side, and wait for it to reach the
3831 // "closed" state on both sides.
3832 callee()->data_channel()->Close();
3833 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3834 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3835}
3836
3837TEST_P(PeerConnectionIntegrationTest,
3838 MediaTransportDataChannelConfigSentToOtherSide) {
3839 PeerConnectionInterface::RTCConfiguration rtc_config;
3840 rtc_config.use_media_transport_for_data_channels = true;
3841 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3842 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3843 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3844 loopback_media_transports()->second_factory()));
3845 ConnectFakeSignaling();
3846
3847 // Create a data channel with a non-default configuration and signal it to the
3848 // callee.
3849 webrtc::DataChannelInit init;
3850 init.id = 53;
3851 init.maxRetransmits = 52;
3852 caller()->CreateDataChannel("data-channel", &init);
3853 caller()->CreateAndSetAndSignalOffer();
3854 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3855
3856 // Ensure that the media transport is ready.
3857 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3858 loopback_media_transports()->FlushAsyncInvokes();
3859
3860 // Ensure that the data channel exists on the callee with the correct
3861 // configuration.
3862 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3863 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003864 // Since "negotiate" is false, the "id" parameter is ignored.
3865 EXPECT_NE(init.id, callee()->data_channel()->id());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003866 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3867 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3868 EXPECT_FALSE(callee()->data_channel()->negotiated());
3869}
3870
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003871TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgrade) {
3872 PeerConnectionInterface::RTCConfiguration rtc_config;
3873 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3874 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3875 rtc_config.use_media_transport = true;
3876 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3877 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3878 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3879 loopback_media_transports()->second_factory()));
3880 ConnectFakeSignaling();
3881
3882 // Do initial offer/answer with just a video track.
3883 caller()->AddVideoTrack();
3884 callee()->AddVideoTrack();
3885 caller()->CreateAndSetAndSignalOffer();
3886 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3887
3888 // Ensure that the media transport is ready.
3889 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3890 loopback_media_transports()->FlushAsyncInvokes();
3891
3892 // Now add an audio track and do another offer/answer.
3893 caller()->AddAudioTrack();
3894 callee()->AddAudioTrack();
3895 caller()->CreateAndSetAndSignalOffer();
3896 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3897
3898 // Ensure both audio and video frames are received end-to-end.
3899 MediaExpectations media_expectations;
3900 media_expectations.ExpectBidirectionalAudioAndVideo();
3901 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3902
3903 // The second offer should not have generated another media transport.
3904 // Media transport was kept alive, and was not recreated.
3905 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3906 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3907}
3908
3909TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgradeOnTheCallee) {
3910 PeerConnectionInterface::RTCConfiguration rtc_config;
3911 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3912 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3913 rtc_config.use_media_transport = true;
3914 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3915 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3916 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3917 loopback_media_transports()->second_factory()));
3918 ConnectFakeSignaling();
3919
3920 // Do initial offer/answer with just a video track.
3921 caller()->AddVideoTrack();
3922 callee()->AddVideoTrack();
3923 caller()->CreateAndSetAndSignalOffer();
3924 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3925
3926 // Ensure that the media transport is ready.
3927 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3928 loopback_media_transports()->FlushAsyncInvokes();
3929
3930 // Now add an audio track and do another offer/answer.
3931 caller()->AddAudioTrack();
3932 callee()->AddAudioTrack();
3933 callee()->CreateAndSetAndSignalOffer();
3934 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3935
3936 // Ensure both audio and video frames are received end-to-end.
3937 MediaExpectations media_expectations;
3938 media_expectations.ExpectBidirectionalAudioAndVideo();
3939 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3940
3941 // The second offer should not have generated another media transport.
3942 // Media transport was kept alive, and was not recreated.
3943 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3944 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3945}
3946
Niels Möllerc68d2822018-11-20 14:52:05 +01003947TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalAudio) {
3948 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003949 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3950 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Niels Möllerc68d2822018-11-20 14:52:05 +01003951 rtc_config.use_media_transport = true;
3952 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3953 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3954 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3955 loopback_media_transports()->second_factory()));
3956 ConnectFakeSignaling();
3957
3958 caller()->AddAudioTrack();
3959 callee()->AddAudioTrack();
3960 // Start offer/answer exchange and wait for it to complete.
3961 caller()->CreateAndSetAndSignalOffer();
3962 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3963
3964 // Ensure that the media transport is ready.
3965 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3966 loopback_media_transports()->FlushAsyncInvokes();
3967
3968 MediaExpectations media_expectations;
3969 media_expectations.ExpectBidirectionalAudio();
3970 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3971
3972 webrtc::MediaTransportPair::Stats first_stats =
3973 loopback_media_transports()->FirstStats();
3974 webrtc::MediaTransportPair::Stats second_stats =
3975 loopback_media_transports()->SecondStats();
3976
3977 EXPECT_GT(first_stats.received_audio_frames, 0);
3978 EXPECT_GE(second_stats.sent_audio_frames, first_stats.received_audio_frames);
3979
3980 EXPECT_GT(second_stats.received_audio_frames, 0);
3981 EXPECT_GE(first_stats.sent_audio_frames, second_stats.received_audio_frames);
3982}
3983
Niels Möller46879152019-01-07 15:54:47 +01003984TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalVideo) {
3985 PeerConnectionInterface::RTCConfiguration rtc_config;
3986 rtc_config.use_media_transport = true;
3987 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3988 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3989 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3990 loopback_media_transports()->second_factory()));
3991 ConnectFakeSignaling();
3992
3993 caller()->AddVideoTrack();
3994 callee()->AddVideoTrack();
3995 // Start offer/answer exchange and wait for it to complete.
3996 caller()->CreateAndSetAndSignalOffer();
3997 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3998
3999 // Ensure that the media transport is ready.
4000 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
4001 loopback_media_transports()->FlushAsyncInvokes();
4002
4003 MediaExpectations media_expectations;
4004 media_expectations.ExpectBidirectionalVideo();
4005 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4006
4007 webrtc::MediaTransportPair::Stats first_stats =
4008 loopback_media_transports()->FirstStats();
4009 webrtc::MediaTransportPair::Stats second_stats =
4010 loopback_media_transports()->SecondStats();
4011
4012 EXPECT_GT(first_stats.received_video_frames, 0);
4013 EXPECT_GE(second_stats.sent_video_frames, first_stats.received_video_frames);
4014
4015 EXPECT_GT(second_stats.received_video_frames, 0);
4016 EXPECT_GE(first_stats.sent_video_frames, second_stats.received_video_frames);
4017}
4018
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08004019TEST_P(PeerConnectionIntegrationTest,
4020 MediaTransportDataChannelUsesRtpBidirectionalVideo) {
4021 PeerConnectionInterface::RTCConfiguration rtc_config;
4022 rtc_config.use_media_transport = false;
4023 rtc_config.use_media_transport_for_data_channels = true;
4024 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
4025 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
4026 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
4027 loopback_media_transports()->second_factory()));
4028 ConnectFakeSignaling();
4029
4030 caller()->AddVideoTrack();
4031 callee()->AddVideoTrack();
4032 // Start offer/answer exchange and wait for it to complete.
4033 caller()->CreateAndSetAndSignalOffer();
4034 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4035
4036 MediaExpectations media_expectations;
4037 media_expectations.ExpectBidirectionalVideo();
4038 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4039}
4040
deadbeef1dcb1642017-03-29 21:08:16 -07004041// Test that the ICE connection and gathering states eventually reach
4042// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08004043TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07004044 ASSERT_TRUE(CreatePeerConnectionWrappers());
4045 ConnectFakeSignaling();
4046 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08004047 caller()->AddAudioVideoTracks();
4048 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004049 caller()->CreateAndSetAndSignalOffer();
4050 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4051 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4052 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
4053 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
4054 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
4055 // After the best candidate pair is selected and all candidates are signaled,
4056 // the ICE connection state should reach "complete".
4057 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
4058 // answerer/"callee" by default) only reaches "connected". When this is
4059 // fixed, this test should be updated.
4060 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4061 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00004062 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4063 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07004064}
4065
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004066constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
4067 cricket::PORTALLOCATOR_DISABLE_RELAY |
4068 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004069
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004070// Use a mock resolver to resolve the hostname back to the original IP on both
4071// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004072TEST_P(PeerConnectionIntegrationTest,
4073 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004074 auto caller_resolver_factory =
4075 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
4076 auto callee_resolver_factory =
4077 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
4078 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
4079 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004080
4081 // This also verifies that the injected AsyncResolverFactory is used by
4082 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004083 EXPECT_CALL(*caller_resolver_factory, Create())
4084 .WillOnce(Return(&caller_async_resolver));
4085 webrtc::PeerConnectionDependencies caller_deps(nullptr);
4086 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
4087
4088 EXPECT_CALL(*callee_resolver_factory, Create())
4089 .WillOnce(Return(&callee_async_resolver));
4090 webrtc::PeerConnectionDependencies callee_deps(nullptr);
4091 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
4092
4093 PeerConnectionInterface::RTCConfiguration config;
4094 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4095 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4096
4097 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4098 config, std::move(caller_deps), config, std::move(callee_deps)));
4099
4100 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
4101 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
4102
4103 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07004104 caller()->SetMdnsResponder(
4105 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
4106 callee()->SetMdnsResponder(
4107 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004108
4109 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004110
4111 ConnectFakeSignaling();
4112 caller()->AddAudioVideoTracks();
4113 callee()->AddAudioVideoTracks();
4114 caller()->CreateAndSetAndSignalOffer();
4115 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4116 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4117 caller()->ice_connection_state(), kDefaultTimeout);
4118 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4119 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08004120
4121 EXPECT_EQ(1, webrtc::metrics::NumEvents(
4122 "WebRTC.PeerConnection.CandidatePairType_UDP",
4123 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07004124}
4125
Steve Antonede9ca52017-10-16 13:04:27 -07004126// Test that firewalling the ICE connection causes the clients to identify the
4127// disconnected state and then removing the firewall causes them to reconnect.
4128class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08004129 : public PeerConnectionIntegrationBaseTest,
4130 public ::testing::WithParamInterface<
4131 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07004132 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08004133 PeerConnectionIntegrationIceStatesTest()
4134 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
4135 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07004136 }
4137
4138 void StartStunServer(const SocketAddress& server_address) {
4139 stun_server_.reset(
4140 cricket::TestStunServer::Create(network_thread(), server_address));
4141 }
4142
4143 bool TestIPv6() {
4144 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
4145 }
4146
4147 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08004148 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
4149 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07004150 }
4151
4152 std::vector<SocketAddress> CallerAddresses() {
4153 std::vector<SocketAddress> addresses;
4154 addresses.push_back(SocketAddress("1.1.1.1", 0));
4155 if (TestIPv6()) {
4156 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
4157 }
4158 return addresses;
4159 }
4160
4161 std::vector<SocketAddress> CalleeAddresses() {
4162 std::vector<SocketAddress> addresses;
4163 addresses.push_back(SocketAddress("2.2.2.2", 0));
4164 if (TestIPv6()) {
4165 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
4166 }
4167 return addresses;
4168 }
4169
4170 void SetUpNetworkInterfaces() {
4171 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07004172 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
4173 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07004174
4175 // Add network addresses for test.
4176 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004177 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004178 }
4179 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07004180 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07004181 }
4182 }
4183
4184 private:
4185 uint32_t port_allocator_flags_;
4186 std::unique_ptr<cricket::TestStunServer> stun_server_;
4187};
4188
4189// Tests that the PeerConnection goes through all the ICE gathering/connection
4190// states over the duration of the call. This includes Disconnected and Failed
4191// states, induced by putting a firewall between the peers and waiting for them
4192// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08004193TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004194 rtc::ScopedFakeClock fake_clock;
4195 // Some things use a time of "0" as a special value, so we need to start out
4196 // the fake clock at a nonzero time.
4197 fake_clock.AdvanceTime(TimeDelta::seconds(1));
Steve Antonede9ca52017-10-16 13:04:27 -07004198
4199 const SocketAddress kStunServerAddress =
4200 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
4201 StartStunServer(kStunServerAddress);
4202
4203 PeerConnectionInterface::RTCConfiguration config;
4204 PeerConnectionInterface::IceServer ice_stun_server;
4205 ice_stun_server.urls.push_back(
4206 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4207 kStunServerAddress.PortAsString());
4208 config.servers.push_back(ice_stun_server);
4209
4210 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4211 ConnectFakeSignaling();
4212 SetPortAllocatorFlags();
4213 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004214 caller()->AddAudioVideoTracks();
4215 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004216
4217 // Initial state before anything happens.
4218 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4219 caller()->ice_gathering_state());
4220 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4221 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004222 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4223 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004224
4225 // Start the call by creating the offer, setting it as the local description,
4226 // then sending it to the peer who will respond with an answer. This happens
4227 // asynchronously so that we can watch the states as it runs in the
4228 // background.
4229 caller()->CreateAndSetAndSignalOffer();
4230
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004231 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
4232 caller()->ice_connection_state());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004233 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004234 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004235
4236 // Verify that the observer was notified of the intermediate transitions.
4237 EXPECT_THAT(caller()->ice_connection_state_history(),
4238 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4239 PeerConnectionInterface::kIceConnectionConnected,
4240 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004241 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4242 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4243 PeerConnectionInterface::kIceConnectionConnected,
4244 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004245 EXPECT_THAT(
4246 caller()->peer_connection_state_history(),
4247 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004248 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004249 EXPECT_THAT(caller()->ice_gathering_state_history(),
4250 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4251 PeerConnectionInterface::kIceGatheringComplete));
4252
4253 // Block connections to/from the caller and wait for ICE to become
4254 // disconnected.
4255 for (const auto& caller_address : CallerAddresses()) {
4256 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4257 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004258 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004259 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4260 caller()->ice_connection_state(), kDefaultTimeout,
4261 fake_clock);
4262 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4263 caller()->standardized_ice_connection_state(),
4264 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004265
4266 // Let ICE re-establish by removing the firewall rules.
4267 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004268 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004269 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4270 caller()->ice_connection_state(), kDefaultTimeout,
4271 fake_clock);
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004272 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004273 caller()->standardized_ice_connection_state(),
4274 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004275
4276 // According to RFC7675, if there is no response within 30 seconds then the
4277 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004278 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004279 constexpr int kConsentTimeout = 30000;
4280 for (const auto& caller_address : CallerAddresses()) {
4281 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4282 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004283 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004284 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4285 caller()->ice_connection_state(), kConsentTimeout,
4286 fake_clock);
4287 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4288 caller()->standardized_ice_connection_state(),
4289 kConsentTimeout, fake_clock);
4290
4291 // We need to manually close the peerconnections before the fake clock goes
4292 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4293 // return to using non-faked time.
4294 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4295 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
4296}
4297
4298// Tests that if the connection doesn't get set up properly we eventually reach
4299// the "failed" iceConnectionState.
4300TEST_P(PeerConnectionIntegrationIceStatesTest, IceStateSetupFailure) {
4301 rtc::ScopedFakeClock fake_clock;
4302 // Some things use a time of "0" as a special value, so we need to start out
4303 // the fake clock at a nonzero time.
4304 fake_clock.AdvanceTime(TimeDelta::seconds(1));
4305
4306 // Block connections to/from the caller and wait for ICE to become
4307 // disconnected.
4308 for (const auto& caller_address : CallerAddresses()) {
4309 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4310 }
4311
4312 ASSERT_TRUE(CreatePeerConnectionWrappers());
4313 ConnectFakeSignaling();
4314 SetPortAllocatorFlags();
4315 SetUpNetworkInterfaces();
4316 caller()->AddAudioVideoTracks();
4317 caller()->CreateAndSetAndSignalOffer();
4318
4319 // According to RFC7675, if there is no response within 30 seconds then the
4320 // peer should consider the other side to have rejected the connection. This
4321 // is signaled by the state transitioning to "failed".
4322 constexpr int kConsentTimeout = 30000;
4323 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4324 caller()->standardized_ice_connection_state(),
4325 kConsentTimeout, fake_clock);
4326
4327 // We need to manually close the peerconnections before the fake clock goes
4328 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4329 // return to using non-faked time.
4330 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4331 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
Steve Antonede9ca52017-10-16 13:04:27 -07004332}
4333
4334// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4335// and that the statistics in the metric observers are updated correctly.
4336TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4337 ASSERT_TRUE(CreatePeerConnectionWrappers());
4338 ConnectFakeSignaling();
4339 SetPortAllocatorFlags();
4340 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004341 caller()->AddAudioVideoTracks();
4342 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004343 caller()->CreateAndSetAndSignalOffer();
4344
4345 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4346
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004347 // TODO(bugs.webrtc.org/9456): Fix it.
4348 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4349 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4350 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4351 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004352 if (TestIPv6()) {
4353 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4354 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004355 EXPECT_EQ(0, num_best_ipv4);
4356 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004357 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004358 EXPECT_EQ(1, num_best_ipv4);
4359 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004360 }
4361
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004362 EXPECT_EQ(0, webrtc::metrics::NumEvents(
4363 "WebRTC.PeerConnection.CandidatePairType_UDP",
4364 webrtc::kIceCandidatePairHostHost));
4365 EXPECT_EQ(1, webrtc::metrics::NumEvents(
4366 "WebRTC.PeerConnection.CandidatePairType_UDP",
4367 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004368}
4369
4370constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4371 cricket::PORTALLOCATOR_DISABLE_STUN |
4372 cricket::PORTALLOCATOR_DISABLE_RELAY;
4373constexpr uint32_t kFlagsIPv6NoStun =
4374 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4375 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4376constexpr uint32_t kFlagsIPv4Stun =
4377 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4378
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004379INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004380 PeerConnectionIntegrationTest,
4381 PeerConnectionIntegrationIceStatesTest,
4382 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4383 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4384 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4385 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004386
deadbeef1dcb1642017-03-29 21:08:16 -07004387// This test sets up a call between two parties with audio and video.
4388// During the call, the caller restarts ICE and the test verifies that
4389// new ICE candidates are generated and audio and video still can flow, and the
4390// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004391TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004392 ASSERT_TRUE(CreatePeerConnectionWrappers());
4393 ConnectFakeSignaling();
4394 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004395 caller()->AddAudioVideoTracks();
4396 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004397 caller()->CreateAndSetAndSignalOffer();
4398 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4399 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4400 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004401 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4402 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004403
4404 // To verify that the ICE restart actually occurs, get
4405 // ufrag/password/candidates before and after restart.
4406 // Create an SDP string of the first audio candidate for both clients.
4407 const webrtc::IceCandidateCollection* audio_candidates_caller =
4408 caller()->pc()->local_description()->candidates(0);
4409 const webrtc::IceCandidateCollection* audio_candidates_callee =
4410 callee()->pc()->local_description()->candidates(0);
4411 ASSERT_GT(audio_candidates_caller->count(), 0u);
4412 ASSERT_GT(audio_candidates_callee->count(), 0u);
4413 std::string caller_candidate_pre_restart;
4414 ASSERT_TRUE(
4415 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4416 std::string callee_candidate_pre_restart;
4417 ASSERT_TRUE(
4418 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4419 const cricket::SessionDescription* desc =
4420 caller()->pc()->local_description()->description();
4421 std::string caller_ufrag_pre_restart =
4422 desc->transport_infos()[0].description.ice_ufrag;
4423 desc = callee()->pc()->local_description()->description();
4424 std::string callee_ufrag_pre_restart =
4425 desc->transport_infos()[0].description.ice_ufrag;
4426
Alex Drake00c7ecf2019-08-06 10:54:47 -07004427 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004428 // Have the caller initiate an ICE restart.
4429 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4430 caller()->CreateAndSetAndSignalOffer();
4431 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4432 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4433 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004434 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004435 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4436
4437 // Grab the ufrags/candidates again.
4438 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4439 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4440 ASSERT_GT(audio_candidates_caller->count(), 0u);
4441 ASSERT_GT(audio_candidates_callee->count(), 0u);
4442 std::string caller_candidate_post_restart;
4443 ASSERT_TRUE(
4444 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4445 std::string callee_candidate_post_restart;
4446 ASSERT_TRUE(
4447 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4448 desc = caller()->pc()->local_description()->description();
4449 std::string caller_ufrag_post_restart =
4450 desc->transport_infos()[0].description.ice_ufrag;
4451 desc = callee()->pc()->local_description()->description();
4452 std::string callee_ufrag_post_restart =
4453 desc->transport_infos()[0].description.ice_ufrag;
4454 // Sanity check that an ICE restart was actually negotiated in SDP.
4455 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4456 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4457 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4458 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07004459 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004460
4461 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004462 MediaExpectations media_expectations;
4463 media_expectations.ExpectBidirectionalAudioAndVideo();
4464 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004465}
4466
4467// Verify that audio/video can be received end-to-end when ICE renomination is
4468// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004469TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004470 PeerConnectionInterface::RTCConfiguration config;
4471 config.enable_ice_renomination = true;
4472 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4473 ConnectFakeSignaling();
4474 // Do normal offer/answer and wait for some frames to be received in each
4475 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004476 caller()->AddAudioVideoTracks();
4477 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004478 caller()->CreateAndSetAndSignalOffer();
4479 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4480 // Sanity check that ICE renomination was actually negotiated.
4481 const cricket::SessionDescription* desc =
4482 caller()->pc()->local_description()->description();
4483 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004484 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004485 }
4486 desc = callee()->pc()->local_description()->description();
4487 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004488 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004489 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004490 MediaExpectations media_expectations;
4491 media_expectations.ExpectBidirectionalAudioAndVideo();
4492 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004493}
4494
Steve Anton6f25b092017-10-23 09:39:20 -07004495// With a max bundle policy and RTCP muxing, adding a new media description to
4496// the connection should not affect ICE at all because the new media will use
4497// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004498TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004499 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004500 PeerConnectionInterface::RTCConfiguration config;
4501 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4502 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4503 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4504 config, PeerConnectionInterface::RTCConfiguration()));
4505 ConnectFakeSignaling();
4506
Steve Anton15324772018-01-16 10:26:49 -08004507 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004508 caller()->CreateAndSetAndSignalOffer();
4509 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004510 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4511 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004512
4513 caller()->clear_ice_connection_state_history();
4514
Steve Anton15324772018-01-16 10:26:49 -08004515 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004516 caller()->CreateAndSetAndSignalOffer();
4517 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4518
4519 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4520}
4521
deadbeef1dcb1642017-03-29 21:08:16 -07004522// This test sets up a call between two parties with audio and video. It then
4523// renegotiates setting the video m-line to "port 0", then later renegotiates
4524// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004525TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004526 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4527 ASSERT_TRUE(CreatePeerConnectionWrappers());
4528 ConnectFakeSignaling();
4529
4530 // Do initial negotiation, only sending media from the caller. Will result in
4531 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004532 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004533 caller()->CreateAndSetAndSignalOffer();
4534 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4535
4536 // Negotiate again, disabling the video "m=" section (the callee will set the
4537 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004538 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4539 PeerConnectionInterface::RTCOfferAnswerOptions options;
4540 options.offer_to_receive_video = 0;
4541 callee()->SetOfferAnswerOptions(options);
4542 } else {
4543 callee()->SetRemoteOfferHandler([this] {
4544 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4545 });
4546 }
deadbeef1dcb1642017-03-29 21:08:16 -07004547 caller()->CreateAndSetAndSignalOffer();
4548 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4549 // Sanity check that video "m=" section was actually rejected.
4550 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4551 callee()->pc()->local_description()->description());
4552 ASSERT_NE(nullptr, answer_video_content);
4553 ASSERT_TRUE(answer_video_content->rejected);
4554
4555 // Enable video and do negotiation again, making sure video is received
4556 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004557 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4558 PeerConnectionInterface::RTCOfferAnswerOptions options;
4559 options.offer_to_receive_video = 1;
4560 callee()->SetOfferAnswerOptions(options);
4561 } else {
4562 // The caller's transceiver is stopped, so we need to add another track.
4563 auto caller_transceiver =
4564 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4565 EXPECT_TRUE(caller_transceiver->stopped());
4566 caller()->AddVideoTrack();
4567 }
4568 callee()->AddVideoTrack();
4569 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004570 caller()->CreateAndSetAndSignalOffer();
4571 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004572
deadbeef1dcb1642017-03-29 21:08:16 -07004573 // Verify the caller receives frames from the newly added stream, and the
4574 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004575 MediaExpectations media_expectations;
4576 media_expectations.CalleeExpectsSomeAudio();
4577 media_expectations.ExpectBidirectionalVideo();
4578 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004579}
4580
deadbeef1dcb1642017-03-29 21:08:16 -07004581// This tests that if we negotiate after calling CreateSender but before we
4582// have a track, then set a track later, frames from the newly-set track are
4583// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004584TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004585 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4586 ASSERT_TRUE(CreatePeerConnectionWrappers());
4587 ConnectFakeSignaling();
4588 auto caller_audio_sender =
4589 caller()->pc()->CreateSender("audio", "caller_stream");
4590 auto caller_video_sender =
4591 caller()->pc()->CreateSender("video", "caller_stream");
4592 auto callee_audio_sender =
4593 callee()->pc()->CreateSender("audio", "callee_stream");
4594 auto callee_video_sender =
4595 callee()->pc()->CreateSender("video", "callee_stream");
4596 caller()->CreateAndSetAndSignalOffer();
4597 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4598 // Wait for ICE to complete, without any tracks being set.
4599 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4600 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4601 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4602 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4603 // Now set the tracks, and expect frames to immediately start flowing.
4604 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4605 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4606 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4607 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004608 MediaExpectations media_expectations;
4609 media_expectations.ExpectBidirectionalAudioAndVideo();
4610 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4611}
4612
4613// This tests that if we negotiate after calling AddTransceiver but before we
4614// have a track, then set a track later, frames from the newly-set tracks are
4615// received end-to-end.
4616TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4617 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4618 ASSERT_TRUE(CreatePeerConnectionWrappers());
4619 ConnectFakeSignaling();
4620 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4621 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4622 auto caller_audio_sender = audio_result.MoveValue()->sender();
4623 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4624 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4625 auto caller_video_sender = video_result.MoveValue()->sender();
4626 callee()->SetRemoteOfferHandler([this] {
4627 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4628 callee()->pc()->GetTransceivers()[0]->SetDirection(
4629 RtpTransceiverDirection::kSendRecv);
4630 callee()->pc()->GetTransceivers()[1]->SetDirection(
4631 RtpTransceiverDirection::kSendRecv);
4632 });
4633 caller()->CreateAndSetAndSignalOffer();
4634 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4635 // Wait for ICE to complete, without any tracks being set.
4636 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4637 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4638 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4639 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4640 // Now set the tracks, and expect frames to immediately start flowing.
4641 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4642 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4643 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4644 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4645 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4646 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4647 MediaExpectations media_expectations;
4648 media_expectations.ExpectBidirectionalAudioAndVideo();
4649 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004650}
4651
4652// This test verifies that a remote video track can be added via AddStream,
4653// and sent end-to-end. For this particular test, it's simply echoed back
4654// from the caller to the callee, rather than being forwarded to a third
4655// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004656TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004657 ASSERT_TRUE(CreatePeerConnectionWrappers());
4658 ConnectFakeSignaling();
4659 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004660 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004661 caller()->CreateAndSetAndSignalOffer();
4662 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004663 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004664
4665 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4666 // time).
4667 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4668 callee()->CreateAndSetAndSignalOffer();
4669 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4670
Seth Hampson2f0d7022018-02-20 11:54:42 -08004671 MediaExpectations media_expectations;
4672 media_expectations.ExpectBidirectionalVideo();
4673 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004674}
4675
4676// Test that we achieve the expected end-to-end connection time, using a
4677// fake clock and simulated latency on the media and signaling paths.
4678// We use a TURN<->TURN connection because this is usually the quickest to
4679// set up initially, especially when we're confident the connection will work
4680// and can start sending media before we get a STUN response.
4681//
4682// With various optimizations enabled, here are the network delays we expect to
4683// be on the critical path:
4684// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4685// signaling answer (with DTLS fingerprint).
4686// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4687// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4688// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004689TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004690 rtc::ScopedFakeClock fake_clock;
4691 // Some things use a time of "0" as a special value, so we need to start out
4692 // the fake clock at a nonzero time.
4693 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02004694 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07004695
4696 static constexpr int media_hop_delay_ms = 50;
4697 static constexpr int signaling_trip_delay_ms = 500;
4698 // For explanation of these values, see comment above.
4699 static constexpr int required_media_hops = 9;
4700 static constexpr int required_signaling_trips = 2;
4701 // For internal delays (such as posting an event asychronously).
4702 static constexpr int allowed_internal_delay_ms = 20;
4703 static constexpr int total_connection_time_ms =
4704 media_hop_delay_ms * required_media_hops +
4705 signaling_trip_delay_ms * required_signaling_trips +
4706 allowed_internal_delay_ms;
4707
4708 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4709 3478};
4710 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4711 0};
4712 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4713 3478};
4714 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4715 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004716 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4717 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004718
Seth Hampsonaed71642018-06-11 07:41:32 -07004719 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4720 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004721 // Bypass permission check on received packets so media can be sent before
4722 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004723 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4724 turn_server_1->set_enable_permission_checks(false);
4725 });
4726 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4727 turn_server_2->set_enable_permission_checks(false);
4728 });
deadbeef1dcb1642017-03-29 21:08:16 -07004729
4730 PeerConnectionInterface::RTCConfiguration client_1_config;
4731 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4732 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4733 ice_server_1.username = "test";
4734 ice_server_1.password = "test";
4735 client_1_config.servers.push_back(ice_server_1);
4736 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4737 client_1_config.presume_writable_when_fully_relayed = true;
4738
4739 PeerConnectionInterface::RTCConfiguration client_2_config;
4740 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4741 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4742 ice_server_2.username = "test";
4743 ice_server_2.password = "test";
4744 client_2_config.servers.push_back(ice_server_2);
4745 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4746 client_2_config.presume_writable_when_fully_relayed = true;
4747
4748 ASSERT_TRUE(
4749 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4750 // Set up the simulated delays.
4751 SetSignalingDelayMs(signaling_trip_delay_ms);
4752 ConnectFakeSignaling();
4753 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4754 virtual_socket_server()->UpdateDelayDistribution();
4755
4756 // Set "offer to receive audio/video" without adding any tracks, so we just
4757 // set up ICE/DTLS with no media.
4758 PeerConnectionInterface::RTCOfferAnswerOptions options;
4759 options.offer_to_receive_audio = 1;
4760 options.offer_to_receive_video = 1;
4761 caller()->SetOfferAnswerOptions(options);
4762 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004763 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4764 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004765 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4766 // If this is not done a DCHECK can be hit in ports.cc, because a large
4767 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07004768 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07004769}
4770
Jonas Orelandbdcee282017-10-10 14:01:40 +02004771// Verify that a TurnCustomizer passed in through RTCConfiguration
4772// is actually used by the underlying TURN candidate pair.
4773// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004774TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004775 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4776 3478};
4777 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4778 0};
4779 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4780 3478};
4781 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4782 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004783 CreateTurnServer(turn_server_1_internal_address,
4784 turn_server_1_external_address);
4785 CreateTurnServer(turn_server_2_internal_address,
4786 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004787
4788 PeerConnectionInterface::RTCConfiguration client_1_config;
4789 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4790 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4791 ice_server_1.username = "test";
4792 ice_server_1.password = "test";
4793 client_1_config.servers.push_back(ice_server_1);
4794 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004795 auto* customizer1 = CreateTurnCustomizer();
4796 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004797
4798 PeerConnectionInterface::RTCConfiguration client_2_config;
4799 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4800 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4801 ice_server_2.username = "test";
4802 ice_server_2.password = "test";
4803 client_2_config.servers.push_back(ice_server_2);
4804 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004805 auto* customizer2 = CreateTurnCustomizer();
4806 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004807
4808 ASSERT_TRUE(
4809 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4810 ConnectFakeSignaling();
4811
4812 // Set "offer to receive audio/video" without adding any tracks, so we just
4813 // set up ICE/DTLS with no media.
4814 PeerConnectionInterface::RTCOfferAnswerOptions options;
4815 options.offer_to_receive_audio = 1;
4816 options.offer_to_receive_video = 1;
4817 caller()->SetOfferAnswerOptions(options);
4818 caller()->CreateAndSetAndSignalOffer();
4819 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4820
Seth Hampsonaed71642018-06-11 07:41:32 -07004821 ExpectTurnCustomizerCountersIncremented(customizer1);
4822 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004823}
4824
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004825// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4826// send media between the caller and the callee.
4827TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4828 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4829 3478};
4830 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4831
4832 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004833 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4834 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004835
4836 webrtc::PeerConnectionInterface::IceServer ice_server;
4837 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4838 ice_server.username = "test";
4839 ice_server.password = "test";
4840
4841 PeerConnectionInterface::RTCConfiguration client_1_config;
4842 client_1_config.servers.push_back(ice_server);
4843 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4844
4845 PeerConnectionInterface::RTCConfiguration client_2_config;
4846 client_2_config.servers.push_back(ice_server);
4847 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4848
4849 ASSERT_TRUE(
4850 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4851
4852 // Do normal offer/answer and wait for ICE to complete.
4853 ConnectFakeSignaling();
4854 caller()->AddAudioVideoTracks();
4855 callee()->AddAudioVideoTracks();
4856 caller()->CreateAndSetAndSignalOffer();
4857 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4858 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4859 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4860
4861 MediaExpectations media_expectations;
4862 media_expectations.ExpectBidirectionalAudioAndVideo();
4863 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4864}
4865
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004866// Verify that a SSLCertificateVerifier passed in through
4867// PeerConnectionDependencies is actually used by the underlying SSL
4868// implementation to determine whether a certificate presented by the TURN
4869// server is accepted by the client. Note that openssladapter_unittest.cc
4870// contains more detailed, lower-level tests.
4871TEST_P(PeerConnectionIntegrationTest,
4872 SSLCertificateVerifierUsedForTurnConnections) {
4873 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4874 3478};
4875 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4876
4877 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4878 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004879 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4880 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004881
4882 webrtc::PeerConnectionInterface::IceServer ice_server;
4883 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4884 ice_server.username = "test";
4885 ice_server.password = "test";
4886
4887 PeerConnectionInterface::RTCConfiguration client_1_config;
4888 client_1_config.servers.push_back(ice_server);
4889 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4890
4891 PeerConnectionInterface::RTCConfiguration client_2_config;
4892 client_2_config.servers.push_back(ice_server);
4893 // Setting the type to kRelay forces the connection to go through a TURN
4894 // server.
4895 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4896
4897 // Get a copy to the pointer so we can verify calls later.
4898 rtc::TestCertificateVerifier* client_1_cert_verifier =
4899 new rtc::TestCertificateVerifier();
4900 client_1_cert_verifier->verify_certificate_ = true;
4901 rtc::TestCertificateVerifier* client_2_cert_verifier =
4902 new rtc::TestCertificateVerifier();
4903 client_2_cert_verifier->verify_certificate_ = true;
4904
4905 // Create the dependencies with the test certificate verifier.
4906 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4907 client_1_deps.tls_cert_verifier =
4908 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4909 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4910 client_2_deps.tls_cert_verifier =
4911 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4912
4913 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4914 client_1_config, std::move(client_1_deps), client_2_config,
4915 std::move(client_2_deps)));
4916 ConnectFakeSignaling();
4917
4918 // Set "offer to receive audio/video" without adding any tracks, so we just
4919 // set up ICE/DTLS with no media.
4920 PeerConnectionInterface::RTCOfferAnswerOptions options;
4921 options.offer_to_receive_audio = 1;
4922 options.offer_to_receive_video = 1;
4923 caller()->SetOfferAnswerOptions(options);
4924 caller()->CreateAndSetAndSignalOffer();
4925 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4926
4927 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4928 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004929}
4930
4931TEST_P(PeerConnectionIntegrationTest,
4932 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4933 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4934 3478};
4935 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4936
4937 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4938 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004939 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4940 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004941
4942 webrtc::PeerConnectionInterface::IceServer ice_server;
4943 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4944 ice_server.username = "test";
4945 ice_server.password = "test";
4946
4947 PeerConnectionInterface::RTCConfiguration client_1_config;
4948 client_1_config.servers.push_back(ice_server);
4949 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4950
4951 PeerConnectionInterface::RTCConfiguration client_2_config;
4952 client_2_config.servers.push_back(ice_server);
4953 // Setting the type to kRelay forces the connection to go through a TURN
4954 // server.
4955 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4956
4957 // Get a copy to the pointer so we can verify calls later.
4958 rtc::TestCertificateVerifier* client_1_cert_verifier =
4959 new rtc::TestCertificateVerifier();
4960 client_1_cert_verifier->verify_certificate_ = false;
4961 rtc::TestCertificateVerifier* client_2_cert_verifier =
4962 new rtc::TestCertificateVerifier();
4963 client_2_cert_verifier->verify_certificate_ = false;
4964
4965 // Create the dependencies with the test certificate verifier.
4966 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4967 client_1_deps.tls_cert_verifier =
4968 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4969 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4970 client_2_deps.tls_cert_verifier =
4971 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4972
4973 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4974 client_1_config, std::move(client_1_deps), client_2_config,
4975 std::move(client_2_deps)));
4976 ConnectFakeSignaling();
4977
4978 // Set "offer to receive audio/video" without adding any tracks, so we just
4979 // set up ICE/DTLS with no media.
4980 PeerConnectionInterface::RTCOfferAnswerOptions options;
4981 options.offer_to_receive_audio = 1;
4982 options.offer_to_receive_video = 1;
4983 caller()->SetOfferAnswerOptions(options);
4984 caller()->CreateAndSetAndSignalOffer();
4985 bool wait_res = true;
4986 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4987 // properly, should be able to just wait for a state of "failed" instead of
4988 // waiting a fixed 10 seconds.
4989 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4990 ASSERT_FALSE(wait_res);
4991
4992 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4993 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004994}
4995
deadbeefc964d0b2017-04-03 10:03:35 -07004996// Test that audio and video flow end-to-end when codec names don't use the
4997// expected casing, given that they're supposed to be case insensitive. To test
4998// this, all but one codec is removed from each media description, and its
4999// casing is changed.
5000//
5001// In the past, this has regressed and caused crashes/black video, due to the
5002// fact that code at some layers was doing case-insensitive comparisons and
5003// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005004TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07005005 ASSERT_TRUE(CreatePeerConnectionWrappers());
5006 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005007 caller()->AddAudioVideoTracks();
5008 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07005009
5010 // Remove all but one audio/video codec (opus and VP8), and change the
5011 // casing of the caller's generated offer.
5012 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
5013 cricket::AudioContentDescription* audio =
5014 GetFirstAudioContentDescription(description);
5015 ASSERT_NE(nullptr, audio);
5016 auto audio_codecs = audio->codecs();
5017 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
5018 [](const cricket::AudioCodec& codec) {
5019 return codec.name != "opus";
5020 }),
5021 audio_codecs.end());
5022 ASSERT_EQ(1u, audio_codecs.size());
5023 audio_codecs[0].name = "OpUs";
5024 audio->set_codecs(audio_codecs);
5025
5026 cricket::VideoContentDescription* video =
5027 GetFirstVideoContentDescription(description);
5028 ASSERT_NE(nullptr, video);
5029 auto video_codecs = video->codecs();
5030 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
5031 [](const cricket::VideoCodec& codec) {
5032 return codec.name != "VP8";
5033 }),
5034 video_codecs.end());
5035 ASSERT_EQ(1u, video_codecs.size());
5036 video_codecs[0].name = "vP8";
5037 video->set_codecs(video_codecs);
5038 });
5039
5040 caller()->CreateAndSetAndSignalOffer();
5041 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5042
5043 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005044 MediaExpectations media_expectations;
5045 media_expectations.ExpectBidirectionalAudioAndVideo();
5046 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07005047}
5048
Jonas Oreland49ac5952018-09-26 16:04:32 +02005049TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07005050 ASSERT_TRUE(CreatePeerConnectionWrappers());
5051 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005052 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07005053 caller()->CreateAndSetAndSignalOffer();
5054 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07005055 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005056 MediaExpectations media_expectations;
5057 media_expectations.CalleeExpectsSomeAudio(1);
5058 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02005059 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07005060 auto receiver = callee()->pc()->GetReceivers()[0];
5061 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005062 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07005063 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
5064 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02005065 sources[0].source_id());
5066 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
5067}
5068
5069TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
5070 ASSERT_TRUE(CreatePeerConnectionWrappers());
5071 ConnectFakeSignaling();
5072 caller()->AddVideoTrack();
5073 caller()->CreateAndSetAndSignalOffer();
5074 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5075 // Wait for one video frame to be received by the callee.
5076 MediaExpectations media_expectations;
5077 media_expectations.CalleeExpectsSomeVideo(1);
5078 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5079 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
5080 auto receiver = callee()->pc()->GetReceivers()[0];
5081 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
5082 auto sources = receiver->GetSources();
5083 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02005084 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02005085 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
5086 sources[0].source_id());
5087 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07005088}
5089
deadbeef2f425aa2017-04-14 10:41:32 -07005090// Test that if a track is removed and added again with a different stream ID,
5091// the new stream ID is successfully communicated in SDP and media continues to
5092// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005093// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
5094// it will not reuse a transceiver that has already been sending. After creating
5095// a new transceiver it tries to create an offer with two senders of the same
5096// track ids and it fails.
5097TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07005098 ASSERT_TRUE(CreatePeerConnectionWrappers());
5099 ConnectFakeSignaling();
5100
deadbeef2f425aa2017-04-14 10:41:32 -07005101 // Add track using stream 1, do offer/answer.
5102 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
5103 caller()->CreateLocalAudioTrack();
5104 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07005105 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07005106 caller()->CreateAndSetAndSignalOffer();
5107 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005108 {
5109 MediaExpectations media_expectations;
5110 media_expectations.CalleeExpectsSomeAudio(1);
5111 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5112 }
deadbeef2f425aa2017-04-14 10:41:32 -07005113 // Remove the sender, and create a new one with the new stream.
5114 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07005115 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07005116 caller()->CreateAndSetAndSignalOffer();
5117 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5118 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005119 {
5120 MediaExpectations media_expectations;
5121 media_expectations.CalleeExpectsSomeAudio();
5122 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5123 }
deadbeef2f425aa2017-04-14 10:41:32 -07005124}
5125
Seth Hampson2f0d7022018-02-20 11:54:42 -08005126TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02005127 ASSERT_TRUE(CreatePeerConnectionWrappers());
5128 ConnectFakeSignaling();
5129
Karl Wiberg918f50c2018-07-05 11:40:33 +02005130 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02005131 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
5132 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02005133 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01005134 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
5135 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02005136
Steve Anton15324772018-01-16 10:26:49 -08005137 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02005138 caller()->CreateAndSetAndSignalOffer();
5139 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5140}
5141
Steve Antonede9ca52017-10-16 13:04:27 -07005142// Test that if candidates are only signaled by applying full session
5143// descriptions (instead of using AddIceCandidate), the peers can connect to
5144// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005145TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07005146 ASSERT_TRUE(CreatePeerConnectionWrappers());
5147 // Each side will signal the session descriptions but not candidates.
5148 ConnectFakeSignalingForSdpOnly();
5149
5150 // Add audio video track and exchange the initial offer/answer with media
5151 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08005152 caller()->AddAudioVideoTracks();
5153 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07005154 caller()->CreateAndSetAndSignalOffer();
5155
5156 // Wait for all candidates to be gathered on both the caller and callee.
5157 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5158 caller()->ice_gathering_state(), kDefaultTimeout);
5159 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
5160 callee()->ice_gathering_state(), kDefaultTimeout);
5161
5162 // The candidates will now be included in the session description, so
5163 // signaling them will start the ICE connection.
5164 caller()->CreateAndSetAndSignalOffer();
5165 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5166
5167 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005168 MediaExpectations media_expectations;
5169 media_expectations.ExpectBidirectionalAudioAndVideo();
5170 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07005171}
5172
henrika5f6bf242017-11-01 11:06:56 +01005173// Test that SetAudioPlayout can be used to disable audio playout from the
5174// start, then later enable it. This may be useful, for example, if the caller
5175// needs to play a local ringtone until some event occurs, after which it
5176// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005177TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01005178 ASSERT_TRUE(CreatePeerConnectionWrappers());
5179 ConnectFakeSignaling();
5180
5181 // Set up audio-only call where audio playout is disabled on caller's side.
5182 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08005183 caller()->AddAudioTrack();
5184 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005185 caller()->CreateAndSetAndSignalOffer();
5186 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5187
5188 // Pump messages for a second.
5189 WAIT(false, 1000);
5190 // Since audio playout is disabled, the caller shouldn't have received
5191 // anything (at the playout level, at least).
5192 EXPECT_EQ(0, caller()->audio_frames_received());
5193 // As a sanity check, make sure the callee (for which playout isn't disabled)
5194 // did still see frames on its audio level.
5195 ASSERT_GT(callee()->audio_frames_received(), 0);
5196
5197 // Enable playout again, and ensure audio starts flowing.
5198 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005199 MediaExpectations media_expectations;
5200 media_expectations.ExpectBidirectionalAudio();
5201 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01005202}
5203
5204double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5205 auto report = pc->NewGetStats();
5206 auto track_stats_list =
5207 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5208 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5209 for (const auto* track_stats : track_stats_list) {
5210 if (track_stats->remote_source.is_defined() &&
5211 *track_stats->remote_source) {
5212 remote_track_stats = track_stats;
5213 break;
5214 }
5215 }
5216
5217 if (!remote_track_stats->total_audio_energy.is_defined()) {
5218 return 0.0;
5219 }
5220 return *remote_track_stats->total_audio_energy;
5221}
5222
5223// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5224// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005225TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005226 DisableAudioPlayoutStillGeneratesAudioStats) {
5227 ASSERT_TRUE(CreatePeerConnectionWrappers());
5228 ConnectFakeSignaling();
5229
5230 // Set up audio-only call where playout is disabled but audio-processing is
5231 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005232 caller()->AddAudioTrack();
5233 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005234 caller()->pc()->SetAudioPlayout(false);
5235
5236 caller()->CreateAndSetAndSignalOffer();
5237 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5238
5239 // Wait for the callee to receive audio stats.
5240 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5241}
5242
henrika4f167df2017-11-01 14:45:55 +01005243// Test that SetAudioRecording can be used to disable audio recording from the
5244// start, then later enable it. This may be useful, for example, if the caller
5245// wants to ensure that no audio resources are active before a certain state
5246// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005247TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005248 ASSERT_TRUE(CreatePeerConnectionWrappers());
5249 ConnectFakeSignaling();
5250
5251 // Set up audio-only call where audio recording is disabled on caller's side.
5252 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005253 caller()->AddAudioTrack();
5254 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005255 caller()->CreateAndSetAndSignalOffer();
5256 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5257
5258 // Pump messages for a second.
5259 WAIT(false, 1000);
5260 // Since caller has disabled audio recording, the callee shouldn't have
5261 // received anything.
5262 EXPECT_EQ(0, callee()->audio_frames_received());
5263 // As a sanity check, make sure the caller did still see frames on its
5264 // audio level since audio recording is enabled on the calle side.
5265 ASSERT_GT(caller()->audio_frames_received(), 0);
5266
5267 // Enable audio recording again, and ensure audio starts flowing.
5268 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005269 MediaExpectations media_expectations;
5270 media_expectations.ExpectBidirectionalAudio();
5271 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005272}
5273
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005274// Test that after closing PeerConnections, they stop sending any packets (ICE,
5275// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005276TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005277 // Set up audio/video/data, wait for some frames to be received.
5278 ASSERT_TRUE(CreatePeerConnectionWrappers());
5279 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005280 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005281#ifdef HAVE_SCTP
5282 caller()->CreateDataChannel();
5283#endif
5284 caller()->CreateAndSetAndSignalOffer();
5285 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005286 MediaExpectations media_expectations;
5287 media_expectations.CalleeExpectsSomeAudioAndVideo();
5288 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005289 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005290 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005291 // Pump messages for a second, and ensure no new packets end up sent.
5292 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5293 WAIT(false, 1000);
5294 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5295 EXPECT_EQ(sent_packets_a, sent_packets_b);
5296}
5297
Steve Anton7eca0932018-03-30 15:18:41 -07005298// Test that transport stats are generated by the RTCStatsCollector for a
5299// connection that only involves data channels. This is a regression test for
5300// crbug.com/826972.
5301#ifdef HAVE_SCTP
5302TEST_P(PeerConnectionIntegrationTest,
5303 TransportStatsReportedForDataChannelOnlyConnection) {
5304 ASSERT_TRUE(CreatePeerConnectionWrappers());
5305 ConnectFakeSignaling();
5306 caller()->CreateDataChannel();
5307
5308 caller()->CreateAndSetAndSignalOffer();
5309 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5310 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5311
5312 auto caller_report = caller()->NewGetStats();
5313 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5314 auto callee_report = callee()->NewGetStats();
5315 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5316}
5317#endif // HAVE_SCTP
5318
Qingsi Wang7685e862018-06-11 20:15:46 -07005319TEST_P(PeerConnectionIntegrationTest,
5320 IceEventsGeneratedAndLoggedInRtcEventLog) {
5321 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5322 ConnectFakeSignaling();
5323 PeerConnectionInterface::RTCOfferAnswerOptions options;
5324 options.offer_to_receive_audio = 1;
5325 caller()->SetOfferAnswerOptions(options);
5326 caller()->CreateAndSetAndSignalOffer();
5327 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5328 ASSERT_NE(nullptr, caller()->event_log_factory());
5329 ASSERT_NE(nullptr, callee()->event_log_factory());
5330 webrtc::FakeRtcEventLog* caller_event_log =
5331 static_cast<webrtc::FakeRtcEventLog*>(
5332 caller()->event_log_factory()->last_log_created());
5333 webrtc::FakeRtcEventLog* callee_event_log =
5334 static_cast<webrtc::FakeRtcEventLog*>(
5335 callee()->event_log_factory()->last_log_created());
5336 ASSERT_NE(nullptr, caller_event_log);
5337 ASSERT_NE(nullptr, callee_event_log);
5338 int caller_ice_config_count = caller_event_log->GetEventCount(
5339 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5340 int caller_ice_event_count = caller_event_log->GetEventCount(
5341 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5342 int callee_ice_config_count = callee_event_log->GetEventCount(
5343 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5344 int callee_ice_event_count = callee_event_log->GetEventCount(
5345 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5346 EXPECT_LT(0, caller_ice_config_count);
5347 EXPECT_LT(0, caller_ice_event_count);
5348 EXPECT_LT(0, callee_ice_config_count);
5349 EXPECT_LT(0, callee_ice_event_count);
5350}
5351
Qingsi Wangc129c352019-04-18 10:41:58 -07005352TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005353 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5354 3478};
5355 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5356
5357 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5358
5359 webrtc::PeerConnectionInterface::IceServer ice_server;
5360 ice_server.urls.push_back("turn:88.88.88.0:3478");
5361 ice_server.username = "test";
5362 ice_server.password = "test";
5363
5364 PeerConnectionInterface::RTCConfiguration caller_config;
5365 caller_config.servers.push_back(ice_server);
5366 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5367 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005368 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005369
5370 PeerConnectionInterface::RTCConfiguration callee_config;
5371 callee_config.servers.push_back(ice_server);
5372 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5373 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005374 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005375
5376 ASSERT_TRUE(
5377 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5378
5379 // Do normal offer/answer and wait for ICE to complete.
5380 ConnectFakeSignaling();
5381 caller()->AddAudioVideoTracks();
5382 callee()->AddAudioVideoTracks();
5383 caller()->CreateAndSetAndSignalOffer();
5384 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5385 // Since we are doing continual gathering, the ICE transport does not reach
5386 // kIceGatheringComplete (see
5387 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5388 // kIceConnectionComplete.
5389 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5390 caller()->ice_connection_state(), kDefaultTimeout);
5391 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5392 callee()->ice_connection_state(), kDefaultTimeout);
5393 // Note that we cannot use the metric
5394 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5395 // metric is only populated when we reach kIceConnectionComplete in the
5396 // current implementation.
5397 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5398 caller()->last_candidate_gathered().type());
5399 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5400 callee()->last_candidate_gathered().type());
5401
5402 // Loosen the caller's candidate filter.
5403 caller_config = caller()->pc()->GetConfiguration();
5404 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5405 caller()->pc()->SetConfiguration(caller_config);
5406 // We should have gathered a new host candidate.
5407 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5408 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5409
5410 // Loosen the callee's candidate filter.
5411 callee_config = callee()->pc()->GetConfiguration();
5412 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5413 callee()->pc()->SetConfiguration(callee_config);
5414 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5415 callee()->last_candidate_gathered().type(), kDefaultTimeout);
5416}
5417
Eldar Relloda13ea22019-06-01 12:23:43 +03005418TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03005419 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5420 3478};
5421 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5422
5423 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5424
5425 webrtc::PeerConnectionInterface::IceServer ice_server;
5426 ice_server.urls.push_back("turn:88.88.88.0:3478");
5427 ice_server.username = "test";
5428 ice_server.password = "123";
5429
5430 PeerConnectionInterface::RTCConfiguration caller_config;
5431 caller_config.servers.push_back(ice_server);
5432 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5433 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5434
5435 PeerConnectionInterface::RTCConfiguration callee_config;
5436 callee_config.servers.push_back(ice_server);
5437 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5438 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5439
5440 ASSERT_TRUE(
5441 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5442
5443 // Do normal offer/answer and wait for ICE to complete.
5444 ConnectFakeSignaling();
5445 caller()->AddAudioVideoTracks();
5446 callee()->AddAudioVideoTracks();
5447 caller()->CreateAndSetAndSignalOffer();
5448 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5449 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5450 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5451 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
5452 EXPECT_NE(std::string::npos,
5453 caller()->error_event().host_candidate.find(":"));
5454}
5455
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005456INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5457 PeerConnectionIntegrationTest,
5458 Values(SdpSemantics::kPlanB,
5459 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005460
Steve Anton74255ff2018-01-24 18:32:57 -08005461// Tests that verify interoperability between Plan B and Unified Plan
5462// PeerConnections.
5463class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08005464 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08005465 public ::testing::WithParamInterface<
5466 std::tuple<SdpSemantics, SdpSemantics>> {
5467 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08005468 // Setting the SdpSemantics for the base test to kDefault does not matter
5469 // because we specify not to use the test semantics when creating
5470 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08005471 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07005472 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08005473 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08005474 callee_semantics_(std::get<1>(GetParam())) {}
5475
5476 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07005477 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5478 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08005479 }
5480
5481 const SdpSemantics caller_semantics_;
5482 const SdpSemantics callee_semantics_;
5483};
5484
5485TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5486 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5487 ConnectFakeSignaling();
5488
5489 caller()->CreateAndSetAndSignalOffer();
5490 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5491}
5492
5493TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
5494 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5495 ConnectFakeSignaling();
5496 auto audio_sender = caller()->AddAudioTrack();
5497
5498 caller()->CreateAndSetAndSignalOffer();
5499 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5500
5501 // Verify that one audio receiver has been created on the remote and that it
5502 // has the same track ID as the sending track.
5503 auto receivers = callee()->pc()->GetReceivers();
5504 ASSERT_EQ(1u, receivers.size());
5505 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
5506 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
5507
Seth Hampson2f0d7022018-02-20 11:54:42 -08005508 MediaExpectations media_expectations;
5509 media_expectations.CalleeExpectsSomeAudio();
5510 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005511}
5512
5513TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
5514 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5515 ConnectFakeSignaling();
5516 auto video_sender = caller()->AddVideoTrack();
5517 auto audio_sender = caller()->AddAudioTrack();
5518
5519 caller()->CreateAndSetAndSignalOffer();
5520 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5521
5522 // Verify that one audio and one video receiver have been created on the
5523 // remote and that they have the same track IDs as the sending tracks.
5524 auto audio_receivers =
5525 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5526 ASSERT_EQ(1u, audio_receivers.size());
5527 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5528 auto video_receivers =
5529 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5530 ASSERT_EQ(1u, video_receivers.size());
5531 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5532
Seth Hampson2f0d7022018-02-20 11:54:42 -08005533 MediaExpectations media_expectations;
5534 media_expectations.CalleeExpectsSomeAudioAndVideo();
5535 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005536}
5537
5538TEST_P(PeerConnectionIntegrationInteropTest,
5539 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5540 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5541 ConnectFakeSignaling();
5542 caller()->AddAudioVideoTracks();
5543 callee()->AddAudioVideoTracks();
5544
5545 caller()->CreateAndSetAndSignalOffer();
5546 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5547
Seth Hampson2f0d7022018-02-20 11:54:42 -08005548 MediaExpectations media_expectations;
5549 media_expectations.ExpectBidirectionalAudioAndVideo();
5550 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005551}
5552
5553TEST_P(PeerConnectionIntegrationInteropTest,
5554 ReverseRolesOneAudioLocalToOneVideoRemote) {
5555 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5556 ConnectFakeSignaling();
5557 caller()->AddAudioTrack();
5558 callee()->AddVideoTrack();
5559
5560 caller()->CreateAndSetAndSignalOffer();
5561 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5562
5563 // Verify that only the audio track has been negotiated.
5564 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5565 // Might also check that the callee's NegotiationNeeded flag is set.
5566
5567 // Reverse roles.
5568 callee()->CreateAndSetAndSignalOffer();
5569 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5570
Seth Hampson2f0d7022018-02-20 11:54:42 -08005571 MediaExpectations media_expectations;
5572 media_expectations.CallerExpectsSomeVideo();
5573 media_expectations.CalleeExpectsSomeAudio();
5574 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005575}
5576
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005577INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07005578 PeerConnectionIntegrationTest,
5579 PeerConnectionIntegrationInteropTest,
5580 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5581 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5582
5583// Test that if the Unified Plan side offers two video tracks then the Plan B
5584// side will only see the first one and ignore the second.
5585TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005586 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5587 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005588 ConnectFakeSignaling();
5589 auto first_sender = caller()->AddVideoTrack();
5590 caller()->AddVideoTrack();
5591
5592 caller()->CreateAndSetAndSignalOffer();
5593 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5594
5595 // Verify that there is only one receiver and it corresponds to the first
5596 // added track.
5597 auto receivers = callee()->pc()->GetReceivers();
5598 ASSERT_EQ(1u, receivers.size());
5599 EXPECT_TRUE(receivers[0]->track()->enabled());
5600 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5601
Seth Hampson2f0d7022018-02-20 11:54:42 -08005602 MediaExpectations media_expectations;
5603 media_expectations.CalleeExpectsSomeVideo();
5604 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005605}
5606
Steve Anton2bed3972019-01-04 17:04:30 -08005607// Test that if the initial offer tagged BUNDLE section is rejected due to its
5608// associated RtpTransceiver being stopped and another transceiver is added,
5609// then renegotiation causes the callee to receive the new video track without
5610// error.
5611// This is a regression test for bugs.webrtc.org/9954
5612TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5613 ReOfferWithStoppedBundleTaggedTransceiver) {
5614 RTCConfiguration config;
5615 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5616 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5617 ConnectFakeSignaling();
5618 auto audio_transceiver_or_error =
5619 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5620 ASSERT_TRUE(audio_transceiver_or_error.ok());
5621 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5622
5623 caller()->CreateAndSetAndSignalOffer();
5624 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5625 {
5626 MediaExpectations media_expectations;
5627 media_expectations.CalleeExpectsSomeAudio();
5628 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5629 }
5630
5631 audio_transceiver->Stop();
5632 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5633
5634 caller()->CreateAndSetAndSignalOffer();
5635 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5636 {
5637 MediaExpectations media_expectations;
5638 media_expectations.CalleeExpectsSomeVideo();
5639 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5640 }
5641}
5642
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005643#ifdef HAVE_SCTP
5644
5645TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5646 EndToEndCallWithBundledSctpDataChannel) {
5647 ASSERT_TRUE(CreatePeerConnectionWrappers());
5648 ConnectFakeSignaling();
5649 caller()->CreateDataChannel();
5650 caller()->AddAudioVideoTracks();
5651 callee()->AddAudioVideoTracks();
5652 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
5653 caller()->CreateAndSetAndSignalOffer();
5654 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5655 // Ensure that media and data are multiplexed on the same DTLS transport.
5656 // This only works on Unified Plan, because transports are not exposed in plan
5657 // B.
5658 auto sctp_info = caller()->pc()->GetSctpTransport()->Information();
5659 EXPECT_EQ(sctp_info.dtls_transport(),
5660 caller()->pc()->GetSenders()[0]->dtls_transport());
5661}
5662
5663#endif // HAVE_SCTP
5664
deadbeef1dcb1642017-03-29 21:08:16 -07005665} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01005666} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07005667
5668#endif // if !defined(THREAD_SANITIZER)