blob: 78263b7ca45755d775a0d3c600a48d18b748037d [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));
777 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800778 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
779 RemoveUnusedVideoRenderers();
780 }
deadbeef1dcb1642017-03-29 21:08:16 -0700781 // As mentioned above, we need to send the message immediately after
782 // SetLocalDescription.
783 SendSdpMessage(type, sdp);
784 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
785 return true;
786 }
787
788 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
789 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
790 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100791 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700792 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800793 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
794 RemoveUnusedVideoRenderers();
795 }
deadbeef1dcb1642017-03-29 21:08:16 -0700796 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
797 return observer->result();
798 }
799
Seth Hampson2f0d7022018-02-20 11:54:42 -0800800 // This is a work around to remove unused fake_video_renderers from
801 // transceivers that have either stopped or are no longer receiving.
802 void RemoveUnusedVideoRenderers() {
803 auto transceivers = pc()->GetTransceivers();
804 for (auto& transceiver : transceivers) {
805 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
806 continue;
807 }
808 // Remove fake video renderers from any stopped transceivers.
809 if (transceiver->stopped()) {
810 auto it =
811 fake_video_renderers_.find(transceiver->receiver()->track()->id());
812 if (it != fake_video_renderers_.end()) {
813 fake_video_renderers_.erase(it);
814 }
815 }
816 // Remove fake video renderers from any transceivers that are no longer
817 // receiving.
818 if ((transceiver->current_direction() &&
819 !webrtc::RtpTransceiverDirectionHasRecv(
820 *transceiver->current_direction()))) {
821 auto it =
822 fake_video_renderers_.find(transceiver->receiver()->track()->id());
823 if (it != fake_video_renderers_.end()) {
824 fake_video_renderers_.erase(it);
825 }
826 }
827 }
828 }
829
deadbeef1dcb1642017-03-29 21:08:16 -0700830 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
831 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800832 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700833 if (signaling_delay_ms_ == 0) {
834 RelaySdpMessageIfReceiverExists(type, msg);
835 } else {
836 invoker_.AsyncInvokeDelayed<void>(
837 RTC_FROM_HERE, rtc::Thread::Current(),
838 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
839 this, type, msg),
840 signaling_delay_ms_);
841 }
842 }
843
Steve Antona3a92c22017-12-07 10:27:41 -0800844 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700845 if (signaling_message_receiver_) {
846 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
847 }
848 }
849
850 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
851 // default).
852 void SendIceMessage(const std::string& sdp_mid,
853 int sdp_mline_index,
854 const std::string& msg) {
855 if (signaling_delay_ms_ == 0) {
856 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
857 } else {
858 invoker_.AsyncInvokeDelayed<void>(
859 RTC_FROM_HERE, rtc::Thread::Current(),
860 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
861 this, sdp_mid, sdp_mline_index, msg),
862 signaling_delay_ms_);
863 }
864 }
865
866 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
867 int sdp_mline_index,
868 const std::string& msg) {
869 if (signaling_message_receiver_) {
870 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
871 msg);
872 }
873 }
874
875 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800876 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
877 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700878 HandleIncomingOffer(msg);
879 } else {
880 HandleIncomingAnswer(msg);
881 }
882 }
883
884 void ReceiveIceMessage(const std::string& sdp_mid,
885 int sdp_mline_index,
886 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100887 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700888 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
889 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
890 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
891 }
892
893 // PeerConnectionObserver callbacks.
894 void OnSignalingChange(
895 webrtc::PeerConnectionInterface::SignalingState new_state) override {
896 EXPECT_EQ(pc()->signaling_state(), new_state);
897 }
Steve Anton15324772018-01-16 10:26:49 -0800898 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
899 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
900 streams) override {
901 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
902 rtc::scoped_refptr<VideoTrackInterface> video_track(
903 static_cast<VideoTrackInterface*>(receiver->track().get()));
904 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700905 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800906 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200907 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700908 }
909 }
Steve Anton15324772018-01-16 10:26:49 -0800910 void OnRemoveTrack(
911 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
912 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
913 auto it = fake_video_renderers_.find(receiver->track()->id());
914 RTC_DCHECK(it != fake_video_renderers_.end());
915 fake_video_renderers_.erase(it);
916 }
917 }
deadbeef1dcb1642017-03-29 21:08:16 -0700918 void OnRenegotiationNeeded() override {}
919 void OnIceConnectionChange(
920 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
921 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700922 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700923 }
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100924 void OnStandardizedIceConnectionChange(
925 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
926 standardized_ice_connection_state_history_.push_back(new_state);
927 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200928 void OnConnectionChange(
929 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
930 peer_connection_state_history_.push_back(new_state);
931 }
932
deadbeef1dcb1642017-03-29 21:08:16 -0700933 void OnIceGatheringChange(
934 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700935 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700936 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700937 }
Alex Drake00c7ecf2019-08-06 10:54:47 -0700938
939 void OnIceSelectedCandidatePairChanged(
940 const cricket::CandidatePairChangeEvent& event) {
941 ice_candidate_pair_change_history_.push_back(event);
942 }
deadbeef1dcb1642017-03-29 21:08:16 -0700943 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100944 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700945
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800946 if (remote_async_resolver_) {
947 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800948 if (local_candidate.address().IsUnresolvedIP()) {
949 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
950 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700951 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800952 local_candidate.address().hostname());
953 RTC_DCHECK(!resolved_ip.IsNil());
954 resolved_addr.SetResolvedIP(resolved_ip);
955 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
956 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
957 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700958 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700959 }
960
deadbeef1dcb1642017-03-29 21:08:16 -0700961 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800962 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700963 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700964 // Remote party may be deleted.
965 return;
966 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800967 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700968 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700969 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300970 void OnIceCandidateError(const std::string& host_candidate,
971 const std::string& url,
972 int error_code,
973 const std::string& error_text) override {
974 error_event_ = cricket::IceCandidateErrorEvent(host_candidate, url,
975 error_code, error_text);
976 }
deadbeef1dcb1642017-03-29 21:08:16 -0700977 void OnDataChannel(
978 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100979 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700980 data_channel_ = data_channel;
981 data_observer_.reset(new MockDataChannelObserver(data_channel));
982 }
983
deadbeef1dcb1642017-03-29 21:08:16 -0700984 std::string debug_name_;
985
986 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -0700987 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
988 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -0700989
990 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
991 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
992 peer_connection_factory_;
993
Steve Antonede9ca52017-10-16 13:04:27 -0700994 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700995 // Needed to keep track of number of frames sent.
996 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
997 // Needed to keep track of number of frames received.
998 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
999 fake_video_renderers_;
1000 // Needed to ensure frames aren't received for removed tracks.
1001 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1002 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001003
1004 // For remote peer communication.
1005 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1006 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001007 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001008 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001009 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001010
Niels Möller5c7efe72018-05-11 10:34:46 +02001011 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001012 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001013 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1014 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001015 // |local_video_renderer_| attached to the first created local video track.
1016 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1017
Seth Hampson2f0d7022018-02-20 11:54:42 -08001018 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001019 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1020 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1021 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001022 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001023 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001024 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1025 std::unique_ptr<MockDataChannelObserver> data_observer_;
1026
1027 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1028
Steve Antonede9ca52017-10-16 13:04:27 -07001029 std::vector<PeerConnectionInterface::IceConnectionState>
1030 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001031 std::vector<PeerConnectionInterface::IceConnectionState>
1032 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001033 std::vector<PeerConnectionInterface::PeerConnectionState>
1034 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001035 std::vector<PeerConnectionInterface::IceGatheringState>
1036 ice_gathering_state_history_;
Alex Drake00c7ecf2019-08-06 10:54:47 -07001037 std::vector<cricket::CandidatePairChangeEvent>
1038 ice_candidate_pair_change_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001039
Qingsi Wang7685e862018-06-11 20:15:46 -07001040 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1041
deadbeef1dcb1642017-03-29 21:08:16 -07001042 rtc::AsyncInvoker invoker_;
1043
Seth Hampson2f0d7022018-02-20 11:54:42 -08001044 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001045};
1046
Elad Alon99c3fe52017-10-13 16:29:40 +02001047class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1048 public:
1049 virtual ~MockRtcEventLogOutput() = default;
1050 MOCK_CONST_METHOD0(IsActive, bool());
1051 MOCK_METHOD1(Write, bool(const std::string&));
1052};
1053
Seth Hampson2f0d7022018-02-20 11:54:42 -08001054// This helper object is used for both specifying how many audio/video frames
1055// are expected to be received for a caller/callee. It provides helper functions
1056// to specify these expectations. The object initially starts in a state of no
1057// expectations.
1058class MediaExpectations {
1059 public:
1060 enum ExpectFrames {
1061 kExpectSomeFrames,
1062 kExpectNoFrames,
1063 kNoExpectation,
1064 };
1065
1066 void ExpectBidirectionalAudioAndVideo() {
1067 ExpectBidirectionalAudio();
1068 ExpectBidirectionalVideo();
1069 }
1070
1071 void ExpectBidirectionalAudio() {
1072 CallerExpectsSomeAudio();
1073 CalleeExpectsSomeAudio();
1074 }
1075
1076 void ExpectNoAudio() {
1077 CallerExpectsNoAudio();
1078 CalleeExpectsNoAudio();
1079 }
1080
1081 void ExpectBidirectionalVideo() {
1082 CallerExpectsSomeVideo();
1083 CalleeExpectsSomeVideo();
1084 }
1085
1086 void ExpectNoVideo() {
1087 CallerExpectsNoVideo();
1088 CalleeExpectsNoVideo();
1089 }
1090
1091 void CallerExpectsSomeAudioAndVideo() {
1092 CallerExpectsSomeAudio();
1093 CallerExpectsSomeVideo();
1094 }
1095
1096 void CalleeExpectsSomeAudioAndVideo() {
1097 CalleeExpectsSomeAudio();
1098 CalleeExpectsSomeVideo();
1099 }
1100
1101 // Caller's audio functions.
1102 void CallerExpectsSomeAudio(
1103 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1104 caller_audio_expectation_ = kExpectSomeFrames;
1105 caller_audio_frames_expected_ = expected_audio_frames;
1106 }
1107
1108 void CallerExpectsNoAudio() {
1109 caller_audio_expectation_ = kExpectNoFrames;
1110 caller_audio_frames_expected_ = 0;
1111 }
1112
1113 // Caller's video functions.
1114 void CallerExpectsSomeVideo(
1115 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1116 caller_video_expectation_ = kExpectSomeFrames;
1117 caller_video_frames_expected_ = expected_video_frames;
1118 }
1119
1120 void CallerExpectsNoVideo() {
1121 caller_video_expectation_ = kExpectNoFrames;
1122 caller_video_frames_expected_ = 0;
1123 }
1124
1125 // Callee's audio functions.
1126 void CalleeExpectsSomeAudio(
1127 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1128 callee_audio_expectation_ = kExpectSomeFrames;
1129 callee_audio_frames_expected_ = expected_audio_frames;
1130 }
1131
1132 void CalleeExpectsNoAudio() {
1133 callee_audio_expectation_ = kExpectNoFrames;
1134 callee_audio_frames_expected_ = 0;
1135 }
1136
1137 // Callee's video functions.
1138 void CalleeExpectsSomeVideo(
1139 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1140 callee_video_expectation_ = kExpectSomeFrames;
1141 callee_video_frames_expected_ = expected_video_frames;
1142 }
1143
1144 void CalleeExpectsNoVideo() {
1145 callee_video_expectation_ = kExpectNoFrames;
1146 callee_video_frames_expected_ = 0;
1147 }
1148
1149 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1150 ExpectFrames caller_video_expectation_ = kNoExpectation;
1151 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1152 ExpectFrames callee_video_expectation_ = kNoExpectation;
1153 int caller_audio_frames_expected_ = 0;
1154 int caller_video_frames_expected_ = 0;
1155 int callee_audio_frames_expected_ = 0;
1156 int callee_video_frames_expected_ = 0;
1157};
1158
deadbeef1dcb1642017-03-29 21:08:16 -07001159// Tests two PeerConnections connecting to each other end-to-end, using a
1160// virtual network, fake A/V capture and fake encoder/decoders. The
1161// PeerConnections share the threads/socket servers, but use separate versions
1162// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001163class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001164 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001165 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1166 : sdp_semantics_(sdp_semantics),
1167 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001168 fss_(new rtc::FirewallSocketServer(ss_.get())),
1169 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001170 worker_thread_(rtc::Thread::Create()),
1171 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001172 network_thread_->SetName("PCNetworkThread", this);
1173 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001174 RTC_CHECK(network_thread_->Start());
1175 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001176 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001177 }
1178
Seth Hampson2f0d7022018-02-20 11:54:42 -08001179 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001180 // The PeerConnections should deleted before the TurnCustomizers.
1181 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1182 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1183 // that the TurnCustomizer outlives the life of the PeerConnection or else
1184 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001185 if (caller_) {
1186 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001187 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001188 }
1189 if (callee_) {
1190 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001191 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001192 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001193
1194 // If turn servers were created for the test they need to be destroyed on
1195 // the network thread.
1196 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1197 turn_servers_.clear();
1198 turn_customizers_.clear();
1199 });
deadbeef1dcb1642017-03-29 21:08:16 -07001200 }
1201
1202 bool SignalingStateStable() {
1203 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1204 }
1205
deadbeef71452802017-05-07 17:21:01 -07001206 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001207 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1208 // are connected. This is an important distinction. Once we have separate
1209 // ICE and DTLS state, this check needs to use the DTLS state.
1210 return (callee()->ice_connection_state() ==
1211 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1212 callee()->ice_connection_state() ==
1213 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1214 (caller()->ice_connection_state() ==
1215 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1216 caller()->ice_connection_state() ==
1217 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001218 }
1219
Qingsi Wang7685e862018-06-11 20:15:46 -07001220 // When |event_log_factory| is null, the default implementation of the event
1221 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001222 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1223 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001224 const PeerConnectionFactory::Options* options,
1225 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001226 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001227 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1228 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001229 RTCConfiguration modified_config;
1230 if (config) {
1231 modified_config = *config;
1232 }
Steve Anton3acffc32018-04-12 17:21:03 -07001233 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001234 if (!dependencies.cert_generator) {
1235 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001236 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001237 }
1238 std::unique_ptr<PeerConnectionWrapper> client(
1239 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001240
Niels Möllerf06f9232018-08-07 12:32:18 +02001241 if (!client->Init(options, &modified_config, std::move(dependencies),
1242 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001243 std::move(event_log_factory),
1244 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001245 return nullptr;
1246 }
1247 return client;
1248 }
1249
Qingsi Wang7685e862018-06-11 20:15:46 -07001250 std::unique_ptr<PeerConnectionWrapper>
1251 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1252 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001253 const PeerConnectionFactory::Options* options,
1254 const RTCConfiguration* config,
1255 webrtc::PeerConnectionDependencies dependencies) {
1256 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1257 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001258 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001259 std::move(dependencies),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001260 std::move(event_log_factory),
1261 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001262 }
1263
deadbeef1dcb1642017-03-29 21:08:16 -07001264 bool CreatePeerConnectionWrappers() {
1265 return CreatePeerConnectionWrappersWithConfig(
1266 PeerConnectionInterface::RTCConfiguration(),
1267 PeerConnectionInterface::RTCConfiguration());
1268 }
1269
Steve Anton3acffc32018-04-12 17:21:03 -07001270 bool CreatePeerConnectionWrappersWithSdpSemantics(
1271 SdpSemantics caller_semantics,
1272 SdpSemantics callee_semantics) {
1273 // Can't specify the sdp_semantics in the passed-in configuration since it
1274 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1275 // stored in sdp_semantics_. So get around this by modifying the instance
1276 // variable before calling CreatePeerConnectionWrapper for the caller and
1277 // callee PeerConnections.
1278 SdpSemantics original_semantics = sdp_semantics_;
1279 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001280 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001281 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001282 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001283 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001284 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001285 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001286 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001287 sdp_semantics_ = original_semantics;
1288 return caller_ && callee_;
1289 }
1290
deadbeef1dcb1642017-03-29 21:08:16 -07001291 bool CreatePeerConnectionWrappersWithConfig(
1292 const PeerConnectionInterface::RTCConfiguration& caller_config,
1293 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001294 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001295 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001296 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1297 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001298 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001299 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001300 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1301 /*media_transport_factory=*/nullptr);
1302 return caller_ && callee_;
1303 }
1304
1305 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1306 const PeerConnectionInterface::RTCConfiguration& caller_config,
1307 const PeerConnectionInterface::RTCConfiguration& callee_config,
1308 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1309 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
1310 caller_ =
1311 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1312 webrtc::PeerConnectionDependencies(nullptr),
1313 nullptr, std::move(caller_factory));
1314 callee_ =
1315 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1316 webrtc::PeerConnectionDependencies(nullptr),
1317 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001318 return caller_ && callee_;
1319 }
1320
1321 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1322 const PeerConnectionInterface::RTCConfiguration& caller_config,
1323 webrtc::PeerConnectionDependencies caller_dependencies,
1324 const PeerConnectionInterface::RTCConfiguration& callee_config,
1325 webrtc::PeerConnectionDependencies callee_dependencies) {
1326 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001327 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001328 std::move(caller_dependencies), nullptr,
1329 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001330 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001331 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001332 std::move(callee_dependencies), nullptr,
1333 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001334 return caller_ && callee_;
1335 }
1336
1337 bool CreatePeerConnectionWrappersWithOptions(
1338 const PeerConnectionFactory::Options& caller_options,
1339 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001340 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001341 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001342 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1343 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001344 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001345 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001346 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1347 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001348 return caller_ && callee_;
1349 }
1350
1351 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1352 PeerConnectionInterface::RTCConfiguration default_config;
1353 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001354 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001355 webrtc::PeerConnectionDependencies(nullptr));
1356 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001357 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001358 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001359 return caller_ && callee_;
1360 }
1361
Seth Hampson2f0d7022018-02-20 11:54:42 -08001362 std::unique_ptr<PeerConnectionWrapper>
1363 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001364 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1365 new FakeRTCCertificateGenerator());
1366 cert_generator->use_alternate_key();
1367
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001368 webrtc::PeerConnectionDependencies dependencies(nullptr);
1369 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001370 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001371 std::move(dependencies), nullptr,
1372 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001373 }
1374
Seth Hampsonaed71642018-06-11 07:41:32 -07001375 cricket::TestTurnServer* CreateTurnServer(
1376 rtc::SocketAddress internal_address,
1377 rtc::SocketAddress external_address,
1378 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1379 const std::string& common_name = "test turn server") {
1380 rtc::Thread* thread = network_thread();
1381 std::unique_ptr<cricket::TestTurnServer> turn_server =
1382 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1383 RTC_FROM_HERE,
1384 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001385 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001386 thread, internal_address, external_address, type,
1387 /*ignore_bad_certs=*/true, common_name);
1388 });
1389 turn_servers_.push_back(std::move(turn_server));
1390 // Interactions with the turn server should be done on the network thread.
1391 return turn_servers_.back().get();
1392 }
1393
1394 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1395 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1396 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1397 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001398 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001399 turn_customizers_.push_back(std::move(turn_customizer));
1400 // Interactions with the turn customizer should be done on the network
1401 // thread.
1402 return turn_customizers_.back().get();
1403 }
1404
1405 // Checks that the function counters for a TestTurnCustomizer are greater than
1406 // 0.
1407 void ExpectTurnCustomizerCountersIncremented(
1408 cricket::TestTurnCustomizer* turn_customizer) {
1409 unsigned int allow_channel_data_counter =
1410 network_thread()->Invoke<unsigned int>(
1411 RTC_FROM_HERE, [turn_customizer] {
1412 return turn_customizer->allow_channel_data_cnt_;
1413 });
1414 EXPECT_GT(allow_channel_data_counter, 0u);
1415 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1416 RTC_FROM_HERE,
1417 [turn_customizer] { return turn_customizer->modify_cnt_; });
1418 EXPECT_GT(modify_counter, 0u);
1419 }
1420
deadbeef1dcb1642017-03-29 21:08:16 -07001421 // Once called, SDP blobs and ICE candidates will be automatically signaled
1422 // between PeerConnections.
1423 void ConnectFakeSignaling() {
1424 caller_->set_signaling_message_receiver(callee_.get());
1425 callee_->set_signaling_message_receiver(caller_.get());
1426 }
1427
Steve Antonede9ca52017-10-16 13:04:27 -07001428 // Once called, SDP blobs will be automatically signaled between
1429 // PeerConnections. Note that ICE candidates will not be signaled unless they
1430 // are in the exchanged SDP blobs.
1431 void ConnectFakeSignalingForSdpOnly() {
1432 ConnectFakeSignaling();
1433 SetSignalIceCandidates(false);
1434 }
1435
deadbeef1dcb1642017-03-29 21:08:16 -07001436 void SetSignalingDelayMs(int delay_ms) {
1437 caller_->set_signaling_delay_ms(delay_ms);
1438 callee_->set_signaling_delay_ms(delay_ms);
1439 }
1440
Steve Antonede9ca52017-10-16 13:04:27 -07001441 void SetSignalIceCandidates(bool signal) {
1442 caller_->set_signal_ice_candidates(signal);
1443 callee_->set_signal_ice_candidates(signal);
1444 }
1445
deadbeef1dcb1642017-03-29 21:08:16 -07001446 // Messages may get lost on the unreliable DataChannel, so we send multiple
1447 // times to avoid test flakiness.
1448 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1449 const std::string& data,
1450 int retries) {
1451 for (int i = 0; i < retries; ++i) {
1452 dc->Send(DataBuffer(data));
1453 }
1454 }
1455
1456 rtc::Thread* network_thread() { return network_thread_.get(); }
1457
1458 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1459
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001460 webrtc::MediaTransportPair* loopback_media_transports() {
1461 return &loopback_media_transports_;
1462 }
1463
deadbeef1dcb1642017-03-29 21:08:16 -07001464 PeerConnectionWrapper* caller() { return caller_.get(); }
1465
1466 // Set the |caller_| to the |wrapper| passed in and return the
1467 // original |caller_|.
1468 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1469 PeerConnectionWrapper* wrapper) {
1470 PeerConnectionWrapper* old = caller_.release();
1471 caller_.reset(wrapper);
1472 return old;
1473 }
1474
1475 PeerConnectionWrapper* callee() { return callee_.get(); }
1476
1477 // Set the |callee_| to the |wrapper| passed in and return the
1478 // original |callee_|.
1479 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1480 PeerConnectionWrapper* wrapper) {
1481 PeerConnectionWrapper* old = callee_.release();
1482 callee_.reset(wrapper);
1483 return old;
1484 }
1485
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001486 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1487 network_thread()->Invoke<void>(
1488 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1489 caller()->port_allocator(), caller_flags));
1490 network_thread()->Invoke<void>(
1491 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1492 callee()->port_allocator(), callee_flags));
1493 }
1494
Steve Antonede9ca52017-10-16 13:04:27 -07001495 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1496
Seth Hampson2f0d7022018-02-20 11:54:42 -08001497 // Expects the provided number of new frames to be received within
1498 // kMaxWaitForFramesMs. The new expected frames are specified in
1499 // |media_expectations|. Returns false if any of the expectations were
1500 // not met.
1501 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1502 // First initialize the expected frame counts based upon the current
1503 // frame count.
1504 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1505 if (media_expectations.caller_audio_expectation_ ==
1506 MediaExpectations::kExpectSomeFrames) {
1507 total_caller_audio_frames_expected +=
1508 media_expectations.caller_audio_frames_expected_;
1509 }
1510 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001511 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001512 if (media_expectations.caller_video_expectation_ ==
1513 MediaExpectations::kExpectSomeFrames) {
1514 total_caller_video_frames_expected +=
1515 media_expectations.caller_video_frames_expected_;
1516 }
1517 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1518 if (media_expectations.callee_audio_expectation_ ==
1519 MediaExpectations::kExpectSomeFrames) {
1520 total_callee_audio_frames_expected +=
1521 media_expectations.callee_audio_frames_expected_;
1522 }
1523 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001524 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001525 if (media_expectations.callee_video_expectation_ ==
1526 MediaExpectations::kExpectSomeFrames) {
1527 total_callee_video_frames_expected +=
1528 media_expectations.callee_video_frames_expected_;
1529 }
deadbeef1dcb1642017-03-29 21:08:16 -07001530
Seth Hampson2f0d7022018-02-20 11:54:42 -08001531 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001532 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001533 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001534 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001535 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001536 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001537 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001538 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001539 total_callee_video_frames_expected,
1540 kMaxWaitForFramesMs);
1541 bool expectations_correct =
1542 caller()->audio_frames_received() >=
1543 total_caller_audio_frames_expected &&
1544 caller()->min_video_frames_received_per_track() >=
1545 total_caller_video_frames_expected &&
1546 callee()->audio_frames_received() >=
1547 total_callee_audio_frames_expected &&
1548 callee()->min_video_frames_received_per_track() >=
1549 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001550
Seth Hampson2f0d7022018-02-20 11:54:42 -08001551 // After the combined wait, print out a more detailed message upon
1552 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001553 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001554 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001555 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001556 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001557 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001558 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001559 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001560 total_callee_video_frames_expected);
1561
1562 // We want to make sure nothing unexpected was received.
1563 if (media_expectations.caller_audio_expectation_ ==
1564 MediaExpectations::kExpectNoFrames) {
1565 EXPECT_EQ(caller()->audio_frames_received(),
1566 total_caller_audio_frames_expected);
1567 if (caller()->audio_frames_received() !=
1568 total_caller_audio_frames_expected) {
1569 expectations_correct = false;
1570 }
1571 }
1572 if (media_expectations.caller_video_expectation_ ==
1573 MediaExpectations::kExpectNoFrames) {
1574 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1575 total_caller_video_frames_expected);
1576 if (caller()->min_video_frames_received_per_track() !=
1577 total_caller_video_frames_expected) {
1578 expectations_correct = false;
1579 }
1580 }
1581 if (media_expectations.callee_audio_expectation_ ==
1582 MediaExpectations::kExpectNoFrames) {
1583 EXPECT_EQ(callee()->audio_frames_received(),
1584 total_callee_audio_frames_expected);
1585 if (callee()->audio_frames_received() !=
1586 total_callee_audio_frames_expected) {
1587 expectations_correct = false;
1588 }
1589 }
1590 if (media_expectations.callee_video_expectation_ ==
1591 MediaExpectations::kExpectNoFrames) {
1592 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1593 total_callee_video_frames_expected);
1594 if (callee()->min_video_frames_received_per_track() !=
1595 total_callee_video_frames_expected) {
1596 expectations_correct = false;
1597 }
1598 }
1599 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001600 }
1601
Steve Antond91969e2019-05-30 12:27:03 -07001602 void ClosePeerConnections() {
1603 caller()->pc()->Close();
1604 callee()->pc()->Close();
1605 }
1606
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001607 void TestNegotiatedCipherSuite(
1608 const PeerConnectionFactory::Options& caller_options,
1609 const PeerConnectionFactory::Options& callee_options,
1610 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001611 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1612 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001613 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001614 caller()->AddAudioVideoTracks();
1615 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001616 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001617 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001618 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001619 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001620 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00001621 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001622 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1623 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001624 }
1625
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001626 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1627 bool remote_gcm_enabled,
1628 int expected_cipher_suite) {
1629 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001630 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1631 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001632 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001633 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1634 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001635 TestNegotiatedCipherSuite(caller_options, callee_options,
1636 expected_cipher_suite);
1637 }
1638
Seth Hampson2f0d7022018-02-20 11:54:42 -08001639 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001640 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001641
deadbeef1dcb1642017-03-29 21:08:16 -07001642 private:
1643 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001644 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001645 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001646 // |network_thread_| and |worker_thread_| are used by both
1647 // |caller_| and |callee_| so they must be destroyed
1648 // later.
1649 std::unique_ptr<rtc::Thread> network_thread_;
1650 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001651 // The turn servers and turn customizers should be accessed & deleted on the
1652 // network thread to avoid a race with the socket read/write that occurs
1653 // on the network thread.
1654 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1655 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001656 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001657 std::unique_ptr<PeerConnectionWrapper> caller_;
1658 std::unique_ptr<PeerConnectionWrapper> callee_;
1659};
1660
Seth Hampson2f0d7022018-02-20 11:54:42 -08001661class PeerConnectionIntegrationTest
1662 : public PeerConnectionIntegrationBaseTest,
1663 public ::testing::WithParamInterface<SdpSemantics> {
1664 protected:
1665 PeerConnectionIntegrationTest()
1666 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1667};
1668
1669class PeerConnectionIntegrationTestPlanB
1670 : public PeerConnectionIntegrationBaseTest {
1671 protected:
1672 PeerConnectionIntegrationTestPlanB()
1673 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1674};
1675
1676class PeerConnectionIntegrationTestUnifiedPlan
1677 : public PeerConnectionIntegrationBaseTest {
1678 protected:
1679 PeerConnectionIntegrationTestUnifiedPlan()
1680 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1681};
1682
deadbeef1dcb1642017-03-29 21:08:16 -07001683// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1684// includes testing that the callback is invoked if an observer is connected
1685// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001686TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001687 RtpReceiverObserverOnFirstPacketReceived) {
1688 ASSERT_TRUE(CreatePeerConnectionWrappers());
1689 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001690 caller()->AddAudioVideoTracks();
1691 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001692 // Start offer/answer exchange and wait for it to complete.
1693 caller()->CreateAndSetAndSignalOffer();
1694 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1695 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001696 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1697 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001698 // Wait for all "first packet received" callbacks to be fired.
1699 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001700 absl::c_all_of(caller()->rtp_receiver_observers(),
1701 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1702 return o->first_packet_received();
1703 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001704 kMaxWaitForFramesMs);
1705 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001706 absl::c_all_of(callee()->rtp_receiver_observers(),
1707 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1708 return o->first_packet_received();
1709 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001710 kMaxWaitForFramesMs);
1711 // If new observers are set after the first packet was already received, the
1712 // callback should still be invoked.
1713 caller()->ResetRtpReceiverObservers();
1714 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001715 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1716 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001717 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001718 absl::c_all_of(caller()->rtp_receiver_observers(),
1719 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1720 return o->first_packet_received();
1721 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001722 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001723 absl::c_all_of(callee()->rtp_receiver_observers(),
1724 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1725 return o->first_packet_received();
1726 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001727}
1728
1729class DummyDtmfObserver : public DtmfSenderObserverInterface {
1730 public:
1731 DummyDtmfObserver() : completed_(false) {}
1732
1733 // Implements DtmfSenderObserverInterface.
1734 void OnToneChange(const std::string& tone) override {
1735 tones_.push_back(tone);
1736 if (tone.empty()) {
1737 completed_ = true;
1738 }
1739 }
1740
1741 const std::vector<std::string>& tones() const { return tones_; }
1742 bool completed() const { return completed_; }
1743
1744 private:
1745 bool completed_;
1746 std::vector<std::string> tones_;
1747};
1748
1749// Assumes |sender| already has an audio track added and the offer/answer
1750// exchange is done.
1751void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1752 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001753 // We should be able to get a DTMF sender from the local sender.
1754 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1755 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1756 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001757 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001758 dtmf_sender->RegisterObserver(&observer);
1759
1760 // Test the DtmfSender object just created.
1761 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1762 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1763
1764 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1765 std::vector<std::string> tones = {"1", "a", ""};
1766 EXPECT_EQ(tones, observer.tones());
1767 dtmf_sender->UnregisterObserver();
1768 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1769}
1770
1771// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1772// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001773TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001774 ASSERT_TRUE(CreatePeerConnectionWrappers());
1775 ConnectFakeSignaling();
1776 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001777 caller()->AddAudioTrack();
1778 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001779 caller()->CreateAndSetAndSignalOffer();
1780 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001781 // DTLS must finish before the DTMF sender can be used reliably.
1782 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001783 TestDtmfFromSenderToReceiver(caller(), callee());
1784 TestDtmfFromSenderToReceiver(callee(), caller());
1785}
1786
1787// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1788// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001789TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001790 ASSERT_TRUE(CreatePeerConnectionWrappers());
1791 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001792
deadbeef1dcb1642017-03-29 21:08:16 -07001793 // Do normal offer/answer and wait for some frames to be received in each
1794 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001795 caller()->AddAudioVideoTracks();
1796 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001797 caller()->CreateAndSetAndSignalOffer();
1798 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001799 MediaExpectations media_expectations;
1800 media_expectations.ExpectBidirectionalAudioAndVideo();
1801 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001802 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1803 webrtc::kEnumCounterKeyProtocolDtls));
1804 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1805 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001806}
1807
1808// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001809TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001810 PeerConnectionInterface::RTCConfiguration sdes_config;
1811 sdes_config.enable_dtls_srtp.emplace(false);
1812 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1813 ConnectFakeSignaling();
1814
1815 // Do normal offer/answer and wait for some frames to be received in each
1816 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001817 caller()->AddAudioVideoTracks();
1818 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001819 caller()->CreateAndSetAndSignalOffer();
1820 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001821 MediaExpectations media_expectations;
1822 media_expectations.ExpectBidirectionalAudioAndVideo();
1823 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001824 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1825 webrtc::kEnumCounterKeyProtocolSdes));
1826 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1827 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001828}
1829
Steve Anton9a44b2d2019-07-12 12:58:30 -07001830// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1831// option to offer encrypted versions of all header extensions alongside the
1832// unencrypted versions.
1833TEST_P(PeerConnectionIntegrationTest,
1834 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1835 CryptoOptions crypto_options;
1836 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1837 PeerConnectionInterface::RTCConfiguration config;
1838 config.crypto_options = crypto_options;
1839 // Note: This allows offering >14 RTP header extensions.
1840 config.offer_extmap_allow_mixed = true;
1841 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1842 ConnectFakeSignaling();
1843
1844 // Do normal offer/answer and wait for some frames to be received in each
1845 // direction.
1846 caller()->AddAudioVideoTracks();
1847 callee()->AddAudioVideoTracks();
1848 caller()->CreateAndSetAndSignalOffer();
1849 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1850 MediaExpectations media_expectations;
1851 media_expectations.ExpectBidirectionalAudioAndVideo();
1852 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1853}
1854
Steve Anton8c0f7a72017-10-03 10:03:10 -07001855// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1856// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001857TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001858 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1859 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1860 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1861 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1862 return pc->GetRemoteAudioSSLCertificate();
1863 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001864 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1865 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1866 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1867 return pc->GetRemoteAudioSSLCertChain();
1868 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001869
1870 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1871 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1872
1873 // Configure each side with a known certificate so they can be compared later.
1874 PeerConnectionInterface::RTCConfiguration caller_config;
1875 caller_config.enable_dtls_srtp.emplace(true);
1876 caller_config.certificates.push_back(caller_cert);
1877 PeerConnectionInterface::RTCConfiguration callee_config;
1878 callee_config.enable_dtls_srtp.emplace(true);
1879 callee_config.certificates.push_back(callee_cert);
1880 ASSERT_TRUE(
1881 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1882 ConnectFakeSignaling();
1883
1884 // When first initialized, there should not be a remote SSL certificate (and
1885 // calling this method should not crash).
1886 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1887 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001888 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1889 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001890
Steve Anton15324772018-01-16 10:26:49 -08001891 caller()->AddAudioTrack();
1892 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001893 caller()->CreateAndSetAndSignalOffer();
1894 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1895 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1896
1897 // Once DTLS has been connected, each side should return the other's SSL
1898 // certificate when calling GetRemoteAudioSSLCertificate.
1899
1900 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1901 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001902 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001903 caller_remote_cert->ToPEMString());
1904
1905 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1906 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001907 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001908 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001909
1910 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1911 ASSERT_TRUE(caller_remote_cert_chain);
1912 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1913 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001914 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001915 remote_cert->ToPEMString());
1916
1917 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1918 ASSERT_TRUE(callee_remote_cert_chain);
1919 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1920 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001921 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001922 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001923}
1924
deadbeef1dcb1642017-03-29 21:08:16 -07001925// This test sets up a call between two parties with a source resolution of
1926// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001927TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001928 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1929 ASSERT_TRUE(CreatePeerConnectionWrappers());
1930 ConnectFakeSignaling();
1931
Niels Möller5c7efe72018-05-11 10:34:46 +02001932 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1933 webrtc::FakePeriodicVideoSource::Config config;
1934 config.width = 1280;
1935 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001936 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001937 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1938 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001939
1940 // Do normal offer/answer and wait for at least one frame to be received in
1941 // each direction.
1942 caller()->CreateAndSetAndSignalOffer();
1943 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1944 callee()->min_video_frames_received_per_track() > 0,
1945 kMaxWaitForFramesMs);
1946
1947 // Check rendered aspect ratio.
1948 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1949 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1950 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1951 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1952}
1953
1954// This test sets up an one-way call, with media only from caller to
1955// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001956TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001957 ASSERT_TRUE(CreatePeerConnectionWrappers());
1958 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001959 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001960 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001961 MediaExpectations media_expectations;
1962 media_expectations.CalleeExpectsSomeAudioAndVideo();
1963 media_expectations.CallerExpectsNoAudio();
1964 media_expectations.CallerExpectsNoVideo();
1965 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001966}
1967
1968// This test sets up a audio call initially, with the callee rejecting video
1969// initially. Then later the callee decides to upgrade to audio/video, and
1970// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001971TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001972 ASSERT_TRUE(CreatePeerConnectionWrappers());
1973 ConnectFakeSignaling();
1974 // Initially, offer an audio/video stream from the caller, but refuse to
1975 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001976 caller()->AddAudioVideoTracks();
1977 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001978 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1979 PeerConnectionInterface::RTCOfferAnswerOptions options;
1980 options.offer_to_receive_video = 0;
1981 callee()->SetOfferAnswerOptions(options);
1982 } else {
1983 callee()->SetRemoteOfferHandler([this] {
1984 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1985 });
1986 }
deadbeef1dcb1642017-03-29 21:08:16 -07001987 // Do offer/answer and make sure audio is still received end-to-end.
1988 caller()->CreateAndSetAndSignalOffer();
1989 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001990 {
1991 MediaExpectations media_expectations;
1992 media_expectations.ExpectBidirectionalAudio();
1993 media_expectations.ExpectNoVideo();
1994 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1995 }
deadbeef1dcb1642017-03-29 21:08:16 -07001996 // Sanity check that the callee's description has a rejected video section.
1997 ASSERT_NE(nullptr, callee()->pc()->local_description());
1998 const ContentInfo* callee_video_content =
1999 GetFirstVideoContent(callee()->pc()->local_description()->description());
2000 ASSERT_NE(nullptr, callee_video_content);
2001 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002002
deadbeef1dcb1642017-03-29 21:08:16 -07002003 // Now negotiate with video and ensure negotiation succeeds, with video
2004 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002005 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002006 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2007 PeerConnectionInterface::RTCOfferAnswerOptions options;
2008 options.offer_to_receive_video = 1;
2009 callee()->SetOfferAnswerOptions(options);
2010 } else {
2011 callee()->SetRemoteOfferHandler(nullptr);
2012 caller()->SetRemoteOfferHandler([this] {
2013 // The caller creates a new transceiver to receive video on when receiving
2014 // the offer, but by default it is send only.
2015 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002016 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002017 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
2018 transceivers[2]->receiver()->media_type());
2019 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2020 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
2021 });
2022 }
deadbeef1dcb1642017-03-29 21:08:16 -07002023 callee()->CreateAndSetAndSignalOffer();
2024 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002025 {
2026 // Expect additional audio frames to be received after the upgrade.
2027 MediaExpectations media_expectations;
2028 media_expectations.ExpectBidirectionalAudioAndVideo();
2029 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2030 }
deadbeef1dcb1642017-03-29 21:08:16 -07002031}
2032
deadbeef4389b4d2017-09-07 09:07:36 -07002033// Simpler than the above test; just add an audio track to an established
2034// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002035TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002036 ASSERT_TRUE(CreatePeerConnectionWrappers());
2037 ConnectFakeSignaling();
2038 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002039 caller()->AddVideoTrack();
2040 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002041 caller()->CreateAndSetAndSignalOffer();
2042 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2043 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002044 caller()->AddAudioTrack();
2045 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002046 caller()->CreateAndSetAndSignalOffer();
2047 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2048 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002049 MediaExpectations media_expectations;
2050 media_expectations.ExpectBidirectionalAudioAndVideo();
2051 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002052}
2053
deadbeef1dcb1642017-03-29 21:08:16 -07002054// This test sets up a call that's transferred to a new caller with a different
2055// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002056TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002057 ASSERT_TRUE(CreatePeerConnectionWrappers());
2058 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002059 caller()->AddAudioVideoTracks();
2060 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002061 caller()->CreateAndSetAndSignalOffer();
2062 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2063
2064 // Keep the original peer around which will still send packets to the
2065 // receiving client. These SRTP packets will be dropped.
2066 std::unique_ptr<PeerConnectionWrapper> original_peer(
2067 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002068 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002069 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2070 // directly above.
2071 original_peer->pc()->Close();
2072
2073 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002074 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002075 caller()->CreateAndSetAndSignalOffer();
2076 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2077 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002078 MediaExpectations media_expectations;
2079 media_expectations.ExpectBidirectionalAudioAndVideo();
2080 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002081}
2082
2083// This test sets up a call that's transferred to a new callee with a different
2084// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002085TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002086 ASSERT_TRUE(CreatePeerConnectionWrappers());
2087 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002088 caller()->AddAudioVideoTracks();
2089 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002090 caller()->CreateAndSetAndSignalOffer();
2091 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2092
2093 // Keep the original peer around which will still send packets to the
2094 // receiving client. These SRTP packets will be dropped.
2095 std::unique_ptr<PeerConnectionWrapper> original_peer(
2096 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002097 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002098 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2099 // directly above.
2100 original_peer->pc()->Close();
2101
2102 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002103 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002104 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2105 caller()->CreateAndSetAndSignalOffer();
2106 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2107 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002108 MediaExpectations media_expectations;
2109 media_expectations.ExpectBidirectionalAudioAndVideo();
2110 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002111}
2112
2113// This test sets up a non-bundled call and negotiates bundling at the same
2114// time as starting an ICE restart. When bundling is in effect in the restart,
2115// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002116TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002117 ASSERT_TRUE(CreatePeerConnectionWrappers());
2118 ConnectFakeSignaling();
2119
Steve Anton15324772018-01-16 10:26:49 -08002120 caller()->AddAudioVideoTracks();
2121 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002122 // Remove the bundle group from the SDP received by the callee.
2123 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2124 desc->RemoveGroupByName("BUNDLE");
2125 });
2126 caller()->CreateAndSetAndSignalOffer();
2127 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002128 {
2129 MediaExpectations media_expectations;
2130 media_expectations.ExpectBidirectionalAudioAndVideo();
2131 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2132 }
deadbeef1dcb1642017-03-29 21:08:16 -07002133 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2134 callee()->SetReceivedSdpMunger(nullptr);
2135 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2136 caller()->CreateAndSetAndSignalOffer();
2137 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2138
2139 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002140 {
2141 MediaExpectations media_expectations;
2142 media_expectations.ExpectBidirectionalAudioAndVideo();
2143 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2144 }
deadbeef1dcb1642017-03-29 21:08:16 -07002145}
2146
2147// Test CVO (Coordination of Video Orientation). If a video source is rotated
2148// and both peers support the CVO RTP header extension, the actual video frames
2149// don't need to be encoded in different resolutions, since the rotation is
2150// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002151TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002152 ASSERT_TRUE(CreatePeerConnectionWrappers());
2153 ConnectFakeSignaling();
2154 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002155 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002156 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002157 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002158 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2159
2160 // Wait for video frames to be received by both sides.
2161 caller()->CreateAndSetAndSignalOffer();
2162 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2163 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2164 callee()->min_video_frames_received_per_track() > 0,
2165 kMaxWaitForFramesMs);
2166
2167 // Ensure that the aspect ratio is unmodified.
2168 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2169 // not just assumed.
2170 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2171 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2172 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2173 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2174 // Ensure that the CVO bits were surfaced to the renderer.
2175 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2176 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2177}
2178
2179// Test that when the CVO extension isn't supported, video is rotated the
2180// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002181TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002182 ASSERT_TRUE(CreatePeerConnectionWrappers());
2183 ConnectFakeSignaling();
2184 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002185 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002186 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002187 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002188 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2189
2190 // Remove the CVO extension from the offered SDP.
2191 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2192 cricket::VideoContentDescription* video =
2193 GetFirstVideoContentDescription(desc);
2194 video->ClearRtpHeaderExtensions();
2195 });
2196 // Wait for video frames to be received by both sides.
2197 caller()->CreateAndSetAndSignalOffer();
2198 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2199 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2200 callee()->min_video_frames_received_per_track() > 0,
2201 kMaxWaitForFramesMs);
2202
2203 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2204 // rotation.
2205 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2206 // not just assumed.
2207 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2208 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2209 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2210 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2211 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2212 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2213 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2214}
2215
deadbeef1dcb1642017-03-29 21:08:16 -07002216// Test that if the answerer rejects the audio m= section, no audio is sent or
2217// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002218TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002219 ASSERT_TRUE(CreatePeerConnectionWrappers());
2220 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002221 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002222 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2223 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2224 // it will reject the audio m= section completely.
2225 PeerConnectionInterface::RTCOfferAnswerOptions options;
2226 options.offer_to_receive_audio = 0;
2227 callee()->SetOfferAnswerOptions(options);
2228 } else {
2229 // Stopping the audio RtpTransceiver will cause the media section to be
2230 // rejected in the answer.
2231 callee()->SetRemoteOfferHandler([this] {
2232 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2233 });
2234 }
Steve Anton15324772018-01-16 10:26:49 -08002235 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002236 // Do offer/answer and wait for successful end-to-end video frames.
2237 caller()->CreateAndSetAndSignalOffer();
2238 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002239 MediaExpectations media_expectations;
2240 media_expectations.ExpectBidirectionalVideo();
2241 media_expectations.ExpectNoAudio();
2242 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2243
deadbeef1dcb1642017-03-29 21:08:16 -07002244 // Sanity check that the callee's description has a rejected audio section.
2245 ASSERT_NE(nullptr, callee()->pc()->local_description());
2246 const ContentInfo* callee_audio_content =
2247 GetFirstAudioContent(callee()->pc()->local_description()->description());
2248 ASSERT_NE(nullptr, callee_audio_content);
2249 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002250 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2251 // The caller's transceiver should have stopped after receiving the answer.
2252 EXPECT_TRUE(caller()
2253 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2254 ->stopped());
2255 }
deadbeef1dcb1642017-03-29 21:08:16 -07002256}
2257
2258// Test that if the answerer rejects the video m= section, no video is sent or
2259// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002260TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002261 ASSERT_TRUE(CreatePeerConnectionWrappers());
2262 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002263 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002264 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2265 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2266 // it will reject the video m= section completely.
2267 PeerConnectionInterface::RTCOfferAnswerOptions options;
2268 options.offer_to_receive_video = 0;
2269 callee()->SetOfferAnswerOptions(options);
2270 } else {
2271 // Stopping the video RtpTransceiver will cause the media section to be
2272 // rejected in the answer.
2273 callee()->SetRemoteOfferHandler([this] {
2274 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2275 });
2276 }
Steve Anton15324772018-01-16 10:26:49 -08002277 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002278 // Do offer/answer and wait for successful end-to-end audio frames.
2279 caller()->CreateAndSetAndSignalOffer();
2280 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002281 MediaExpectations media_expectations;
2282 media_expectations.ExpectBidirectionalAudio();
2283 media_expectations.ExpectNoVideo();
2284 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2285
deadbeef1dcb1642017-03-29 21:08:16 -07002286 // Sanity check that the callee's description has a rejected video section.
2287 ASSERT_NE(nullptr, callee()->pc()->local_description());
2288 const ContentInfo* callee_video_content =
2289 GetFirstVideoContent(callee()->pc()->local_description()->description());
2290 ASSERT_NE(nullptr, callee_video_content);
2291 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002292 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2293 // The caller's transceiver should have stopped after receiving the answer.
2294 EXPECT_TRUE(caller()
2295 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2296 ->stopped());
2297 }
deadbeef1dcb1642017-03-29 21:08:16 -07002298}
2299
2300// Test that if the answerer rejects both audio and video m= sections, nothing
2301// bad happens.
2302// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2303// test anything but the fact that negotiation succeeds, which doesn't mean
2304// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002305TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002306 ASSERT_TRUE(CreatePeerConnectionWrappers());
2307 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002308 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002309 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2310 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2311 // will reject both audio and video m= sections.
2312 PeerConnectionInterface::RTCOfferAnswerOptions options;
2313 options.offer_to_receive_audio = 0;
2314 options.offer_to_receive_video = 0;
2315 callee()->SetOfferAnswerOptions(options);
2316 } else {
2317 callee()->SetRemoteOfferHandler([this] {
2318 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002319 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002320 transceiver->Stop();
2321 }
2322 });
2323 }
deadbeef1dcb1642017-03-29 21:08:16 -07002324 // Do offer/answer and wait for stable signaling state.
2325 caller()->CreateAndSetAndSignalOffer();
2326 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002327
deadbeef1dcb1642017-03-29 21:08:16 -07002328 // Sanity check that the callee's description has rejected m= sections.
2329 ASSERT_NE(nullptr, callee()->pc()->local_description());
2330 const ContentInfo* callee_audio_content =
2331 GetFirstAudioContent(callee()->pc()->local_description()->description());
2332 ASSERT_NE(nullptr, callee_audio_content);
2333 EXPECT_TRUE(callee_audio_content->rejected);
2334 const ContentInfo* callee_video_content =
2335 GetFirstVideoContent(callee()->pc()->local_description()->description());
2336 ASSERT_NE(nullptr, callee_video_content);
2337 EXPECT_TRUE(callee_video_content->rejected);
2338}
2339
2340// This test sets up an audio and video call between two parties. After the
2341// call runs for a while, the caller sends an updated offer with video being
2342// rejected. Once the re-negotiation is done, the video flow should stop and
2343// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002344TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002345 ASSERT_TRUE(CreatePeerConnectionWrappers());
2346 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002347 caller()->AddAudioVideoTracks();
2348 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002349 caller()->CreateAndSetAndSignalOffer();
2350 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002351 {
2352 MediaExpectations media_expectations;
2353 media_expectations.ExpectBidirectionalAudioAndVideo();
2354 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2355 }
deadbeef1dcb1642017-03-29 21:08:16 -07002356 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002357 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2358 caller()->SetGeneratedSdpMunger(
2359 [](cricket::SessionDescription* description) {
2360 for (cricket::ContentInfo& content : description->contents()) {
2361 if (cricket::IsVideoContent(&content)) {
2362 content.rejected = true;
2363 }
2364 }
2365 });
2366 } else {
2367 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2368 }
deadbeef1dcb1642017-03-29 21:08:16 -07002369 caller()->CreateAndSetAndSignalOffer();
2370 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2371
2372 // Sanity check that the caller's description has a rejected video section.
2373 ASSERT_NE(nullptr, caller()->pc()->local_description());
2374 const ContentInfo* caller_video_content =
2375 GetFirstVideoContent(caller()->pc()->local_description()->description());
2376 ASSERT_NE(nullptr, caller_video_content);
2377 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002378 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002379 {
2380 MediaExpectations media_expectations;
2381 media_expectations.ExpectBidirectionalAudio();
2382 media_expectations.ExpectNoVideo();
2383 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2384 }
deadbeef1dcb1642017-03-29 21:08:16 -07002385}
2386
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002387// Do one offer/answer with audio, another that disables it (rejecting the m=
2388// section), and another that re-enables it. Regression test for:
2389// bugs.webrtc.org/6023
2390TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2391 ASSERT_TRUE(CreatePeerConnectionWrappers());
2392 ConnectFakeSignaling();
2393
2394 // Add audio track, do normal offer/answer.
2395 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2396 caller()->CreateLocalAudioTrack();
2397 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2398 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2399 caller()->CreateAndSetAndSignalOffer();
2400 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2401
2402 // Remove audio track, and set offer_to_receive_audio to false to cause the
2403 // m= section to be completely disabled, not just "recvonly".
2404 caller()->pc()->RemoveTrack(sender);
2405 PeerConnectionInterface::RTCOfferAnswerOptions options;
2406 options.offer_to_receive_audio = 0;
2407 caller()->SetOfferAnswerOptions(options);
2408 caller()->CreateAndSetAndSignalOffer();
2409 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2410
2411 // Add the audio track again, expecting negotiation to succeed and frames to
2412 // flow.
2413 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2414 options.offer_to_receive_audio = 1;
2415 caller()->SetOfferAnswerOptions(options);
2416 caller()->CreateAndSetAndSignalOffer();
2417 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2418
2419 MediaExpectations media_expectations;
2420 media_expectations.CalleeExpectsSomeAudio();
2421 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2422}
2423
deadbeef1dcb1642017-03-29 21:08:16 -07002424// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2425// is needed to support legacy endpoints.
2426// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2427// add a test for an end-to-end test without MID signaling either (basically,
2428// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002429TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002430 ASSERT_TRUE(CreatePeerConnectionWrappers());
2431 ConnectFakeSignaling();
2432 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002433 caller()->AddAudioVideoTracks();
2434 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002435 // Remove SSRCs and MSIDs from the received offer SDP.
2436 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002437 caller()->CreateAndSetAndSignalOffer();
2438 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002439 MediaExpectations media_expectations;
2440 media_expectations.ExpectBidirectionalAudioAndVideo();
2441 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002442}
2443
Seth Hampson5897a6e2018-04-03 11:16:33 -07002444// Basic end-to-end test, without SSRC signaling. This means that the track
2445// was created properly and frames are delivered when the MSIDs are communicated
2446// with a=msid lines and no a=ssrc lines.
2447TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2448 EndToEndCallWithoutSsrcSignaling) {
2449 const char kStreamId[] = "streamId";
2450 ASSERT_TRUE(CreatePeerConnectionWrappers());
2451 ConnectFakeSignaling();
2452 // Add just audio tracks.
2453 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2454 callee()->AddAudioTrack();
2455
2456 // Remove SSRCs from the received offer SDP.
2457 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2458 caller()->CreateAndSetAndSignalOffer();
2459 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2460 MediaExpectations media_expectations;
2461 media_expectations.ExpectBidirectionalAudio();
2462 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2463}
2464
Steve Antondf527fd2018-04-27 15:52:03 -07002465// Tests that video flows between multiple video tracks when SSRCs are not
2466// signaled. This exercises the MID RTP header extension which is needed to
2467// demux the incoming video tracks.
2468TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2469 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2470 ASSERT_TRUE(CreatePeerConnectionWrappers());
2471 ConnectFakeSignaling();
2472 caller()->AddVideoTrack();
2473 caller()->AddVideoTrack();
2474 callee()->AddVideoTrack();
2475 callee()->AddVideoTrack();
2476
2477 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2478 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2479 caller()->CreateAndSetAndSignalOffer();
2480 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2481 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2482 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2483
2484 // Expect video to be received in both directions on both tracks.
2485 MediaExpectations media_expectations;
2486 media_expectations.ExpectBidirectionalVideo();
2487 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2488}
2489
Henrik Boström5b147782018-12-04 11:25:05 +01002490TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2491 ASSERT_TRUE(CreatePeerConnectionWrappers());
2492 ConnectFakeSignaling();
2493 caller()->AddAudioTrack();
2494 caller()->AddVideoTrack();
2495 caller()->CreateAndSetAndSignalOffer();
2496 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2497 auto callee_receivers = callee()->pc()->GetReceivers();
2498 ASSERT_EQ(2u, callee_receivers.size());
2499 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2500 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2501}
2502
2503TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2504 ASSERT_TRUE(CreatePeerConnectionWrappers());
2505 ConnectFakeSignaling();
2506 caller()->AddAudioTrack();
2507 caller()->AddVideoTrack();
2508 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2509 caller()->CreateAndSetAndSignalOffer();
2510 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2511 auto callee_receivers = callee()->pc()->GetReceivers();
2512 ASSERT_EQ(2u, callee_receivers.size());
2513 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2514 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2515 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2516 callee_receivers[1]->stream_ids()[0]);
2517 EXPECT_EQ(callee_receivers[0]->streams()[0],
2518 callee_receivers[1]->streams()[0]);
2519}
2520
deadbeef1dcb1642017-03-29 21:08:16 -07002521// Test that if two video tracks are sent (from caller to callee, in this test),
2522// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002523TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002524 ASSERT_TRUE(CreatePeerConnectionWrappers());
2525 ConnectFakeSignaling();
2526 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002527 caller()->AddAudioVideoTracks();
2528 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002529 caller()->CreateAndSetAndSignalOffer();
2530 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002531 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002532
2533 MediaExpectations media_expectations;
2534 media_expectations.CalleeExpectsSomeAudioAndVideo();
2535 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002536}
2537
2538static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2539 bool first = true;
2540 for (cricket::ContentInfo& content : desc->contents()) {
2541 if (first) {
2542 first = false;
2543 continue;
2544 }
2545 content.bundle_only = true;
2546 }
2547 first = true;
2548 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2549 if (first) {
2550 first = false;
2551 continue;
2552 }
2553 transport.description.ice_ufrag.clear();
2554 transport.description.ice_pwd.clear();
2555 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2556 transport.description.identity_fingerprint.reset(nullptr);
2557 }
2558}
2559
2560// Test that if applying a true "max bundle" offer, which uses ports of 0,
2561// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2562// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2563// successfully and media flows.
2564// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2565// TODO(deadbeef): Won't need this test once we start generating actual
2566// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002567TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002568 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2569 ASSERT_TRUE(CreatePeerConnectionWrappers());
2570 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002571 caller()->AddAudioVideoTracks();
2572 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002573 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2574 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2575 // but the first m= section.
2576 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2577 caller()->CreateAndSetAndSignalOffer();
2578 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002579 MediaExpectations media_expectations;
2580 media_expectations.ExpectBidirectionalAudioAndVideo();
2581 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002582}
2583
2584// Test that we can receive the audio output level from a remote audio track.
2585// TODO(deadbeef): Use a fake audio source and verify that the output level is
2586// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002587TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002588 ASSERT_TRUE(CreatePeerConnectionWrappers());
2589 ConnectFakeSignaling();
2590 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002591 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002592 caller()->CreateAndSetAndSignalOffer();
2593 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2594
2595 // Get the audio output level stats. Note that the level is not available
2596 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002597 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002598 kMaxWaitForFramesMs);
2599}
2600
2601// Test that an audio input level is reported.
2602// TODO(deadbeef): Use a fake audio source and verify that the input level is
2603// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002604TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002605 ASSERT_TRUE(CreatePeerConnectionWrappers());
2606 ConnectFakeSignaling();
2607 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002608 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002609 caller()->CreateAndSetAndSignalOffer();
2610 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2611
2612 // Get the audio input level stats. The level should be available very
2613 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002614 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002615 kMaxWaitForStatsMs);
2616}
2617
2618// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002619TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002620 ASSERT_TRUE(CreatePeerConnectionWrappers());
2621 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002622 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002623 // Do offer/answer, wait for the callee to receive some frames.
2624 caller()->CreateAndSetAndSignalOffer();
2625 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002626
2627 MediaExpectations media_expectations;
2628 media_expectations.CalleeExpectsSomeAudioAndVideo();
2629 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002630
2631 // Get a handle to the remote tracks created, so they can be used as GetStats
2632 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002633 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002634 // We received frames, so we definitely should have nonzero "received bytes"
2635 // stats at this point.
2636 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2637 0);
2638 }
deadbeef1dcb1642017-03-29 21:08:16 -07002639}
2640
2641// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002642TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002643 ASSERT_TRUE(CreatePeerConnectionWrappers());
2644 ConnectFakeSignaling();
2645 auto audio_track = caller()->CreateLocalAudioTrack();
2646 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002647 caller()->AddTrack(audio_track);
2648 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002649 // Do offer/answer, wait for the callee to receive some frames.
2650 caller()->CreateAndSetAndSignalOffer();
2651 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002652 MediaExpectations media_expectations;
2653 media_expectations.CalleeExpectsSomeAudioAndVideo();
2654 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002655
2656 // The callee received frames, so we definitely should have nonzero "sent
2657 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002658 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2659 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2660}
2661
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002662// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002663TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002664 ASSERT_TRUE(CreatePeerConnectionWrappers());
2665 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002666 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002667
Steve Anton15324772018-01-16 10:26:49 -08002668 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002669
2670 // Do offer/answer, wait for the callee to receive some frames.
2671 caller()->CreateAndSetAndSignalOffer();
2672 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2673
2674 // Get the remote audio track created on the receiver, so they can be used as
2675 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002676 auto receivers = callee()->pc()->GetReceivers();
2677 ASSERT_EQ(1u, receivers.size());
2678 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002679
2680 // Get the audio output level stats. Note that the level is not available
2681 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002682 EXPECT_TRUE_WAIT(
2683 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2684 0,
2685 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002686}
2687
Steve Antona41959e2018-11-28 11:15:33 -08002688// Test that the track ID is associated with all local and remote SSRC stats
2689// using the old GetStats() and more than 1 audio and more than 1 video track.
2690// This is a regression test for crbug.com/906988
2691TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2692 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2693 ASSERT_TRUE(CreatePeerConnectionWrappers());
2694 ConnectFakeSignaling();
2695 auto audio_sender_1 = caller()->AddAudioTrack();
2696 auto video_sender_1 = caller()->AddVideoTrack();
2697 auto audio_sender_2 = caller()->AddAudioTrack();
2698 auto video_sender_2 = caller()->AddVideoTrack();
2699 caller()->CreateAndSetAndSignalOffer();
2700 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2701
2702 MediaExpectations media_expectations;
2703 media_expectations.CalleeExpectsSomeAudioAndVideo();
2704 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2705
2706 std::vector<std::string> track_ids = {
2707 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2708 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2709
2710 auto caller_stats = caller()->OldGetStats();
2711 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2712 auto callee_stats = callee()->OldGetStats();
2713 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2714}
2715
Steve Antonffa6ce42018-11-30 09:26:08 -08002716// Test that the new GetStats() returns stats for all outgoing/incoming streams
2717// with the correct track IDs if there are more than one audio and more than one
2718// video senders/receivers.
2719TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2720 ASSERT_TRUE(CreatePeerConnectionWrappers());
2721 ConnectFakeSignaling();
2722 auto audio_sender_1 = caller()->AddAudioTrack();
2723 auto video_sender_1 = caller()->AddVideoTrack();
2724 auto audio_sender_2 = caller()->AddAudioTrack();
2725 auto video_sender_2 = caller()->AddVideoTrack();
2726 caller()->CreateAndSetAndSignalOffer();
2727 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2728
2729 MediaExpectations media_expectations;
2730 media_expectations.CalleeExpectsSomeAudioAndVideo();
2731 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2732
2733 std::vector<std::string> track_ids = {
2734 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2735 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2736
2737 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2738 caller()->NewGetStats();
2739 ASSERT_TRUE(caller_report);
2740 auto outbound_stream_stats =
2741 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2742 ASSERT_EQ(4u, outbound_stream_stats.size());
2743 std::vector<std::string> outbound_track_ids;
2744 for (const auto& stat : outbound_stream_stats) {
2745 ASSERT_TRUE(stat->bytes_sent.is_defined());
2746 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002747 if (*stat->kind == "video") {
2748 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
2749 EXPECT_GT(*stat->key_frames_encoded, 0u);
2750 ASSERT_TRUE(stat->frames_encoded.is_defined());
2751 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
2752 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002753 ASSERT_TRUE(stat->track_id.is_defined());
2754 const auto* track_stat =
2755 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2756 ASSERT_TRUE(track_stat);
2757 outbound_track_ids.push_back(*track_stat->track_identifier);
2758 }
2759 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2760
2761 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2762 callee()->NewGetStats();
2763 ASSERT_TRUE(callee_report);
2764 auto inbound_stream_stats =
2765 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2766 ASSERT_EQ(4u, inbound_stream_stats.size());
2767 std::vector<std::string> inbound_track_ids;
2768 for (const auto& stat : inbound_stream_stats) {
2769 ASSERT_TRUE(stat->bytes_received.is_defined());
2770 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002771 if (*stat->kind == "video") {
2772 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
2773 EXPECT_GT(*stat->key_frames_decoded, 0u);
2774 ASSERT_TRUE(stat->frames_decoded.is_defined());
2775 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
2776 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002777 ASSERT_TRUE(stat->track_id.is_defined());
2778 const auto* track_stat =
2779 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2780 ASSERT_TRUE(track_stat);
2781 inbound_track_ids.push_back(*track_stat->track_identifier);
2782 }
2783 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2784}
2785
2786// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002787// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2788// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002789TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002790 GetStatsForUnsignaledStreamWithNewStatsApi) {
2791 ASSERT_TRUE(CreatePeerConnectionWrappers());
2792 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002793 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002794 // Remove SSRCs and MSIDs from the received offer SDP.
2795 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2796 caller()->CreateAndSetAndSignalOffer();
2797 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002798 MediaExpectations media_expectations;
2799 media_expectations.CalleeExpectsSomeAudio(1);
2800 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002801
2802 // We received a frame, so we should have nonzero "bytes received" stats for
2803 // the unsignaled stream, if stats are working for it.
2804 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2805 callee()->NewGetStats();
2806 ASSERT_NE(nullptr, report);
2807 auto inbound_stream_stats =
2808 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2809 ASSERT_EQ(1U, inbound_stream_stats.size());
2810 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2811 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002812 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2813}
2814
Taylor Brandstettera4653442018-06-19 09:44:26 -07002815// Same as above but for the legacy stats implementation.
2816TEST_P(PeerConnectionIntegrationTest,
2817 GetStatsForUnsignaledStreamWithOldStatsApi) {
2818 ASSERT_TRUE(CreatePeerConnectionWrappers());
2819 ConnectFakeSignaling();
2820 caller()->AddAudioTrack();
2821 // Remove SSRCs and MSIDs from the received offer SDP.
2822 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2823 caller()->CreateAndSetAndSignalOffer();
2824 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2825
2826 // Note that, since the old stats implementation associates SSRCs with tracks
2827 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2828 // associated track ID. So we can't use the track "selector" argument.
2829 //
2830 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2831 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002832 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002833 kDefaultTimeout);
2834}
2835
zhihuangf8164932017-05-19 13:09:47 -07002836// Test that we can successfully get the media related stats (audio level
2837// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002838TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002839 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2840 ASSERT_TRUE(CreatePeerConnectionWrappers());
2841 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002842 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002843 // Remove SSRCs and MSIDs from the received offer SDP.
2844 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2845 caller()->CreateAndSetAndSignalOffer();
2846 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002847 MediaExpectations media_expectations;
2848 media_expectations.CalleeExpectsSomeAudio(1);
2849 media_expectations.CalleeExpectsSomeVideo(1);
2850 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002851
2852 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2853 callee()->NewGetStats();
2854 ASSERT_NE(nullptr, report);
2855
2856 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2857 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2858 ASSERT_GE(audio_index, 0);
2859 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002860}
2861
deadbeef4e2deab2017-09-20 13:56:21 -07002862// Helper for test below.
2863void ModifySsrcs(cricket::SessionDescription* desc) {
2864 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002865 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002866 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002867 for (uint32_t& ssrc : stream.ssrcs) {
2868 ssrc = rtc::CreateRandomId();
2869 }
2870 }
2871 }
2872}
2873
2874// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2875// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2876// This should result in two "RTCInboundRTPStreamStats", but only one
2877// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2878// being reset to 0 once the SSRC change occurs.
2879//
2880// Regression test for this bug:
2881// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2882//
2883// The bug causes the track stats to only represent one of the two streams:
2884// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2885// that the track stat counters would reset to 0 when the new stream is
2886// received, and a 50% chance that they'll stop updating (while
2887// "concealed_samples" continues increasing, due to silence being generated for
2888// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002889TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002890 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002891 ASSERT_TRUE(CreatePeerConnectionWrappers());
2892 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002893 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002894 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2895 // that doesn't signal SSRCs (from the callee's perspective).
2896 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2897 caller()->CreateAndSetAndSignalOffer();
2898 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2899 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002900 {
2901 MediaExpectations media_expectations;
2902 media_expectations.CalleeExpectsSomeAudio(50);
2903 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2904 }
deadbeef4e2deab2017-09-20 13:56:21 -07002905 // Some audio frames were received, so we should have nonzero "samples
2906 // received" for the track.
2907 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2908 callee()->NewGetStats();
2909 ASSERT_NE(nullptr, report);
2910 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2911 ASSERT_EQ(1U, track_stats.size());
2912 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2913 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2914 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2915
2916 // Create a new offer and munge it to cause the caller to use a new SSRC.
2917 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2918 caller()->CreateAndSetAndSignalOffer();
2919 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2920 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2921 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002922 {
2923 MediaExpectations media_expectations;
2924 media_expectations.CalleeExpectsSomeAudio(25);
2925 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2926 }
deadbeef4e2deab2017-09-20 13:56:21 -07002927
2928 report = callee()->NewGetStats();
2929 ASSERT_NE(nullptr, report);
2930 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2931 ASSERT_EQ(1U, track_stats.size());
2932 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2933 // The "total samples received" stat should only be greater than it was
2934 // before.
2935 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2936 // Right now, the new SSRC will cause the counters to reset to 0.
2937 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2938
2939 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002940 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002941 // good sign that we're seeing stats from the old stream that's no longer
2942 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002943 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002944 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2945 EXPECT_LT(*track_stats[0]->concealed_samples,
2946 *track_stats[0]->total_samples_received *
2947 kAcceptableConcealedSamplesPercentage);
2948
2949 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2950 // sanity check that the SSRC really changed.
2951 // TODO(deadbeef): This isn't working right now, because we're not returning
2952 // *any* stats for the inactive stream. Uncomment when the bug is completely
2953 // fixed.
2954 // auto inbound_stream_stats =
2955 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2956 // ASSERT_EQ(2U, inbound_stream_stats.size());
2957}
2958
deadbeef1dcb1642017-03-29 21:08:16 -07002959// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002960TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002961 PeerConnectionFactory::Options dtls_10_options;
2962 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2963 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2964 dtls_10_options));
2965 ConnectFakeSignaling();
2966 // Do normal offer/answer and wait for some frames to be received in each
2967 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002968 caller()->AddAudioVideoTracks();
2969 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002970 caller()->CreateAndSetAndSignalOffer();
2971 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002972 MediaExpectations media_expectations;
2973 media_expectations.ExpectBidirectionalAudioAndVideo();
2974 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002975}
2976
2977// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002978TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002979 PeerConnectionFactory::Options dtls_10_options;
2980 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2981 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2982 dtls_10_options));
2983 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002984 caller()->AddAudioVideoTracks();
2985 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002986 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002987 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002988 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002989 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002990 kDefaultTimeout);
2991 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002992 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002993 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002994 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002995 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2996 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002997}
2998
2999// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003000TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003001 PeerConnectionFactory::Options dtls_12_options;
3002 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3003 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3004 dtls_12_options));
3005 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003006 caller()->AddAudioVideoTracks();
3007 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003008 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003009 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003010 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003011 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003012 kDefaultTimeout);
3013 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003014 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003015 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00003016 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003017 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3018 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003019}
3020
3021// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3022// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003023TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003024 PeerConnectionFactory::Options caller_options;
3025 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3026 PeerConnectionFactory::Options callee_options;
3027 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3028 ASSERT_TRUE(
3029 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3030 ConnectFakeSignaling();
3031 // Do normal offer/answer and wait for some frames to be received in each
3032 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003033 caller()->AddAudioVideoTracks();
3034 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003035 caller()->CreateAndSetAndSignalOffer();
3036 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003037 MediaExpectations media_expectations;
3038 media_expectations.ExpectBidirectionalAudioAndVideo();
3039 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003040}
3041
3042// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3043// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003044TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003045 PeerConnectionFactory::Options caller_options;
3046 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3047 PeerConnectionFactory::Options callee_options;
3048 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3049 ASSERT_TRUE(
3050 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3051 ConnectFakeSignaling();
3052 // Do normal offer/answer and wait for some frames to be received in each
3053 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003054 caller()->AddAudioVideoTracks();
3055 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003056 caller()->CreateAndSetAndSignalOffer();
3057 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003058 MediaExpectations media_expectations;
3059 media_expectations.ExpectBidirectionalAudioAndVideo();
3060 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003061}
3062
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003063// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3064// works as expected; the cipher should only be used if enabled by both sides.
3065TEST_P(PeerConnectionIntegrationTest,
3066 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3067 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003068 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003069 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003070 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3071 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003072 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3073 TestNegotiatedCipherSuite(caller_options, callee_options,
3074 expected_cipher_suite);
3075}
3076
3077TEST_P(PeerConnectionIntegrationTest,
3078 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3079 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003080 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3081 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003082 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003083 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003084 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3085 TestNegotiatedCipherSuite(caller_options, callee_options,
3086 expected_cipher_suite);
3087}
3088
3089TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3090 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003091 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003092 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003093 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003094 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3095 TestNegotiatedCipherSuite(caller_options, callee_options,
3096 expected_cipher_suite);
3097}
3098
deadbeef1dcb1642017-03-29 21:08:16 -07003099// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003100TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003101 bool local_gcm_enabled = false;
3102 bool remote_gcm_enabled = false;
3103 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3104 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3105 expected_cipher_suite);
3106}
3107
3108// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003109TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003110 bool local_gcm_enabled = true;
3111 bool remote_gcm_enabled = true;
3112 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3113 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3114 expected_cipher_suite);
3115}
3116
3117// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003118TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003119 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
3120 bool local_gcm_enabled = true;
3121 bool remote_gcm_enabled = false;
3122 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3123 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3124 expected_cipher_suite);
3125}
3126
3127// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003128TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003129 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
3130 bool local_gcm_enabled = false;
3131 bool remote_gcm_enabled = true;
3132 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3133 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3134 expected_cipher_suite);
3135}
3136
deadbeef7914b8c2017-04-21 03:23:33 -07003137// Verify that media can be transmitted end-to-end when GCM crypto suites are
3138// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3139// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3140// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003141TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003142 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003143 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07003144 ASSERT_TRUE(
3145 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3146 ConnectFakeSignaling();
3147 // Do normal offer/answer and wait for some frames to be received in each
3148 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003149 caller()->AddAudioVideoTracks();
3150 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003151 caller()->CreateAndSetAndSignalOffer();
3152 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003153 MediaExpectations media_expectations;
3154 media_expectations.ExpectBidirectionalAudioAndVideo();
3155 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003156}
3157
deadbeef1dcb1642017-03-29 21:08:16 -07003158// This test sets up a call between two parties with audio, video and an RTP
3159// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003160TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003161 PeerConnectionInterface::RTCConfiguration rtc_config;
3162 rtc_config.enable_rtp_data_channel = true;
3163 rtc_config.enable_dtls_srtp = false;
3164 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003165 ConnectFakeSignaling();
3166 // Expect that data channel created on caller side will show up for callee as
3167 // well.
3168 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003169 caller()->AddAudioVideoTracks();
3170 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003171 caller()->CreateAndSetAndSignalOffer();
3172 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3173 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003174 MediaExpectations media_expectations;
3175 media_expectations.ExpectBidirectionalAudioAndVideo();
3176 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003177 ASSERT_NE(nullptr, caller()->data_channel());
3178 ASSERT_NE(nullptr, callee()->data_channel());
3179 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3180 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3181
3182 // Ensure data can be sent in both directions.
3183 std::string data = "hello world";
3184 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3185 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3186 kDefaultTimeout);
3187 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3188 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3189 kDefaultTimeout);
3190}
3191
3192// Ensure that an RTP data channel is signaled as closed for the caller when
3193// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003194TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003195 RtpDataChannelSignaledClosedInCalleeOffer) {
3196 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003197 PeerConnectionInterface::RTCConfiguration rtc_config;
3198 rtc_config.enable_rtp_data_channel = true;
3199 rtc_config.enable_dtls_srtp = false;
3200 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003201 ConnectFakeSignaling();
3202 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003203 caller()->AddAudioVideoTracks();
3204 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003205 caller()->CreateAndSetAndSignalOffer();
3206 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3207 ASSERT_NE(nullptr, caller()->data_channel());
3208 ASSERT_NE(nullptr, callee()->data_channel());
3209 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3210 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3211
3212 // Close the data channel on the callee, and do an updated offer/answer.
3213 callee()->data_channel()->Close();
3214 callee()->CreateAndSetAndSignalOffer();
3215 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3216 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3217 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3218}
3219
3220// Tests that data is buffered in an RTP data channel until an observer is
3221// registered for it.
3222//
3223// NOTE: RTP data channels can receive data before the underlying
3224// transport has detected that a channel is writable and thus data can be
3225// received before the data channel state changes to open. That is hard to test
3226// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003227TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003228 DataBufferedUntilRtpDataChannelObserverRegistered) {
3229 // Use fake clock and simulated network delay so that we predictably can wait
3230 // until an SCTP message has been delivered without "sleep()"ing.
3231 rtc::ScopedFakeClock fake_clock;
3232 // Some things use a time of "0" as a special value, so we need to start out
3233 // the fake clock at a nonzero time.
3234 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003235 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003236 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3237 virtual_socket_server()->UpdateDelayDistribution();
3238
Niels Möllerf06f9232018-08-07 12:32:18 +02003239 PeerConnectionInterface::RTCConfiguration rtc_config;
3240 rtc_config.enable_rtp_data_channel = true;
3241 rtc_config.enable_dtls_srtp = false;
3242 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003243 ConnectFakeSignaling();
3244 caller()->CreateDataChannel();
3245 caller()->CreateAndSetAndSignalOffer();
3246 ASSERT_TRUE(caller()->data_channel() != nullptr);
3247 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3248 kDefaultTimeout, fake_clock);
3249 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3250 kDefaultTimeout, fake_clock);
3251 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3252 callee()->data_channel()->state(), kDefaultTimeout,
3253 fake_clock);
3254
3255 // Unregister the observer which is normally automatically registered.
3256 callee()->data_channel()->UnregisterObserver();
3257 // Send data and advance fake clock until it should have been received.
3258 std::string data = "hello world";
3259 caller()->data_channel()->Send(DataBuffer(data));
3260 SIMULATED_WAIT(false, 50, fake_clock);
3261
3262 // Attach data channel and expect data to be received immediately. Note that
3263 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3264 // further, but data can be received even if the callback is asynchronous.
3265 MockDataChannelObserver new_observer(callee()->data_channel());
3266 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3267 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003268 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3269 // If this is not done a DCHECK can be hit in ports.cc, because a large
3270 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07003271 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07003272}
3273
3274// This test sets up a call between two parties with audio, video and but only
3275// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003276TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003277 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3278 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003279 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003280 rtc_config_1.enable_dtls_srtp = false;
3281 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3282 rtc_config_2.enable_dtls_srtp = false;
3283 rtc_config_2.enable_dtls_srtp = false;
3284 ASSERT_TRUE(
3285 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003286 ConnectFakeSignaling();
3287 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003288 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003289 caller()->AddAudioVideoTracks();
3290 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003291 caller()->CreateAndSetAndSignalOffer();
3292 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3293 // The caller should still have a data channel, but it should be closed, and
3294 // one should ever have been created for the callee.
3295 EXPECT_TRUE(caller()->data_channel() != nullptr);
3296 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3297 EXPECT_EQ(nullptr, callee()->data_channel());
3298}
3299
3300// This test sets up a call between two parties with audio, and video. When
3301// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003302TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003303 PeerConnectionInterface::RTCConfiguration rtc_config;
3304 rtc_config.enable_rtp_data_channel = true;
3305 rtc_config.enable_dtls_srtp = false;
3306 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003307 ConnectFakeSignaling();
3308 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003309 caller()->AddAudioVideoTracks();
3310 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003311 caller()->CreateAndSetAndSignalOffer();
3312 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3313 // Create data channel and do new offer and answer.
3314 caller()->CreateDataChannel();
3315 caller()->CreateAndSetAndSignalOffer();
3316 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3317 ASSERT_NE(nullptr, caller()->data_channel());
3318 ASSERT_NE(nullptr, callee()->data_channel());
3319 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3320 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3321 // Ensure data can be sent in both directions.
3322 std::string data = "hello world";
3323 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3324 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3325 kDefaultTimeout);
3326 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3327 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3328 kDefaultTimeout);
3329}
3330
3331#ifdef HAVE_SCTP
3332
3333// This test sets up a call between two parties with audio, video and an SCTP
3334// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003335TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003336 ASSERT_TRUE(CreatePeerConnectionWrappers());
3337 ConnectFakeSignaling();
3338 // Expect that data channel created on caller side will show up for callee as
3339 // well.
3340 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003341 caller()->AddAudioVideoTracks();
3342 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003343 caller()->CreateAndSetAndSignalOffer();
3344 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3345 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003346 MediaExpectations media_expectations;
3347 media_expectations.ExpectBidirectionalAudioAndVideo();
3348 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003349 // Caller data channel should already exist (it created one). Callee data
3350 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3351 ASSERT_NE(nullptr, caller()->data_channel());
3352 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3353 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3354 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3355
3356 // Ensure data can be sent in both directions.
3357 std::string data = "hello world";
3358 caller()->data_channel()->Send(DataBuffer(data));
3359 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3360 kDefaultTimeout);
3361 callee()->data_channel()->Send(DataBuffer(data));
3362 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3363 kDefaultTimeout);
3364}
3365
3366// Ensure that when the callee closes an SCTP data channel, the closing
3367// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003368TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003369 // Same procedure as above test.
3370 ASSERT_TRUE(CreatePeerConnectionWrappers());
3371 ConnectFakeSignaling();
3372 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003373 caller()->AddAudioVideoTracks();
3374 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003375 caller()->CreateAndSetAndSignalOffer();
3376 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3377 ASSERT_NE(nullptr, caller()->data_channel());
3378 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3379 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3380 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3381
3382 // Close the data channel on the callee side, and wait for it to reach the
3383 // "closed" state on both sides.
3384 callee()->data_channel()->Close();
3385 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3386 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3387}
3388
Seth Hampson2f0d7022018-02-20 11:54:42 -08003389TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003390 ASSERT_TRUE(CreatePeerConnectionWrappers());
3391 ConnectFakeSignaling();
3392 webrtc::DataChannelInit init;
3393 init.id = 53;
3394 init.maxRetransmits = 52;
3395 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003396 caller()->AddAudioVideoTracks();
3397 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003398 caller()->CreateAndSetAndSignalOffer();
3399 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003400 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3401 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003402 // Since "negotiated" is false, the "id" parameter should be ignored.
3403 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003404 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3405 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3406 EXPECT_FALSE(callee()->data_channel()->negotiated());
3407}
3408
deadbeef1dcb1642017-03-29 21:08:16 -07003409// Test usrsctp's ability to process unordered data stream, where data actually
3410// arrives out of order using simulated delays. Previously there have been some
3411// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003412TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003413 // Introduce random network delays.
3414 // Otherwise it's not a true "unordered" test.
3415 virtual_socket_server()->set_delay_mean(20);
3416 virtual_socket_server()->set_delay_stddev(5);
3417 virtual_socket_server()->UpdateDelayDistribution();
3418 // Normal procedure, but with unordered data channel config.
3419 ASSERT_TRUE(CreatePeerConnectionWrappers());
3420 ConnectFakeSignaling();
3421 webrtc::DataChannelInit init;
3422 init.ordered = false;
3423 caller()->CreateDataChannel(&init);
3424 caller()->CreateAndSetAndSignalOffer();
3425 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3426 ASSERT_NE(nullptr, caller()->data_channel());
3427 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3428 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3429 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3430
3431 static constexpr int kNumMessages = 100;
3432 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3433 static constexpr size_t kMaxMessageSize = 4096;
3434 // Create and send random messages.
3435 std::vector<std::string> sent_messages;
3436 for (int i = 0; i < kNumMessages; ++i) {
3437 size_t length =
3438 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3439 std::string message;
3440 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3441 caller()->data_channel()->Send(DataBuffer(message));
3442 callee()->data_channel()->Send(DataBuffer(message));
3443 sent_messages.push_back(message);
3444 }
3445
3446 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003447 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003448 caller()->data_observer()->received_message_count(),
3449 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003450 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003451 callee()->data_observer()->received_message_count(),
3452 kDefaultTimeout);
3453
3454 // Sort and compare to make sure none of the messages were corrupted.
3455 std::vector<std::string> caller_received_messages =
3456 caller()->data_observer()->messages();
3457 std::vector<std::string> callee_received_messages =
3458 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003459 absl::c_sort(sent_messages);
3460 absl::c_sort(caller_received_messages);
3461 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003462 EXPECT_EQ(sent_messages, caller_received_messages);
3463 EXPECT_EQ(sent_messages, callee_received_messages);
3464}
3465
3466// This test sets up a call between two parties with audio, and video. When
3467// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003468TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003469 ASSERT_TRUE(CreatePeerConnectionWrappers());
3470 ConnectFakeSignaling();
3471 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003472 caller()->AddAudioVideoTracks();
3473 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003474 caller()->CreateAndSetAndSignalOffer();
3475 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3476 // Create data channel and do new offer and answer.
3477 caller()->CreateDataChannel();
3478 caller()->CreateAndSetAndSignalOffer();
3479 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3480 // Caller data channel should already exist (it created one). Callee data
3481 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3482 ASSERT_NE(nullptr, caller()->data_channel());
3483 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3484 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3485 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3486 // Ensure data can be sent in both directions.
3487 std::string data = "hello world";
3488 caller()->data_channel()->Send(DataBuffer(data));
3489 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3490 kDefaultTimeout);
3491 callee()->data_channel()->Send(DataBuffer(data));
3492 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3493 kDefaultTimeout);
3494}
3495
deadbeef7914b8c2017-04-21 03:23:33 -07003496// Set up a connection initially just using SCTP data channels, later upgrading
3497// to audio/video, ensuring frames are received end-to-end. Effectively the
3498// inverse of the test above.
3499// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003500TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003501 ASSERT_TRUE(CreatePeerConnectionWrappers());
3502 ConnectFakeSignaling();
3503 // Do initial offer/answer with just data channel.
3504 caller()->CreateDataChannel();
3505 caller()->CreateAndSetAndSignalOffer();
3506 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3507 // Wait until data can be sent over the data channel.
3508 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3509 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3510 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3511
3512 // Do subsequent offer/answer with two-way audio and video. Audio and video
3513 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003514 caller()->AddAudioVideoTracks();
3515 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003516 caller()->CreateAndSetAndSignalOffer();
3517 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003518 MediaExpectations media_expectations;
3519 media_expectations.ExpectBidirectionalAudioAndVideo();
3520 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003521}
3522
deadbeef8b7e9ad2017-05-25 09:38:55 -07003523static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003524 cricket::SctpDataContentDescription* dcd_offer =
3525 GetFirstSctpDataContentDescription(desc);
Steve Antonb1c1de12017-12-21 15:14:30 -08003526 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003527 dcd_offer->set_use_sctpmap(false);
3528 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3529}
3530
3531// Test that the data channel works when a spec-compliant SCTP m= section is
3532// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3533// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003534TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003535 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3536 ASSERT_TRUE(CreatePeerConnectionWrappers());
3537 ConnectFakeSignaling();
3538 caller()->CreateDataChannel();
3539 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3540 caller()->CreateAndSetAndSignalOffer();
3541 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3542 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3543 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3544 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3545
3546 // Ensure data can be sent in both directions.
3547 std::string data = "hello world";
3548 caller()->data_channel()->Send(DataBuffer(data));
3549 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3550 kDefaultTimeout);
3551 callee()->data_channel()->Send(DataBuffer(data));
3552 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3553 kDefaultTimeout);
3554}
3555
deadbeef1dcb1642017-03-29 21:08:16 -07003556#endif // HAVE_SCTP
3557
Bjorn Mellema2eb0a72018-11-09 10:13:51 -08003558// This test sets up a call between two parties with a media transport data
3559// channel.
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003560TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelEndToEnd) {
3561 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003562 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3563 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003564 rtc_config.use_media_transport_for_data_channels = true;
3565 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3566 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3567 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3568 loopback_media_transports()->second_factory()));
3569 ConnectFakeSignaling();
3570
3571 // Expect that data channel created on caller side will show up for callee as
3572 // well.
3573 caller()->CreateDataChannel();
3574 caller()->CreateAndSetAndSignalOffer();
3575 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3576
3577 // Ensure that the media transport is ready.
3578 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3579 loopback_media_transports()->FlushAsyncInvokes();
3580
3581 // Caller data channel should already exist (it created one). Callee data
3582 // channel may not exist yet, since negotiation happens in-band, not in SDP.
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
3598// Ensure that when the callee closes a media transport data channel, the
3599// closing procedure results in the data channel being closed for the caller
3600// as well.
3601TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelCalleeCloses) {
3602 PeerConnectionInterface::RTCConfiguration rtc_config;
3603 rtc_config.use_media_transport_for_data_channels = true;
3604 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3605 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3606 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3607 loopback_media_transports()->second_factory()));
3608 ConnectFakeSignaling();
3609
3610 // Create a data channel on the caller and signal it to the callee.
3611 caller()->CreateDataChannel();
3612 caller()->CreateAndSetAndSignalOffer();
3613 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3614
3615 // Ensure that the media transport is ready.
3616 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3617 loopback_media_transports()->FlushAsyncInvokes();
3618
3619 // Data channels exist and open on both ends of the connection.
3620 ASSERT_NE(nullptr, caller()->data_channel());
3621 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3622 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3623 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3624
3625 // Close the data channel on the callee side, and wait for it to reach the
3626 // "closed" state on both sides.
3627 callee()->data_channel()->Close();
3628 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3629 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3630}
3631
3632TEST_P(PeerConnectionIntegrationTest,
3633 MediaTransportDataChannelConfigSentToOtherSide) {
3634 PeerConnectionInterface::RTCConfiguration rtc_config;
3635 rtc_config.use_media_transport_for_data_channels = true;
3636 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3637 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3638 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3639 loopback_media_transports()->second_factory()));
3640 ConnectFakeSignaling();
3641
3642 // Create a data channel with a non-default configuration and signal it to the
3643 // callee.
3644 webrtc::DataChannelInit init;
3645 init.id = 53;
3646 init.maxRetransmits = 52;
3647 caller()->CreateDataChannel("data-channel", &init);
3648 caller()->CreateAndSetAndSignalOffer();
3649 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3650
3651 // Ensure that the media transport is ready.
3652 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3653 loopback_media_transports()->FlushAsyncInvokes();
3654
3655 // Ensure that the data channel exists on the callee with the correct
3656 // configuration.
3657 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3658 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003659 // Since "negotiate" is false, the "id" parameter is ignored.
3660 EXPECT_NE(init.id, callee()->data_channel()->id());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003661 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3662 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3663 EXPECT_FALSE(callee()->data_channel()->negotiated());
3664}
3665
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003666TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgrade) {
3667 PeerConnectionInterface::RTCConfiguration rtc_config;
3668 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3669 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3670 rtc_config.use_media_transport = true;
3671 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3672 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3673 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3674 loopback_media_transports()->second_factory()));
3675 ConnectFakeSignaling();
3676
3677 // Do initial offer/answer with just a video track.
3678 caller()->AddVideoTrack();
3679 callee()->AddVideoTrack();
3680 caller()->CreateAndSetAndSignalOffer();
3681 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3682
3683 // Ensure that the media transport is ready.
3684 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3685 loopback_media_transports()->FlushAsyncInvokes();
3686
3687 // Now add an audio track and do another offer/answer.
3688 caller()->AddAudioTrack();
3689 callee()->AddAudioTrack();
3690 caller()->CreateAndSetAndSignalOffer();
3691 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3692
3693 // Ensure both audio and video frames are received end-to-end.
3694 MediaExpectations media_expectations;
3695 media_expectations.ExpectBidirectionalAudioAndVideo();
3696 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3697
3698 // The second offer should not have generated another media transport.
3699 // Media transport was kept alive, and was not recreated.
3700 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3701 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3702}
3703
3704TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgradeOnTheCallee) {
3705 PeerConnectionInterface::RTCConfiguration rtc_config;
3706 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3707 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3708 rtc_config.use_media_transport = true;
3709 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3710 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3711 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3712 loopback_media_transports()->second_factory()));
3713 ConnectFakeSignaling();
3714
3715 // Do initial offer/answer with just a video track.
3716 caller()->AddVideoTrack();
3717 callee()->AddVideoTrack();
3718 caller()->CreateAndSetAndSignalOffer();
3719 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3720
3721 // Ensure that the media transport is ready.
3722 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3723 loopback_media_transports()->FlushAsyncInvokes();
3724
3725 // Now add an audio track and do another offer/answer.
3726 caller()->AddAudioTrack();
3727 callee()->AddAudioTrack();
3728 callee()->CreateAndSetAndSignalOffer();
3729 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3730
3731 // Ensure both audio and video frames are received end-to-end.
3732 MediaExpectations media_expectations;
3733 media_expectations.ExpectBidirectionalAudioAndVideo();
3734 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3735
3736 // The second offer should not have generated another media transport.
3737 // Media transport was kept alive, and was not recreated.
3738 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3739 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3740}
3741
Niels Möllerc68d2822018-11-20 14:52:05 +01003742TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalAudio) {
3743 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003744 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3745 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Niels Möllerc68d2822018-11-20 14:52:05 +01003746 rtc_config.use_media_transport = true;
3747 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3748 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3749 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3750 loopback_media_transports()->second_factory()));
3751 ConnectFakeSignaling();
3752
3753 caller()->AddAudioTrack();
3754 callee()->AddAudioTrack();
3755 // Start offer/answer exchange and wait for it to complete.
3756 caller()->CreateAndSetAndSignalOffer();
3757 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3758
3759 // Ensure that the media transport is ready.
3760 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3761 loopback_media_transports()->FlushAsyncInvokes();
3762
3763 MediaExpectations media_expectations;
3764 media_expectations.ExpectBidirectionalAudio();
3765 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3766
3767 webrtc::MediaTransportPair::Stats first_stats =
3768 loopback_media_transports()->FirstStats();
3769 webrtc::MediaTransportPair::Stats second_stats =
3770 loopback_media_transports()->SecondStats();
3771
3772 EXPECT_GT(first_stats.received_audio_frames, 0);
3773 EXPECT_GE(second_stats.sent_audio_frames, first_stats.received_audio_frames);
3774
3775 EXPECT_GT(second_stats.received_audio_frames, 0);
3776 EXPECT_GE(first_stats.sent_audio_frames, second_stats.received_audio_frames);
3777}
3778
Niels Möller46879152019-01-07 15:54:47 +01003779TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalVideo) {
3780 PeerConnectionInterface::RTCConfiguration rtc_config;
3781 rtc_config.use_media_transport = true;
3782 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3783 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3784 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3785 loopback_media_transports()->second_factory()));
3786 ConnectFakeSignaling();
3787
3788 caller()->AddVideoTrack();
3789 callee()->AddVideoTrack();
3790 // Start offer/answer exchange and wait for it to complete.
3791 caller()->CreateAndSetAndSignalOffer();
3792 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3793
3794 // Ensure that the media transport is ready.
3795 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3796 loopback_media_transports()->FlushAsyncInvokes();
3797
3798 MediaExpectations media_expectations;
3799 media_expectations.ExpectBidirectionalVideo();
3800 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3801
3802 webrtc::MediaTransportPair::Stats first_stats =
3803 loopback_media_transports()->FirstStats();
3804 webrtc::MediaTransportPair::Stats second_stats =
3805 loopback_media_transports()->SecondStats();
3806
3807 EXPECT_GT(first_stats.received_video_frames, 0);
3808 EXPECT_GE(second_stats.sent_video_frames, first_stats.received_video_frames);
3809
3810 EXPECT_GT(second_stats.received_video_frames, 0);
3811 EXPECT_GE(first_stats.sent_video_frames, second_stats.received_video_frames);
3812}
3813
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003814TEST_P(PeerConnectionIntegrationTest,
3815 MediaTransportDataChannelUsesRtpBidirectionalVideo) {
3816 PeerConnectionInterface::RTCConfiguration rtc_config;
3817 rtc_config.use_media_transport = false;
3818 rtc_config.use_media_transport_for_data_channels = true;
3819 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3820 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3821 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3822 loopback_media_transports()->second_factory()));
3823 ConnectFakeSignaling();
3824
3825 caller()->AddVideoTrack();
3826 callee()->AddVideoTrack();
3827 // Start offer/answer exchange and wait for it to complete.
3828 caller()->CreateAndSetAndSignalOffer();
3829 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3830
3831 MediaExpectations media_expectations;
3832 media_expectations.ExpectBidirectionalVideo();
3833 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3834}
3835
deadbeef1dcb1642017-03-29 21:08:16 -07003836// Test that the ICE connection and gathering states eventually reach
3837// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003838TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003839 ASSERT_TRUE(CreatePeerConnectionWrappers());
3840 ConnectFakeSignaling();
3841 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003842 caller()->AddAudioVideoTracks();
3843 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003844 caller()->CreateAndSetAndSignalOffer();
3845 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3846 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3847 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3848 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3849 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3850 // After the best candidate pair is selected and all candidates are signaled,
3851 // the ICE connection state should reach "complete".
3852 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3853 // answerer/"callee" by default) only reaches "connected". When this is
3854 // fixed, this test should be updated.
3855 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3856 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00003857 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3858 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003859}
3860
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003861constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
3862 cricket::PORTALLOCATOR_DISABLE_RELAY |
3863 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003864
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003865// Use a mock resolver to resolve the hostname back to the original IP on both
3866// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003867TEST_P(PeerConnectionIntegrationTest,
3868 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003869 auto caller_resolver_factory =
3870 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3871 auto callee_resolver_factory =
3872 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3873 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
3874 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003875
3876 // This also verifies that the injected AsyncResolverFactory is used by
3877 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003878 EXPECT_CALL(*caller_resolver_factory, Create())
3879 .WillOnce(Return(&caller_async_resolver));
3880 webrtc::PeerConnectionDependencies caller_deps(nullptr);
3881 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
3882
3883 EXPECT_CALL(*callee_resolver_factory, Create())
3884 .WillOnce(Return(&callee_async_resolver));
3885 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3886 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
3887
3888 PeerConnectionInterface::RTCConfiguration config;
3889 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3890 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3891
3892 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3893 config, std::move(caller_deps), config, std::move(callee_deps)));
3894
3895 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
3896 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
3897
3898 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07003899 caller()->SetMdnsResponder(
3900 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
3901 callee()->SetMdnsResponder(
3902 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003903
3904 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003905
3906 ConnectFakeSignaling();
3907 caller()->AddAudioVideoTracks();
3908 callee()->AddAudioVideoTracks();
3909 caller()->CreateAndSetAndSignalOffer();
3910 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3911 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3912 caller()->ice_connection_state(), kDefaultTimeout);
3913 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3914 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08003915
3916 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3917 "WebRTC.PeerConnection.CandidatePairType_UDP",
3918 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003919}
3920
Steve Antonede9ca52017-10-16 13:04:27 -07003921// Test that firewalling the ICE connection causes the clients to identify the
3922// disconnected state and then removing the firewall causes them to reconnect.
3923class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003924 : public PeerConnectionIntegrationBaseTest,
3925 public ::testing::WithParamInterface<
3926 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003927 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003928 PeerConnectionIntegrationIceStatesTest()
3929 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3930 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003931 }
3932
3933 void StartStunServer(const SocketAddress& server_address) {
3934 stun_server_.reset(
3935 cricket::TestStunServer::Create(network_thread(), server_address));
3936 }
3937
3938 bool TestIPv6() {
3939 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3940 }
3941
3942 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003943 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
3944 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07003945 }
3946
3947 std::vector<SocketAddress> CallerAddresses() {
3948 std::vector<SocketAddress> addresses;
3949 addresses.push_back(SocketAddress("1.1.1.1", 0));
3950 if (TestIPv6()) {
3951 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3952 }
3953 return addresses;
3954 }
3955
3956 std::vector<SocketAddress> CalleeAddresses() {
3957 std::vector<SocketAddress> addresses;
3958 addresses.push_back(SocketAddress("2.2.2.2", 0));
3959 if (TestIPv6()) {
3960 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3961 }
3962 return addresses;
3963 }
3964
3965 void SetUpNetworkInterfaces() {
3966 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07003967 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
3968 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07003969
3970 // Add network addresses for test.
3971 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003972 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003973 }
3974 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003975 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003976 }
3977 }
3978
3979 private:
3980 uint32_t port_allocator_flags_;
3981 std::unique_ptr<cricket::TestStunServer> stun_server_;
3982};
3983
3984// Tests that the PeerConnection goes through all the ICE gathering/connection
3985// states over the duration of the call. This includes Disconnected and Failed
3986// states, induced by putting a firewall between the peers and waiting for them
3987// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003988TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01003989 rtc::ScopedFakeClock fake_clock;
3990 // Some things use a time of "0" as a special value, so we need to start out
3991 // the fake clock at a nonzero time.
3992 fake_clock.AdvanceTime(TimeDelta::seconds(1));
Steve Antonede9ca52017-10-16 13:04:27 -07003993
3994 const SocketAddress kStunServerAddress =
3995 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3996 StartStunServer(kStunServerAddress);
3997
3998 PeerConnectionInterface::RTCConfiguration config;
3999 PeerConnectionInterface::IceServer ice_stun_server;
4000 ice_stun_server.urls.push_back(
4001 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4002 kStunServerAddress.PortAsString());
4003 config.servers.push_back(ice_stun_server);
4004
4005 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4006 ConnectFakeSignaling();
4007 SetPortAllocatorFlags();
4008 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004009 caller()->AddAudioVideoTracks();
4010 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004011
4012 // Initial state before anything happens.
4013 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4014 caller()->ice_gathering_state());
4015 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4016 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004017 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4018 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004019
4020 // Start the call by creating the offer, setting it as the local description,
4021 // then sending it to the peer who will respond with an answer. This happens
4022 // asynchronously so that we can watch the states as it runs in the
4023 // background.
4024 caller()->CreateAndSetAndSignalOffer();
4025
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004026 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
4027 caller()->ice_connection_state());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004028 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004029 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004030
4031 // Verify that the observer was notified of the intermediate transitions.
4032 EXPECT_THAT(caller()->ice_connection_state_history(),
4033 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4034 PeerConnectionInterface::kIceConnectionConnected,
4035 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004036 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4037 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4038 PeerConnectionInterface::kIceConnectionConnected,
4039 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004040 EXPECT_THAT(
4041 caller()->peer_connection_state_history(),
4042 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004043 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004044 EXPECT_THAT(caller()->ice_gathering_state_history(),
4045 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4046 PeerConnectionInterface::kIceGatheringComplete));
4047
4048 // Block connections to/from the caller and wait for ICE to become
4049 // disconnected.
4050 for (const auto& caller_address : CallerAddresses()) {
4051 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4052 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004053 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004054 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4055 caller()->ice_connection_state(), kDefaultTimeout,
4056 fake_clock);
4057 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4058 caller()->standardized_ice_connection_state(),
4059 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004060
4061 // Let ICE re-establish by removing the firewall rules.
4062 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004063 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004064 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4065 caller()->ice_connection_state(), kDefaultTimeout,
4066 fake_clock);
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004067 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004068 caller()->standardized_ice_connection_state(),
4069 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004070
4071 // According to RFC7675, if there is no response within 30 seconds then the
4072 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004073 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004074 constexpr int kConsentTimeout = 30000;
4075 for (const auto& caller_address : CallerAddresses()) {
4076 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4077 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004078 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004079 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4080 caller()->ice_connection_state(), kConsentTimeout,
4081 fake_clock);
4082 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4083 caller()->standardized_ice_connection_state(),
4084 kConsentTimeout, fake_clock);
4085
4086 // We need to manually close the peerconnections before the fake clock goes
4087 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4088 // return to using non-faked time.
4089 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4090 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
4091}
4092
4093// Tests that if the connection doesn't get set up properly we eventually reach
4094// the "failed" iceConnectionState.
4095TEST_P(PeerConnectionIntegrationIceStatesTest, IceStateSetupFailure) {
4096 rtc::ScopedFakeClock fake_clock;
4097 // Some things use a time of "0" as a special value, so we need to start out
4098 // the fake clock at a nonzero time.
4099 fake_clock.AdvanceTime(TimeDelta::seconds(1));
4100
4101 // Block connections to/from the caller and wait for ICE to become
4102 // disconnected.
4103 for (const auto& caller_address : CallerAddresses()) {
4104 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4105 }
4106
4107 ASSERT_TRUE(CreatePeerConnectionWrappers());
4108 ConnectFakeSignaling();
4109 SetPortAllocatorFlags();
4110 SetUpNetworkInterfaces();
4111 caller()->AddAudioVideoTracks();
4112 caller()->CreateAndSetAndSignalOffer();
4113
4114 // According to RFC7675, if there is no response within 30 seconds then the
4115 // peer should consider the other side to have rejected the connection. This
4116 // is signaled by the state transitioning to "failed".
4117 constexpr int kConsentTimeout = 30000;
4118 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4119 caller()->standardized_ice_connection_state(),
4120 kConsentTimeout, fake_clock);
4121
4122 // We need to manually close the peerconnections before the fake clock goes
4123 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4124 // return to using non-faked time.
4125 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4126 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
Steve Antonede9ca52017-10-16 13:04:27 -07004127}
4128
4129// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4130// and that the statistics in the metric observers are updated correctly.
4131TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4132 ASSERT_TRUE(CreatePeerConnectionWrappers());
4133 ConnectFakeSignaling();
4134 SetPortAllocatorFlags();
4135 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004136 caller()->AddAudioVideoTracks();
4137 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004138 caller()->CreateAndSetAndSignalOffer();
4139
4140 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4141
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004142 // TODO(bugs.webrtc.org/9456): Fix it.
4143 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4144 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4145 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4146 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004147 if (TestIPv6()) {
4148 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4149 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004150 EXPECT_EQ(0, num_best_ipv4);
4151 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004152 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004153 EXPECT_EQ(1, num_best_ipv4);
4154 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004155 }
4156
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004157 EXPECT_EQ(0, webrtc::metrics::NumEvents(
4158 "WebRTC.PeerConnection.CandidatePairType_UDP",
4159 webrtc::kIceCandidatePairHostHost));
4160 EXPECT_EQ(1, webrtc::metrics::NumEvents(
4161 "WebRTC.PeerConnection.CandidatePairType_UDP",
4162 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004163}
4164
4165constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4166 cricket::PORTALLOCATOR_DISABLE_STUN |
4167 cricket::PORTALLOCATOR_DISABLE_RELAY;
4168constexpr uint32_t kFlagsIPv6NoStun =
4169 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4170 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4171constexpr uint32_t kFlagsIPv4Stun =
4172 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4173
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004174INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004175 PeerConnectionIntegrationTest,
4176 PeerConnectionIntegrationIceStatesTest,
4177 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4178 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4179 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4180 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004181
deadbeef1dcb1642017-03-29 21:08:16 -07004182// This test sets up a call between two parties with audio and video.
4183// During the call, the caller restarts ICE and the test verifies that
4184// new ICE candidates are generated and audio and video still can flow, and the
4185// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004186TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004187 ASSERT_TRUE(CreatePeerConnectionWrappers());
4188 ConnectFakeSignaling();
4189 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004190 caller()->AddAudioVideoTracks();
4191 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004192 caller()->CreateAndSetAndSignalOffer();
4193 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4194 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4195 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004196 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4197 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004198
4199 // To verify that the ICE restart actually occurs, get
4200 // ufrag/password/candidates before and after restart.
4201 // Create an SDP string of the first audio candidate for both clients.
4202 const webrtc::IceCandidateCollection* audio_candidates_caller =
4203 caller()->pc()->local_description()->candidates(0);
4204 const webrtc::IceCandidateCollection* audio_candidates_callee =
4205 callee()->pc()->local_description()->candidates(0);
4206 ASSERT_GT(audio_candidates_caller->count(), 0u);
4207 ASSERT_GT(audio_candidates_callee->count(), 0u);
4208 std::string caller_candidate_pre_restart;
4209 ASSERT_TRUE(
4210 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4211 std::string callee_candidate_pre_restart;
4212 ASSERT_TRUE(
4213 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4214 const cricket::SessionDescription* desc =
4215 caller()->pc()->local_description()->description();
4216 std::string caller_ufrag_pre_restart =
4217 desc->transport_infos()[0].description.ice_ufrag;
4218 desc = callee()->pc()->local_description()->description();
4219 std::string callee_ufrag_pre_restart =
4220 desc->transport_infos()[0].description.ice_ufrag;
4221
Alex Drake00c7ecf2019-08-06 10:54:47 -07004222 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004223 // Have the caller initiate an ICE restart.
4224 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4225 caller()->CreateAndSetAndSignalOffer();
4226 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4227 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4228 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004229 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004230 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4231
4232 // Grab the ufrags/candidates again.
4233 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4234 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4235 ASSERT_GT(audio_candidates_caller->count(), 0u);
4236 ASSERT_GT(audio_candidates_callee->count(), 0u);
4237 std::string caller_candidate_post_restart;
4238 ASSERT_TRUE(
4239 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4240 std::string callee_candidate_post_restart;
4241 ASSERT_TRUE(
4242 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4243 desc = caller()->pc()->local_description()->description();
4244 std::string caller_ufrag_post_restart =
4245 desc->transport_infos()[0].description.ice_ufrag;
4246 desc = callee()->pc()->local_description()->description();
4247 std::string callee_ufrag_post_restart =
4248 desc->transport_infos()[0].description.ice_ufrag;
4249 // Sanity check that an ICE restart was actually negotiated in SDP.
4250 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4251 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4252 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4253 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07004254 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004255
4256 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004257 MediaExpectations media_expectations;
4258 media_expectations.ExpectBidirectionalAudioAndVideo();
4259 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004260}
4261
4262// Verify that audio/video can be received end-to-end when ICE renomination is
4263// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004264TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004265 PeerConnectionInterface::RTCConfiguration config;
4266 config.enable_ice_renomination = true;
4267 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4268 ConnectFakeSignaling();
4269 // Do normal offer/answer and wait for some frames to be received in each
4270 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004271 caller()->AddAudioVideoTracks();
4272 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004273 caller()->CreateAndSetAndSignalOffer();
4274 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4275 // Sanity check that ICE renomination was actually negotiated.
4276 const cricket::SessionDescription* desc =
4277 caller()->pc()->local_description()->description();
4278 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004279 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004280 }
4281 desc = callee()->pc()->local_description()->description();
4282 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004283 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004284 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004285 MediaExpectations media_expectations;
4286 media_expectations.ExpectBidirectionalAudioAndVideo();
4287 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004288}
4289
Steve Anton6f25b092017-10-23 09:39:20 -07004290// With a max bundle policy and RTCP muxing, adding a new media description to
4291// the connection should not affect ICE at all because the new media will use
4292// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004293TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004294 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004295 PeerConnectionInterface::RTCConfiguration config;
4296 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4297 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4298 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4299 config, PeerConnectionInterface::RTCConfiguration()));
4300 ConnectFakeSignaling();
4301
Steve Anton15324772018-01-16 10:26:49 -08004302 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004303 caller()->CreateAndSetAndSignalOffer();
4304 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004305 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4306 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004307
4308 caller()->clear_ice_connection_state_history();
4309
Steve Anton15324772018-01-16 10:26:49 -08004310 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004311 caller()->CreateAndSetAndSignalOffer();
4312 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4313
4314 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4315}
4316
deadbeef1dcb1642017-03-29 21:08:16 -07004317// This test sets up a call between two parties with audio and video. It then
4318// renegotiates setting the video m-line to "port 0", then later renegotiates
4319// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004320TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004321 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4322 ASSERT_TRUE(CreatePeerConnectionWrappers());
4323 ConnectFakeSignaling();
4324
4325 // Do initial negotiation, only sending media from the caller. Will result in
4326 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004327 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004328 caller()->CreateAndSetAndSignalOffer();
4329 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4330
4331 // Negotiate again, disabling the video "m=" section (the callee will set the
4332 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004333 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4334 PeerConnectionInterface::RTCOfferAnswerOptions options;
4335 options.offer_to_receive_video = 0;
4336 callee()->SetOfferAnswerOptions(options);
4337 } else {
4338 callee()->SetRemoteOfferHandler([this] {
4339 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4340 });
4341 }
deadbeef1dcb1642017-03-29 21:08:16 -07004342 caller()->CreateAndSetAndSignalOffer();
4343 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4344 // Sanity check that video "m=" section was actually rejected.
4345 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4346 callee()->pc()->local_description()->description());
4347 ASSERT_NE(nullptr, answer_video_content);
4348 ASSERT_TRUE(answer_video_content->rejected);
4349
4350 // Enable video and do negotiation again, making sure video is received
4351 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004352 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4353 PeerConnectionInterface::RTCOfferAnswerOptions options;
4354 options.offer_to_receive_video = 1;
4355 callee()->SetOfferAnswerOptions(options);
4356 } else {
4357 // The caller's transceiver is stopped, so we need to add another track.
4358 auto caller_transceiver =
4359 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4360 EXPECT_TRUE(caller_transceiver->stopped());
4361 caller()->AddVideoTrack();
4362 }
4363 callee()->AddVideoTrack();
4364 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004365 caller()->CreateAndSetAndSignalOffer();
4366 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004367
deadbeef1dcb1642017-03-29 21:08:16 -07004368 // Verify the caller receives frames from the newly added stream, and the
4369 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004370 MediaExpectations media_expectations;
4371 media_expectations.CalleeExpectsSomeAudio();
4372 media_expectations.ExpectBidirectionalVideo();
4373 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004374}
4375
deadbeef1dcb1642017-03-29 21:08:16 -07004376// This tests that if we negotiate after calling CreateSender but before we
4377// have a track, then set a track later, frames from the newly-set track are
4378// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004379TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004380 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4381 ASSERT_TRUE(CreatePeerConnectionWrappers());
4382 ConnectFakeSignaling();
4383 auto caller_audio_sender =
4384 caller()->pc()->CreateSender("audio", "caller_stream");
4385 auto caller_video_sender =
4386 caller()->pc()->CreateSender("video", "caller_stream");
4387 auto callee_audio_sender =
4388 callee()->pc()->CreateSender("audio", "callee_stream");
4389 auto callee_video_sender =
4390 callee()->pc()->CreateSender("video", "callee_stream");
4391 caller()->CreateAndSetAndSignalOffer();
4392 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4393 // Wait for ICE to complete, without any tracks being set.
4394 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4395 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4396 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4397 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4398 // Now set the tracks, and expect frames to immediately start flowing.
4399 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4400 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4401 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4402 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004403 MediaExpectations media_expectations;
4404 media_expectations.ExpectBidirectionalAudioAndVideo();
4405 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4406}
4407
4408// This tests that if we negotiate after calling AddTransceiver but before we
4409// have a track, then set a track later, frames from the newly-set tracks are
4410// received end-to-end.
4411TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4412 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4413 ASSERT_TRUE(CreatePeerConnectionWrappers());
4414 ConnectFakeSignaling();
4415 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4416 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4417 auto caller_audio_sender = audio_result.MoveValue()->sender();
4418 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4419 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4420 auto caller_video_sender = video_result.MoveValue()->sender();
4421 callee()->SetRemoteOfferHandler([this] {
4422 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4423 callee()->pc()->GetTransceivers()[0]->SetDirection(
4424 RtpTransceiverDirection::kSendRecv);
4425 callee()->pc()->GetTransceivers()[1]->SetDirection(
4426 RtpTransceiverDirection::kSendRecv);
4427 });
4428 caller()->CreateAndSetAndSignalOffer();
4429 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4430 // Wait for ICE to complete, without any tracks being set.
4431 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4432 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4433 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4434 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4435 // Now set the tracks, and expect frames to immediately start flowing.
4436 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4437 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4438 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4439 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4440 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4441 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4442 MediaExpectations media_expectations;
4443 media_expectations.ExpectBidirectionalAudioAndVideo();
4444 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004445}
4446
4447// This test verifies that a remote video track can be added via AddStream,
4448// and sent end-to-end. For this particular test, it's simply echoed back
4449// from the caller to the callee, rather than being forwarded to a third
4450// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004451TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004452 ASSERT_TRUE(CreatePeerConnectionWrappers());
4453 ConnectFakeSignaling();
4454 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004455 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004456 caller()->CreateAndSetAndSignalOffer();
4457 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004458 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004459
4460 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4461 // time).
4462 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4463 callee()->CreateAndSetAndSignalOffer();
4464 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4465
Seth Hampson2f0d7022018-02-20 11:54:42 -08004466 MediaExpectations media_expectations;
4467 media_expectations.ExpectBidirectionalVideo();
4468 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004469}
4470
4471// Test that we achieve the expected end-to-end connection time, using a
4472// fake clock and simulated latency on the media and signaling paths.
4473// We use a TURN<->TURN connection because this is usually the quickest to
4474// set up initially, especially when we're confident the connection will work
4475// and can start sending media before we get a STUN response.
4476//
4477// With various optimizations enabled, here are the network delays we expect to
4478// be on the critical path:
4479// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4480// signaling answer (with DTLS fingerprint).
4481// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4482// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4483// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004484TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004485 rtc::ScopedFakeClock fake_clock;
4486 // Some things use a time of "0" as a special value, so we need to start out
4487 // the fake clock at a nonzero time.
4488 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02004489 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07004490
4491 static constexpr int media_hop_delay_ms = 50;
4492 static constexpr int signaling_trip_delay_ms = 500;
4493 // For explanation of these values, see comment above.
4494 static constexpr int required_media_hops = 9;
4495 static constexpr int required_signaling_trips = 2;
4496 // For internal delays (such as posting an event asychronously).
4497 static constexpr int allowed_internal_delay_ms = 20;
4498 static constexpr int total_connection_time_ms =
4499 media_hop_delay_ms * required_media_hops +
4500 signaling_trip_delay_ms * required_signaling_trips +
4501 allowed_internal_delay_ms;
4502
4503 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4504 3478};
4505 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4506 0};
4507 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4508 3478};
4509 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4510 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004511 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4512 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004513
Seth Hampsonaed71642018-06-11 07:41:32 -07004514 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4515 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004516 // Bypass permission check on received packets so media can be sent before
4517 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004518 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4519 turn_server_1->set_enable_permission_checks(false);
4520 });
4521 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4522 turn_server_2->set_enable_permission_checks(false);
4523 });
deadbeef1dcb1642017-03-29 21:08:16 -07004524
4525 PeerConnectionInterface::RTCConfiguration client_1_config;
4526 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4527 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4528 ice_server_1.username = "test";
4529 ice_server_1.password = "test";
4530 client_1_config.servers.push_back(ice_server_1);
4531 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4532 client_1_config.presume_writable_when_fully_relayed = true;
4533
4534 PeerConnectionInterface::RTCConfiguration client_2_config;
4535 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4536 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4537 ice_server_2.username = "test";
4538 ice_server_2.password = "test";
4539 client_2_config.servers.push_back(ice_server_2);
4540 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4541 client_2_config.presume_writable_when_fully_relayed = true;
4542
4543 ASSERT_TRUE(
4544 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4545 // Set up the simulated delays.
4546 SetSignalingDelayMs(signaling_trip_delay_ms);
4547 ConnectFakeSignaling();
4548 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4549 virtual_socket_server()->UpdateDelayDistribution();
4550
4551 // Set "offer to receive audio/video" without adding any tracks, so we just
4552 // set up ICE/DTLS with no media.
4553 PeerConnectionInterface::RTCOfferAnswerOptions options;
4554 options.offer_to_receive_audio = 1;
4555 options.offer_to_receive_video = 1;
4556 caller()->SetOfferAnswerOptions(options);
4557 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004558 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4559 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004560 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4561 // If this is not done a DCHECK can be hit in ports.cc, because a large
4562 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07004563 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07004564}
4565
Jonas Orelandbdcee282017-10-10 14:01:40 +02004566// Verify that a TurnCustomizer passed in through RTCConfiguration
4567// is actually used by the underlying TURN candidate pair.
4568// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004569TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004570 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4571 3478};
4572 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4573 0};
4574 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4575 3478};
4576 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4577 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004578 CreateTurnServer(turn_server_1_internal_address,
4579 turn_server_1_external_address);
4580 CreateTurnServer(turn_server_2_internal_address,
4581 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004582
4583 PeerConnectionInterface::RTCConfiguration client_1_config;
4584 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4585 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4586 ice_server_1.username = "test";
4587 ice_server_1.password = "test";
4588 client_1_config.servers.push_back(ice_server_1);
4589 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004590 auto* customizer1 = CreateTurnCustomizer();
4591 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004592
4593 PeerConnectionInterface::RTCConfiguration client_2_config;
4594 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4595 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4596 ice_server_2.username = "test";
4597 ice_server_2.password = "test";
4598 client_2_config.servers.push_back(ice_server_2);
4599 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004600 auto* customizer2 = CreateTurnCustomizer();
4601 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004602
4603 ASSERT_TRUE(
4604 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4605 ConnectFakeSignaling();
4606
4607 // Set "offer to receive audio/video" without adding any tracks, so we just
4608 // set up ICE/DTLS with no media.
4609 PeerConnectionInterface::RTCOfferAnswerOptions options;
4610 options.offer_to_receive_audio = 1;
4611 options.offer_to_receive_video = 1;
4612 caller()->SetOfferAnswerOptions(options);
4613 caller()->CreateAndSetAndSignalOffer();
4614 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4615
Seth Hampsonaed71642018-06-11 07:41:32 -07004616 ExpectTurnCustomizerCountersIncremented(customizer1);
4617 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004618}
4619
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004620// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4621// send media between the caller and the callee.
4622TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4623 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4624 3478};
4625 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4626
4627 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004628 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4629 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004630
4631 webrtc::PeerConnectionInterface::IceServer ice_server;
4632 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4633 ice_server.username = "test";
4634 ice_server.password = "test";
4635
4636 PeerConnectionInterface::RTCConfiguration client_1_config;
4637 client_1_config.servers.push_back(ice_server);
4638 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4639
4640 PeerConnectionInterface::RTCConfiguration client_2_config;
4641 client_2_config.servers.push_back(ice_server);
4642 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4643
4644 ASSERT_TRUE(
4645 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4646
4647 // Do normal offer/answer and wait for ICE to complete.
4648 ConnectFakeSignaling();
4649 caller()->AddAudioVideoTracks();
4650 callee()->AddAudioVideoTracks();
4651 caller()->CreateAndSetAndSignalOffer();
4652 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4653 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4654 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4655
4656 MediaExpectations media_expectations;
4657 media_expectations.ExpectBidirectionalAudioAndVideo();
4658 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4659}
4660
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004661// Verify that a SSLCertificateVerifier passed in through
4662// PeerConnectionDependencies is actually used by the underlying SSL
4663// implementation to determine whether a certificate presented by the TURN
4664// server is accepted by the client. Note that openssladapter_unittest.cc
4665// contains more detailed, lower-level tests.
4666TEST_P(PeerConnectionIntegrationTest,
4667 SSLCertificateVerifierUsedForTurnConnections) {
4668 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4669 3478};
4670 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4671
4672 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4673 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004674 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4675 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004676
4677 webrtc::PeerConnectionInterface::IceServer ice_server;
4678 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4679 ice_server.username = "test";
4680 ice_server.password = "test";
4681
4682 PeerConnectionInterface::RTCConfiguration client_1_config;
4683 client_1_config.servers.push_back(ice_server);
4684 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4685
4686 PeerConnectionInterface::RTCConfiguration client_2_config;
4687 client_2_config.servers.push_back(ice_server);
4688 // Setting the type to kRelay forces the connection to go through a TURN
4689 // server.
4690 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4691
4692 // Get a copy to the pointer so we can verify calls later.
4693 rtc::TestCertificateVerifier* client_1_cert_verifier =
4694 new rtc::TestCertificateVerifier();
4695 client_1_cert_verifier->verify_certificate_ = true;
4696 rtc::TestCertificateVerifier* client_2_cert_verifier =
4697 new rtc::TestCertificateVerifier();
4698 client_2_cert_verifier->verify_certificate_ = true;
4699
4700 // Create the dependencies with the test certificate verifier.
4701 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4702 client_1_deps.tls_cert_verifier =
4703 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4704 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4705 client_2_deps.tls_cert_verifier =
4706 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4707
4708 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4709 client_1_config, std::move(client_1_deps), client_2_config,
4710 std::move(client_2_deps)));
4711 ConnectFakeSignaling();
4712
4713 // Set "offer to receive audio/video" without adding any tracks, so we just
4714 // set up ICE/DTLS with no media.
4715 PeerConnectionInterface::RTCOfferAnswerOptions options;
4716 options.offer_to_receive_audio = 1;
4717 options.offer_to_receive_video = 1;
4718 caller()->SetOfferAnswerOptions(options);
4719 caller()->CreateAndSetAndSignalOffer();
4720 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4721
4722 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4723 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004724}
4725
4726TEST_P(PeerConnectionIntegrationTest,
4727 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4728 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4729 3478};
4730 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4731
4732 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4733 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004734 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4735 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004736
4737 webrtc::PeerConnectionInterface::IceServer ice_server;
4738 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4739 ice_server.username = "test";
4740 ice_server.password = "test";
4741
4742 PeerConnectionInterface::RTCConfiguration client_1_config;
4743 client_1_config.servers.push_back(ice_server);
4744 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4745
4746 PeerConnectionInterface::RTCConfiguration client_2_config;
4747 client_2_config.servers.push_back(ice_server);
4748 // Setting the type to kRelay forces the connection to go through a TURN
4749 // server.
4750 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4751
4752 // Get a copy to the pointer so we can verify calls later.
4753 rtc::TestCertificateVerifier* client_1_cert_verifier =
4754 new rtc::TestCertificateVerifier();
4755 client_1_cert_verifier->verify_certificate_ = false;
4756 rtc::TestCertificateVerifier* client_2_cert_verifier =
4757 new rtc::TestCertificateVerifier();
4758 client_2_cert_verifier->verify_certificate_ = false;
4759
4760 // Create the dependencies with the test certificate verifier.
4761 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4762 client_1_deps.tls_cert_verifier =
4763 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4764 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4765 client_2_deps.tls_cert_verifier =
4766 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4767
4768 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4769 client_1_config, std::move(client_1_deps), client_2_config,
4770 std::move(client_2_deps)));
4771 ConnectFakeSignaling();
4772
4773 // Set "offer to receive audio/video" without adding any tracks, so we just
4774 // set up ICE/DTLS with no media.
4775 PeerConnectionInterface::RTCOfferAnswerOptions options;
4776 options.offer_to_receive_audio = 1;
4777 options.offer_to_receive_video = 1;
4778 caller()->SetOfferAnswerOptions(options);
4779 caller()->CreateAndSetAndSignalOffer();
4780 bool wait_res = true;
4781 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4782 // properly, should be able to just wait for a state of "failed" instead of
4783 // waiting a fixed 10 seconds.
4784 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4785 ASSERT_FALSE(wait_res);
4786
4787 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4788 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004789}
4790
deadbeefc964d0b2017-04-03 10:03:35 -07004791// Test that audio and video flow end-to-end when codec names don't use the
4792// expected casing, given that they're supposed to be case insensitive. To test
4793// this, all but one codec is removed from each media description, and its
4794// casing is changed.
4795//
4796// In the past, this has regressed and caused crashes/black video, due to the
4797// fact that code at some layers was doing case-insensitive comparisons and
4798// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004799TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004800 ASSERT_TRUE(CreatePeerConnectionWrappers());
4801 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004802 caller()->AddAudioVideoTracks();
4803 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004804
4805 // Remove all but one audio/video codec (opus and VP8), and change the
4806 // casing of the caller's generated offer.
4807 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4808 cricket::AudioContentDescription* audio =
4809 GetFirstAudioContentDescription(description);
4810 ASSERT_NE(nullptr, audio);
4811 auto audio_codecs = audio->codecs();
4812 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4813 [](const cricket::AudioCodec& codec) {
4814 return codec.name != "opus";
4815 }),
4816 audio_codecs.end());
4817 ASSERT_EQ(1u, audio_codecs.size());
4818 audio_codecs[0].name = "OpUs";
4819 audio->set_codecs(audio_codecs);
4820
4821 cricket::VideoContentDescription* video =
4822 GetFirstVideoContentDescription(description);
4823 ASSERT_NE(nullptr, video);
4824 auto video_codecs = video->codecs();
4825 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4826 [](const cricket::VideoCodec& codec) {
4827 return codec.name != "VP8";
4828 }),
4829 video_codecs.end());
4830 ASSERT_EQ(1u, video_codecs.size());
4831 video_codecs[0].name = "vP8";
4832 video->set_codecs(video_codecs);
4833 });
4834
4835 caller()->CreateAndSetAndSignalOffer();
4836 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4837
4838 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004839 MediaExpectations media_expectations;
4840 media_expectations.ExpectBidirectionalAudioAndVideo();
4841 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004842}
4843
Jonas Oreland49ac5952018-09-26 16:04:32 +02004844TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004845 ASSERT_TRUE(CreatePeerConnectionWrappers());
4846 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004847 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004848 caller()->CreateAndSetAndSignalOffer();
4849 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004850 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004851 MediaExpectations media_expectations;
4852 media_expectations.CalleeExpectsSomeAudio(1);
4853 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004854 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004855 auto receiver = callee()->pc()->GetReceivers()[0];
4856 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004857 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004858 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4859 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004860 sources[0].source_id());
4861 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4862}
4863
4864TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4865 ASSERT_TRUE(CreatePeerConnectionWrappers());
4866 ConnectFakeSignaling();
4867 caller()->AddVideoTrack();
4868 caller()->CreateAndSetAndSignalOffer();
4869 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4870 // Wait for one video frame to be received by the callee.
4871 MediaExpectations media_expectations;
4872 media_expectations.CalleeExpectsSomeVideo(1);
4873 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4874 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4875 auto receiver = callee()->pc()->GetReceivers()[0];
4876 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4877 auto sources = receiver->GetSources();
4878 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02004879 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004880 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4881 sources[0].source_id());
4882 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004883}
4884
deadbeef2f425aa2017-04-14 10:41:32 -07004885// Test that if a track is removed and added again with a different stream ID,
4886// the new stream ID is successfully communicated in SDP and media continues to
4887// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004888// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4889// it will not reuse a transceiver that has already been sending. After creating
4890// a new transceiver it tries to create an offer with two senders of the same
4891// track ids and it fails.
4892TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004893 ASSERT_TRUE(CreatePeerConnectionWrappers());
4894 ConnectFakeSignaling();
4895
deadbeef2f425aa2017-04-14 10:41:32 -07004896 // Add track using stream 1, do offer/answer.
4897 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4898 caller()->CreateLocalAudioTrack();
4899 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004900 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004901 caller()->CreateAndSetAndSignalOffer();
4902 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004903 {
4904 MediaExpectations media_expectations;
4905 media_expectations.CalleeExpectsSomeAudio(1);
4906 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4907 }
deadbeef2f425aa2017-04-14 10:41:32 -07004908 // Remove the sender, and create a new one with the new stream.
4909 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004910 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004911 caller()->CreateAndSetAndSignalOffer();
4912 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4913 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004914 {
4915 MediaExpectations media_expectations;
4916 media_expectations.CalleeExpectsSomeAudio();
4917 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4918 }
deadbeef2f425aa2017-04-14 10:41:32 -07004919}
4920
Seth Hampson2f0d7022018-02-20 11:54:42 -08004921TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004922 ASSERT_TRUE(CreatePeerConnectionWrappers());
4923 ConnectFakeSignaling();
4924
Karl Wiberg918f50c2018-07-05 11:40:33 +02004925 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02004926 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
4927 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02004928 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004929 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4930 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004931
Steve Anton15324772018-01-16 10:26:49 -08004932 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004933 caller()->CreateAndSetAndSignalOffer();
4934 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4935}
4936
Steve Antonede9ca52017-10-16 13:04:27 -07004937// Test that if candidates are only signaled by applying full session
4938// descriptions (instead of using AddIceCandidate), the peers can connect to
4939// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004940TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004941 ASSERT_TRUE(CreatePeerConnectionWrappers());
4942 // Each side will signal the session descriptions but not candidates.
4943 ConnectFakeSignalingForSdpOnly();
4944
4945 // Add audio video track and exchange the initial offer/answer with media
4946 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004947 caller()->AddAudioVideoTracks();
4948 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004949 caller()->CreateAndSetAndSignalOffer();
4950
4951 // Wait for all candidates to be gathered on both the caller and callee.
4952 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4953 caller()->ice_gathering_state(), kDefaultTimeout);
4954 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4955 callee()->ice_gathering_state(), kDefaultTimeout);
4956
4957 // The candidates will now be included in the session description, so
4958 // signaling them will start the ICE connection.
4959 caller()->CreateAndSetAndSignalOffer();
4960 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4961
4962 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004963 MediaExpectations media_expectations;
4964 media_expectations.ExpectBidirectionalAudioAndVideo();
4965 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004966}
4967
henrika5f6bf242017-11-01 11:06:56 +01004968// Test that SetAudioPlayout can be used to disable audio playout from the
4969// start, then later enable it. This may be useful, for example, if the caller
4970// needs to play a local ringtone until some event occurs, after which it
4971// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004972TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004973 ASSERT_TRUE(CreatePeerConnectionWrappers());
4974 ConnectFakeSignaling();
4975
4976 // Set up audio-only call where audio playout is disabled on caller's side.
4977 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004978 caller()->AddAudioTrack();
4979 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004980 caller()->CreateAndSetAndSignalOffer();
4981 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4982
4983 // Pump messages for a second.
4984 WAIT(false, 1000);
4985 // Since audio playout is disabled, the caller shouldn't have received
4986 // anything (at the playout level, at least).
4987 EXPECT_EQ(0, caller()->audio_frames_received());
4988 // As a sanity check, make sure the callee (for which playout isn't disabled)
4989 // did still see frames on its audio level.
4990 ASSERT_GT(callee()->audio_frames_received(), 0);
4991
4992 // Enable playout again, and ensure audio starts flowing.
4993 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004994 MediaExpectations media_expectations;
4995 media_expectations.ExpectBidirectionalAudio();
4996 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004997}
4998
4999double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5000 auto report = pc->NewGetStats();
5001 auto track_stats_list =
5002 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5003 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5004 for (const auto* track_stats : track_stats_list) {
5005 if (track_stats->remote_source.is_defined() &&
5006 *track_stats->remote_source) {
5007 remote_track_stats = track_stats;
5008 break;
5009 }
5010 }
5011
5012 if (!remote_track_stats->total_audio_energy.is_defined()) {
5013 return 0.0;
5014 }
5015 return *remote_track_stats->total_audio_energy;
5016}
5017
5018// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5019// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005020TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005021 DisableAudioPlayoutStillGeneratesAudioStats) {
5022 ASSERT_TRUE(CreatePeerConnectionWrappers());
5023 ConnectFakeSignaling();
5024
5025 // Set up audio-only call where playout is disabled but audio-processing is
5026 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005027 caller()->AddAudioTrack();
5028 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005029 caller()->pc()->SetAudioPlayout(false);
5030
5031 caller()->CreateAndSetAndSignalOffer();
5032 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5033
5034 // Wait for the callee to receive audio stats.
5035 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5036}
5037
henrika4f167df2017-11-01 14:45:55 +01005038// Test that SetAudioRecording can be used to disable audio recording from the
5039// start, then later enable it. This may be useful, for example, if the caller
5040// wants to ensure that no audio resources are active before a certain state
5041// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005042TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005043 ASSERT_TRUE(CreatePeerConnectionWrappers());
5044 ConnectFakeSignaling();
5045
5046 // Set up audio-only call where audio recording is disabled on caller's side.
5047 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005048 caller()->AddAudioTrack();
5049 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005050 caller()->CreateAndSetAndSignalOffer();
5051 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5052
5053 // Pump messages for a second.
5054 WAIT(false, 1000);
5055 // Since caller has disabled audio recording, the callee shouldn't have
5056 // received anything.
5057 EXPECT_EQ(0, callee()->audio_frames_received());
5058 // As a sanity check, make sure the caller did still see frames on its
5059 // audio level since audio recording is enabled on the calle side.
5060 ASSERT_GT(caller()->audio_frames_received(), 0);
5061
5062 // Enable audio recording again, and ensure audio starts flowing.
5063 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005064 MediaExpectations media_expectations;
5065 media_expectations.ExpectBidirectionalAudio();
5066 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005067}
5068
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005069// Test that after closing PeerConnections, they stop sending any packets (ICE,
5070// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005071TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005072 // Set up audio/video/data, wait for some frames to be received.
5073 ASSERT_TRUE(CreatePeerConnectionWrappers());
5074 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005075 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005076#ifdef HAVE_SCTP
5077 caller()->CreateDataChannel();
5078#endif
5079 caller()->CreateAndSetAndSignalOffer();
5080 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005081 MediaExpectations media_expectations;
5082 media_expectations.CalleeExpectsSomeAudioAndVideo();
5083 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005084 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005085 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005086 // Pump messages for a second, and ensure no new packets end up sent.
5087 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5088 WAIT(false, 1000);
5089 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5090 EXPECT_EQ(sent_packets_a, sent_packets_b);
5091}
5092
Steve Anton7eca0932018-03-30 15:18:41 -07005093// Test that transport stats are generated by the RTCStatsCollector for a
5094// connection that only involves data channels. This is a regression test for
5095// crbug.com/826972.
5096#ifdef HAVE_SCTP
5097TEST_P(PeerConnectionIntegrationTest,
5098 TransportStatsReportedForDataChannelOnlyConnection) {
5099 ASSERT_TRUE(CreatePeerConnectionWrappers());
5100 ConnectFakeSignaling();
5101 caller()->CreateDataChannel();
5102
5103 caller()->CreateAndSetAndSignalOffer();
5104 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5105 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5106
5107 auto caller_report = caller()->NewGetStats();
5108 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5109 auto callee_report = callee()->NewGetStats();
5110 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5111}
5112#endif // HAVE_SCTP
5113
Qingsi Wang7685e862018-06-11 20:15:46 -07005114TEST_P(PeerConnectionIntegrationTest,
5115 IceEventsGeneratedAndLoggedInRtcEventLog) {
5116 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5117 ConnectFakeSignaling();
5118 PeerConnectionInterface::RTCOfferAnswerOptions options;
5119 options.offer_to_receive_audio = 1;
5120 caller()->SetOfferAnswerOptions(options);
5121 caller()->CreateAndSetAndSignalOffer();
5122 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5123 ASSERT_NE(nullptr, caller()->event_log_factory());
5124 ASSERT_NE(nullptr, callee()->event_log_factory());
5125 webrtc::FakeRtcEventLog* caller_event_log =
5126 static_cast<webrtc::FakeRtcEventLog*>(
5127 caller()->event_log_factory()->last_log_created());
5128 webrtc::FakeRtcEventLog* callee_event_log =
5129 static_cast<webrtc::FakeRtcEventLog*>(
5130 callee()->event_log_factory()->last_log_created());
5131 ASSERT_NE(nullptr, caller_event_log);
5132 ASSERT_NE(nullptr, callee_event_log);
5133 int caller_ice_config_count = caller_event_log->GetEventCount(
5134 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5135 int caller_ice_event_count = caller_event_log->GetEventCount(
5136 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5137 int callee_ice_config_count = callee_event_log->GetEventCount(
5138 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5139 int callee_ice_event_count = callee_event_log->GetEventCount(
5140 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5141 EXPECT_LT(0, caller_ice_config_count);
5142 EXPECT_LT(0, caller_ice_event_count);
5143 EXPECT_LT(0, callee_ice_config_count);
5144 EXPECT_LT(0, callee_ice_event_count);
5145}
5146
Qingsi Wangc129c352019-04-18 10:41:58 -07005147TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005148 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5149 3478};
5150 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5151
5152 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5153
5154 webrtc::PeerConnectionInterface::IceServer ice_server;
5155 ice_server.urls.push_back("turn:88.88.88.0:3478");
5156 ice_server.username = "test";
5157 ice_server.password = "test";
5158
5159 PeerConnectionInterface::RTCConfiguration caller_config;
5160 caller_config.servers.push_back(ice_server);
5161 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5162 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005163 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005164
5165 PeerConnectionInterface::RTCConfiguration callee_config;
5166 callee_config.servers.push_back(ice_server);
5167 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5168 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005169 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005170
5171 ASSERT_TRUE(
5172 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5173
5174 // Do normal offer/answer and wait for ICE to complete.
5175 ConnectFakeSignaling();
5176 caller()->AddAudioVideoTracks();
5177 callee()->AddAudioVideoTracks();
5178 caller()->CreateAndSetAndSignalOffer();
5179 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5180 // Since we are doing continual gathering, the ICE transport does not reach
5181 // kIceGatheringComplete (see
5182 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5183 // kIceConnectionComplete.
5184 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5185 caller()->ice_connection_state(), kDefaultTimeout);
5186 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5187 callee()->ice_connection_state(), kDefaultTimeout);
5188 // Note that we cannot use the metric
5189 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5190 // metric is only populated when we reach kIceConnectionComplete in the
5191 // current implementation.
5192 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5193 caller()->last_candidate_gathered().type());
5194 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5195 callee()->last_candidate_gathered().type());
5196
5197 // Loosen the caller's candidate filter.
5198 caller_config = caller()->pc()->GetConfiguration();
5199 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5200 caller()->pc()->SetConfiguration(caller_config);
5201 // We should have gathered a new host candidate.
5202 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5203 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5204
5205 // Loosen the callee's candidate filter.
5206 callee_config = callee()->pc()->GetConfiguration();
5207 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5208 callee()->pc()->SetConfiguration(callee_config);
5209 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5210 callee()->last_candidate_gathered().type(), kDefaultTimeout);
5211}
5212
Eldar Relloda13ea22019-06-01 12:23:43 +03005213TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03005214 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5215 3478};
5216 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5217
5218 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5219
5220 webrtc::PeerConnectionInterface::IceServer ice_server;
5221 ice_server.urls.push_back("turn:88.88.88.0:3478");
5222 ice_server.username = "test";
5223 ice_server.password = "123";
5224
5225 PeerConnectionInterface::RTCConfiguration caller_config;
5226 caller_config.servers.push_back(ice_server);
5227 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5228 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5229
5230 PeerConnectionInterface::RTCConfiguration callee_config;
5231 callee_config.servers.push_back(ice_server);
5232 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5233 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5234
5235 ASSERT_TRUE(
5236 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5237
5238 // Do normal offer/answer and wait for ICE to complete.
5239 ConnectFakeSignaling();
5240 caller()->AddAudioVideoTracks();
5241 callee()->AddAudioVideoTracks();
5242 caller()->CreateAndSetAndSignalOffer();
5243 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5244 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5245 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5246 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
5247 EXPECT_NE(std::string::npos,
5248 caller()->error_event().host_candidate.find(":"));
5249}
5250
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005251INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5252 PeerConnectionIntegrationTest,
5253 Values(SdpSemantics::kPlanB,
5254 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005255
Steve Anton74255ff2018-01-24 18:32:57 -08005256// Tests that verify interoperability between Plan B and Unified Plan
5257// PeerConnections.
5258class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08005259 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08005260 public ::testing::WithParamInterface<
5261 std::tuple<SdpSemantics, SdpSemantics>> {
5262 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08005263 // Setting the SdpSemantics for the base test to kDefault does not matter
5264 // because we specify not to use the test semantics when creating
5265 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08005266 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07005267 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08005268 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08005269 callee_semantics_(std::get<1>(GetParam())) {}
5270
5271 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07005272 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5273 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08005274 }
5275
5276 const SdpSemantics caller_semantics_;
5277 const SdpSemantics callee_semantics_;
5278};
5279
5280TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5281 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5282 ConnectFakeSignaling();
5283
5284 caller()->CreateAndSetAndSignalOffer();
5285 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5286}
5287
5288TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
5289 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5290 ConnectFakeSignaling();
5291 auto audio_sender = caller()->AddAudioTrack();
5292
5293 caller()->CreateAndSetAndSignalOffer();
5294 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5295
5296 // Verify that one audio receiver has been created on the remote and that it
5297 // has the same track ID as the sending track.
5298 auto receivers = callee()->pc()->GetReceivers();
5299 ASSERT_EQ(1u, receivers.size());
5300 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
5301 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
5302
Seth Hampson2f0d7022018-02-20 11:54:42 -08005303 MediaExpectations media_expectations;
5304 media_expectations.CalleeExpectsSomeAudio();
5305 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005306}
5307
5308TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
5309 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5310 ConnectFakeSignaling();
5311 auto video_sender = caller()->AddVideoTrack();
5312 auto audio_sender = caller()->AddAudioTrack();
5313
5314 caller()->CreateAndSetAndSignalOffer();
5315 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5316
5317 // Verify that one audio and one video receiver have been created on the
5318 // remote and that they have the same track IDs as the sending tracks.
5319 auto audio_receivers =
5320 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5321 ASSERT_EQ(1u, audio_receivers.size());
5322 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5323 auto video_receivers =
5324 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5325 ASSERT_EQ(1u, video_receivers.size());
5326 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5327
Seth Hampson2f0d7022018-02-20 11:54:42 -08005328 MediaExpectations media_expectations;
5329 media_expectations.CalleeExpectsSomeAudioAndVideo();
5330 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005331}
5332
5333TEST_P(PeerConnectionIntegrationInteropTest,
5334 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5335 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5336 ConnectFakeSignaling();
5337 caller()->AddAudioVideoTracks();
5338 callee()->AddAudioVideoTracks();
5339
5340 caller()->CreateAndSetAndSignalOffer();
5341 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5342
Seth Hampson2f0d7022018-02-20 11:54:42 -08005343 MediaExpectations media_expectations;
5344 media_expectations.ExpectBidirectionalAudioAndVideo();
5345 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005346}
5347
5348TEST_P(PeerConnectionIntegrationInteropTest,
5349 ReverseRolesOneAudioLocalToOneVideoRemote) {
5350 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5351 ConnectFakeSignaling();
5352 caller()->AddAudioTrack();
5353 callee()->AddVideoTrack();
5354
5355 caller()->CreateAndSetAndSignalOffer();
5356 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5357
5358 // Verify that only the audio track has been negotiated.
5359 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5360 // Might also check that the callee's NegotiationNeeded flag is set.
5361
5362 // Reverse roles.
5363 callee()->CreateAndSetAndSignalOffer();
5364 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5365
Seth Hampson2f0d7022018-02-20 11:54:42 -08005366 MediaExpectations media_expectations;
5367 media_expectations.CallerExpectsSomeVideo();
5368 media_expectations.CalleeExpectsSomeAudio();
5369 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005370}
5371
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005372INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07005373 PeerConnectionIntegrationTest,
5374 PeerConnectionIntegrationInteropTest,
5375 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5376 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5377
5378// Test that if the Unified Plan side offers two video tracks then the Plan B
5379// side will only see the first one and ignore the second.
5380TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005381 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5382 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005383 ConnectFakeSignaling();
5384 auto first_sender = caller()->AddVideoTrack();
5385 caller()->AddVideoTrack();
5386
5387 caller()->CreateAndSetAndSignalOffer();
5388 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5389
5390 // Verify that there is only one receiver and it corresponds to the first
5391 // added track.
5392 auto receivers = callee()->pc()->GetReceivers();
5393 ASSERT_EQ(1u, receivers.size());
5394 EXPECT_TRUE(receivers[0]->track()->enabled());
5395 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5396
Seth Hampson2f0d7022018-02-20 11:54:42 -08005397 MediaExpectations media_expectations;
5398 media_expectations.CalleeExpectsSomeVideo();
5399 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005400}
5401
Steve Anton2bed3972019-01-04 17:04:30 -08005402// Test that if the initial offer tagged BUNDLE section is rejected due to its
5403// associated RtpTransceiver being stopped and another transceiver is added,
5404// then renegotiation causes the callee to receive the new video track without
5405// error.
5406// This is a regression test for bugs.webrtc.org/9954
5407TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5408 ReOfferWithStoppedBundleTaggedTransceiver) {
5409 RTCConfiguration config;
5410 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5411 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5412 ConnectFakeSignaling();
5413 auto audio_transceiver_or_error =
5414 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5415 ASSERT_TRUE(audio_transceiver_or_error.ok());
5416 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5417
5418 caller()->CreateAndSetAndSignalOffer();
5419 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5420 {
5421 MediaExpectations media_expectations;
5422 media_expectations.CalleeExpectsSomeAudio();
5423 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5424 }
5425
5426 audio_transceiver->Stop();
5427 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5428
5429 caller()->CreateAndSetAndSignalOffer();
5430 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5431 {
5432 MediaExpectations media_expectations;
5433 media_expectations.CalleeExpectsSomeVideo();
5434 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5435 }
5436}
5437
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005438#ifdef HAVE_SCTP
5439
5440TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5441 EndToEndCallWithBundledSctpDataChannel) {
5442 ASSERT_TRUE(CreatePeerConnectionWrappers());
5443 ConnectFakeSignaling();
5444 caller()->CreateDataChannel();
5445 caller()->AddAudioVideoTracks();
5446 callee()->AddAudioVideoTracks();
5447 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
5448 caller()->CreateAndSetAndSignalOffer();
5449 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5450 // Ensure that media and data are multiplexed on the same DTLS transport.
5451 // This only works on Unified Plan, because transports are not exposed in plan
5452 // B.
5453 auto sctp_info = caller()->pc()->GetSctpTransport()->Information();
5454 EXPECT_EQ(sctp_info.dtls_transport(),
5455 caller()->pc()->GetSenders()[0]->dtls_transport());
5456}
5457
5458#endif // HAVE_SCTP
5459
deadbeef1dcb1642017-03-29 21:08:16 -07005460} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01005461} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07005462
5463#endif // if !defined(THREAD_SANITIZER)