blob: 59bfb0483a72aaf625e1e0ba7e2bffbf11b610d0 [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 }
Alex Drake43faee02019-08-12 16:27:34 -0700943
deadbeef1dcb1642017-03-29 21:08:16 -0700944 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100945 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700946
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800947 if (remote_async_resolver_) {
948 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800949 if (local_candidate.address().IsUnresolvedIP()) {
950 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
951 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700952 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800953 local_candidate.address().hostname());
954 RTC_DCHECK(!resolved_ip.IsNil());
955 resolved_addr.SetResolvedIP(resolved_ip);
956 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
957 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
958 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700959 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700960 }
961
deadbeef1dcb1642017-03-29 21:08:16 -0700962 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800963 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700964 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700965 // Remote party may be deleted.
966 return;
967 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800968 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700969 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700970 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300971 void OnIceCandidateError(const std::string& host_candidate,
972 const std::string& url,
973 int error_code,
974 const std::string& error_text) override {
975 error_event_ = cricket::IceCandidateErrorEvent(host_candidate, url,
976 error_code, error_text);
977 }
deadbeef1dcb1642017-03-29 21:08:16 -0700978 void OnDataChannel(
979 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100980 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700981 data_channel_ = data_channel;
982 data_observer_.reset(new MockDataChannelObserver(data_channel));
983 }
984
deadbeef1dcb1642017-03-29 21:08:16 -0700985 std::string debug_name_;
986
987 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -0700988 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
989 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -0700990
991 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
992 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
993 peer_connection_factory_;
994
Steve Antonede9ca52017-10-16 13:04:27 -0700995 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700996 // Needed to keep track of number of frames sent.
997 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
998 // Needed to keep track of number of frames received.
999 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1000 fake_video_renderers_;
1001 // Needed to ensure frames aren't received for removed tracks.
1002 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
1003 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -07001004
1005 // For remote peer communication.
1006 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1007 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001008 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001009 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001010 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001011
Niels Möller5c7efe72018-05-11 10:34:46 +02001012 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001013 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001014 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1015 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001016 // |local_video_renderer_| attached to the first created local video track.
1017 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1018
Seth Hampson2f0d7022018-02-20 11:54:42 -08001019 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001020 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1021 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1022 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001023 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001024 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001025 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1026 std::unique_ptr<MockDataChannelObserver> data_observer_;
1027
1028 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1029
Steve Antonede9ca52017-10-16 13:04:27 -07001030 std::vector<PeerConnectionInterface::IceConnectionState>
1031 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001032 std::vector<PeerConnectionInterface::IceConnectionState>
1033 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001034 std::vector<PeerConnectionInterface::PeerConnectionState>
1035 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001036 std::vector<PeerConnectionInterface::IceGatheringState>
1037 ice_gathering_state_history_;
Alex Drake00c7ecf2019-08-06 10:54:47 -07001038 std::vector<cricket::CandidatePairChangeEvent>
1039 ice_candidate_pair_change_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001040
Qingsi Wang7685e862018-06-11 20:15:46 -07001041 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1042
deadbeef1dcb1642017-03-29 21:08:16 -07001043 rtc::AsyncInvoker invoker_;
1044
Seth Hampson2f0d7022018-02-20 11:54:42 -08001045 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001046};
1047
Elad Alon99c3fe52017-10-13 16:29:40 +02001048class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1049 public:
1050 virtual ~MockRtcEventLogOutput() = default;
1051 MOCK_CONST_METHOD0(IsActive, bool());
1052 MOCK_METHOD1(Write, bool(const std::string&));
1053};
1054
Seth Hampson2f0d7022018-02-20 11:54:42 -08001055// This helper object is used for both specifying how many audio/video frames
1056// are expected to be received for a caller/callee. It provides helper functions
1057// to specify these expectations. The object initially starts in a state of no
1058// expectations.
1059class MediaExpectations {
1060 public:
1061 enum ExpectFrames {
1062 kExpectSomeFrames,
1063 kExpectNoFrames,
1064 kNoExpectation,
1065 };
1066
1067 void ExpectBidirectionalAudioAndVideo() {
1068 ExpectBidirectionalAudio();
1069 ExpectBidirectionalVideo();
1070 }
1071
1072 void ExpectBidirectionalAudio() {
1073 CallerExpectsSomeAudio();
1074 CalleeExpectsSomeAudio();
1075 }
1076
1077 void ExpectNoAudio() {
1078 CallerExpectsNoAudio();
1079 CalleeExpectsNoAudio();
1080 }
1081
1082 void ExpectBidirectionalVideo() {
1083 CallerExpectsSomeVideo();
1084 CalleeExpectsSomeVideo();
1085 }
1086
1087 void ExpectNoVideo() {
1088 CallerExpectsNoVideo();
1089 CalleeExpectsNoVideo();
1090 }
1091
1092 void CallerExpectsSomeAudioAndVideo() {
1093 CallerExpectsSomeAudio();
1094 CallerExpectsSomeVideo();
1095 }
1096
1097 void CalleeExpectsSomeAudioAndVideo() {
1098 CalleeExpectsSomeAudio();
1099 CalleeExpectsSomeVideo();
1100 }
1101
1102 // Caller's audio functions.
1103 void CallerExpectsSomeAudio(
1104 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1105 caller_audio_expectation_ = kExpectSomeFrames;
1106 caller_audio_frames_expected_ = expected_audio_frames;
1107 }
1108
1109 void CallerExpectsNoAudio() {
1110 caller_audio_expectation_ = kExpectNoFrames;
1111 caller_audio_frames_expected_ = 0;
1112 }
1113
1114 // Caller's video functions.
1115 void CallerExpectsSomeVideo(
1116 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1117 caller_video_expectation_ = kExpectSomeFrames;
1118 caller_video_frames_expected_ = expected_video_frames;
1119 }
1120
1121 void CallerExpectsNoVideo() {
1122 caller_video_expectation_ = kExpectNoFrames;
1123 caller_video_frames_expected_ = 0;
1124 }
1125
1126 // Callee's audio functions.
1127 void CalleeExpectsSomeAudio(
1128 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1129 callee_audio_expectation_ = kExpectSomeFrames;
1130 callee_audio_frames_expected_ = expected_audio_frames;
1131 }
1132
1133 void CalleeExpectsNoAudio() {
1134 callee_audio_expectation_ = kExpectNoFrames;
1135 callee_audio_frames_expected_ = 0;
1136 }
1137
1138 // Callee's video functions.
1139 void CalleeExpectsSomeVideo(
1140 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1141 callee_video_expectation_ = kExpectSomeFrames;
1142 callee_video_frames_expected_ = expected_video_frames;
1143 }
1144
1145 void CalleeExpectsNoVideo() {
1146 callee_video_expectation_ = kExpectNoFrames;
1147 callee_video_frames_expected_ = 0;
1148 }
1149
1150 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1151 ExpectFrames caller_video_expectation_ = kNoExpectation;
1152 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1153 ExpectFrames callee_video_expectation_ = kNoExpectation;
1154 int caller_audio_frames_expected_ = 0;
1155 int caller_video_frames_expected_ = 0;
1156 int callee_audio_frames_expected_ = 0;
1157 int callee_video_frames_expected_ = 0;
1158};
1159
deadbeef1dcb1642017-03-29 21:08:16 -07001160// Tests two PeerConnections connecting to each other end-to-end, using a
1161// virtual network, fake A/V capture and fake encoder/decoders. The
1162// PeerConnections share the threads/socket servers, but use separate versions
1163// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001164class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001165 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001166 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1167 : sdp_semantics_(sdp_semantics),
1168 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001169 fss_(new rtc::FirewallSocketServer(ss_.get())),
1170 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001171 worker_thread_(rtc::Thread::Create()),
1172 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001173 network_thread_->SetName("PCNetworkThread", this);
1174 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001175 RTC_CHECK(network_thread_->Start());
1176 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001177 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001178 }
1179
Seth Hampson2f0d7022018-02-20 11:54:42 -08001180 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001181 // The PeerConnections should deleted before the TurnCustomizers.
1182 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1183 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1184 // that the TurnCustomizer outlives the life of the PeerConnection or else
1185 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001186 if (caller_) {
1187 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001188 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001189 }
1190 if (callee_) {
1191 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001192 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001193 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001194
1195 // If turn servers were created for the test they need to be destroyed on
1196 // the network thread.
1197 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1198 turn_servers_.clear();
1199 turn_customizers_.clear();
1200 });
deadbeef1dcb1642017-03-29 21:08:16 -07001201 }
1202
1203 bool SignalingStateStable() {
1204 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1205 }
1206
deadbeef71452802017-05-07 17:21:01 -07001207 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001208 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1209 // are connected. This is an important distinction. Once we have separate
1210 // ICE and DTLS state, this check needs to use the DTLS state.
1211 return (callee()->ice_connection_state() ==
1212 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1213 callee()->ice_connection_state() ==
1214 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1215 (caller()->ice_connection_state() ==
1216 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1217 caller()->ice_connection_state() ==
1218 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001219 }
1220
Qingsi Wang7685e862018-06-11 20:15:46 -07001221 // When |event_log_factory| is null, the default implementation of the event
1222 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001223 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1224 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001225 const PeerConnectionFactory::Options* options,
1226 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001227 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001228 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1229 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001230 RTCConfiguration modified_config;
1231 if (config) {
1232 modified_config = *config;
1233 }
Steve Anton3acffc32018-04-12 17:21:03 -07001234 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001235 if (!dependencies.cert_generator) {
1236 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001237 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001238 }
1239 std::unique_ptr<PeerConnectionWrapper> client(
1240 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001241
Niels Möllerf06f9232018-08-07 12:32:18 +02001242 if (!client->Init(options, &modified_config, std::move(dependencies),
1243 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001244 std::move(event_log_factory),
1245 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001246 return nullptr;
1247 }
1248 return client;
1249 }
1250
Qingsi Wang7685e862018-06-11 20:15:46 -07001251 std::unique_ptr<PeerConnectionWrapper>
1252 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1253 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001254 const PeerConnectionFactory::Options* options,
1255 const RTCConfiguration* config,
1256 webrtc::PeerConnectionDependencies dependencies) {
1257 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1258 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001259 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001260 std::move(dependencies),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001261 std::move(event_log_factory),
1262 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001263 }
1264
deadbeef1dcb1642017-03-29 21:08:16 -07001265 bool CreatePeerConnectionWrappers() {
1266 return CreatePeerConnectionWrappersWithConfig(
1267 PeerConnectionInterface::RTCConfiguration(),
1268 PeerConnectionInterface::RTCConfiguration());
1269 }
1270
Steve Anton3acffc32018-04-12 17:21:03 -07001271 bool CreatePeerConnectionWrappersWithSdpSemantics(
1272 SdpSemantics caller_semantics,
1273 SdpSemantics callee_semantics) {
1274 // Can't specify the sdp_semantics in the passed-in configuration since it
1275 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1276 // stored in sdp_semantics_. So get around this by modifying the instance
1277 // variable before calling CreatePeerConnectionWrapper for the caller and
1278 // callee PeerConnections.
1279 SdpSemantics original_semantics = sdp_semantics_;
1280 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001281 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001282 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001283 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001284 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001285 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001286 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001287 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001288 sdp_semantics_ = original_semantics;
1289 return caller_ && callee_;
1290 }
1291
deadbeef1dcb1642017-03-29 21:08:16 -07001292 bool CreatePeerConnectionWrappersWithConfig(
1293 const PeerConnectionInterface::RTCConfiguration& caller_config,
1294 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001295 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001296 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001297 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1298 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001299 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001300 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001301 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1302 /*media_transport_factory=*/nullptr);
1303 return caller_ && callee_;
1304 }
1305
1306 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1307 const PeerConnectionInterface::RTCConfiguration& caller_config,
1308 const PeerConnectionInterface::RTCConfiguration& callee_config,
1309 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1310 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
1311 caller_ =
1312 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1313 webrtc::PeerConnectionDependencies(nullptr),
1314 nullptr, std::move(caller_factory));
1315 callee_ =
1316 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1317 webrtc::PeerConnectionDependencies(nullptr),
1318 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001319 return caller_ && callee_;
1320 }
1321
1322 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1323 const PeerConnectionInterface::RTCConfiguration& caller_config,
1324 webrtc::PeerConnectionDependencies caller_dependencies,
1325 const PeerConnectionInterface::RTCConfiguration& callee_config,
1326 webrtc::PeerConnectionDependencies callee_dependencies) {
1327 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001328 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001329 std::move(caller_dependencies), nullptr,
1330 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001331 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001332 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001333 std::move(callee_dependencies), nullptr,
1334 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001335 return caller_ && callee_;
1336 }
1337
1338 bool CreatePeerConnectionWrappersWithOptions(
1339 const PeerConnectionFactory::Options& caller_options,
1340 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001341 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001342 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001343 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1344 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001345 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001346 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001347 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1348 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001349 return caller_ && callee_;
1350 }
1351
1352 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1353 PeerConnectionInterface::RTCConfiguration default_config;
1354 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001355 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001356 webrtc::PeerConnectionDependencies(nullptr));
1357 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001358 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001359 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001360 return caller_ && callee_;
1361 }
1362
Seth Hampson2f0d7022018-02-20 11:54:42 -08001363 std::unique_ptr<PeerConnectionWrapper>
1364 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001365 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1366 new FakeRTCCertificateGenerator());
1367 cert_generator->use_alternate_key();
1368
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001369 webrtc::PeerConnectionDependencies dependencies(nullptr);
1370 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001371 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001372 std::move(dependencies), nullptr,
1373 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001374 }
1375
Seth Hampsonaed71642018-06-11 07:41:32 -07001376 cricket::TestTurnServer* CreateTurnServer(
1377 rtc::SocketAddress internal_address,
1378 rtc::SocketAddress external_address,
1379 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1380 const std::string& common_name = "test turn server") {
1381 rtc::Thread* thread = network_thread();
1382 std::unique_ptr<cricket::TestTurnServer> turn_server =
1383 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1384 RTC_FROM_HERE,
1385 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001386 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001387 thread, internal_address, external_address, type,
1388 /*ignore_bad_certs=*/true, common_name);
1389 });
1390 turn_servers_.push_back(std::move(turn_server));
1391 // Interactions with the turn server should be done on the network thread.
1392 return turn_servers_.back().get();
1393 }
1394
1395 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1396 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1397 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1398 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001399 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001400 turn_customizers_.push_back(std::move(turn_customizer));
1401 // Interactions with the turn customizer should be done on the network
1402 // thread.
1403 return turn_customizers_.back().get();
1404 }
1405
1406 // Checks that the function counters for a TestTurnCustomizer are greater than
1407 // 0.
1408 void ExpectTurnCustomizerCountersIncremented(
1409 cricket::TestTurnCustomizer* turn_customizer) {
1410 unsigned int allow_channel_data_counter =
1411 network_thread()->Invoke<unsigned int>(
1412 RTC_FROM_HERE, [turn_customizer] {
1413 return turn_customizer->allow_channel_data_cnt_;
1414 });
1415 EXPECT_GT(allow_channel_data_counter, 0u);
1416 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1417 RTC_FROM_HERE,
1418 [turn_customizer] { return turn_customizer->modify_cnt_; });
1419 EXPECT_GT(modify_counter, 0u);
1420 }
1421
deadbeef1dcb1642017-03-29 21:08:16 -07001422 // Once called, SDP blobs and ICE candidates will be automatically signaled
1423 // between PeerConnections.
1424 void ConnectFakeSignaling() {
1425 caller_->set_signaling_message_receiver(callee_.get());
1426 callee_->set_signaling_message_receiver(caller_.get());
1427 }
1428
Steve Antonede9ca52017-10-16 13:04:27 -07001429 // Once called, SDP blobs will be automatically signaled between
1430 // PeerConnections. Note that ICE candidates will not be signaled unless they
1431 // are in the exchanged SDP blobs.
1432 void ConnectFakeSignalingForSdpOnly() {
1433 ConnectFakeSignaling();
1434 SetSignalIceCandidates(false);
1435 }
1436
deadbeef1dcb1642017-03-29 21:08:16 -07001437 void SetSignalingDelayMs(int delay_ms) {
1438 caller_->set_signaling_delay_ms(delay_ms);
1439 callee_->set_signaling_delay_ms(delay_ms);
1440 }
1441
Steve Antonede9ca52017-10-16 13:04:27 -07001442 void SetSignalIceCandidates(bool signal) {
1443 caller_->set_signal_ice_candidates(signal);
1444 callee_->set_signal_ice_candidates(signal);
1445 }
1446
deadbeef1dcb1642017-03-29 21:08:16 -07001447 // Messages may get lost on the unreliable DataChannel, so we send multiple
1448 // times to avoid test flakiness.
1449 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1450 const std::string& data,
1451 int retries) {
1452 for (int i = 0; i < retries; ++i) {
1453 dc->Send(DataBuffer(data));
1454 }
1455 }
1456
1457 rtc::Thread* network_thread() { return network_thread_.get(); }
1458
1459 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1460
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001461 webrtc::MediaTransportPair* loopback_media_transports() {
1462 return &loopback_media_transports_;
1463 }
1464
deadbeef1dcb1642017-03-29 21:08:16 -07001465 PeerConnectionWrapper* caller() { return caller_.get(); }
1466
1467 // Set the |caller_| to the |wrapper| passed in and return the
1468 // original |caller_|.
1469 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1470 PeerConnectionWrapper* wrapper) {
1471 PeerConnectionWrapper* old = caller_.release();
1472 caller_.reset(wrapper);
1473 return old;
1474 }
1475
1476 PeerConnectionWrapper* callee() { return callee_.get(); }
1477
1478 // Set the |callee_| to the |wrapper| passed in and return the
1479 // original |callee_|.
1480 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1481 PeerConnectionWrapper* wrapper) {
1482 PeerConnectionWrapper* old = callee_.release();
1483 callee_.reset(wrapper);
1484 return old;
1485 }
1486
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001487 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1488 network_thread()->Invoke<void>(
1489 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1490 caller()->port_allocator(), caller_flags));
1491 network_thread()->Invoke<void>(
1492 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1493 callee()->port_allocator(), callee_flags));
1494 }
1495
Steve Antonede9ca52017-10-16 13:04:27 -07001496 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1497
Seth Hampson2f0d7022018-02-20 11:54:42 -08001498 // Expects the provided number of new frames to be received within
1499 // kMaxWaitForFramesMs. The new expected frames are specified in
1500 // |media_expectations|. Returns false if any of the expectations were
1501 // not met.
1502 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1503 // First initialize the expected frame counts based upon the current
1504 // frame count.
1505 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1506 if (media_expectations.caller_audio_expectation_ ==
1507 MediaExpectations::kExpectSomeFrames) {
1508 total_caller_audio_frames_expected +=
1509 media_expectations.caller_audio_frames_expected_;
1510 }
1511 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001512 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001513 if (media_expectations.caller_video_expectation_ ==
1514 MediaExpectations::kExpectSomeFrames) {
1515 total_caller_video_frames_expected +=
1516 media_expectations.caller_video_frames_expected_;
1517 }
1518 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1519 if (media_expectations.callee_audio_expectation_ ==
1520 MediaExpectations::kExpectSomeFrames) {
1521 total_callee_audio_frames_expected +=
1522 media_expectations.callee_audio_frames_expected_;
1523 }
1524 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001525 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001526 if (media_expectations.callee_video_expectation_ ==
1527 MediaExpectations::kExpectSomeFrames) {
1528 total_callee_video_frames_expected +=
1529 media_expectations.callee_video_frames_expected_;
1530 }
deadbeef1dcb1642017-03-29 21:08:16 -07001531
Seth Hampson2f0d7022018-02-20 11:54:42 -08001532 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001533 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001534 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001535 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001536 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001537 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001538 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001539 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001540 total_callee_video_frames_expected,
1541 kMaxWaitForFramesMs);
1542 bool expectations_correct =
1543 caller()->audio_frames_received() >=
1544 total_caller_audio_frames_expected &&
1545 caller()->min_video_frames_received_per_track() >=
1546 total_caller_video_frames_expected &&
1547 callee()->audio_frames_received() >=
1548 total_callee_audio_frames_expected &&
1549 callee()->min_video_frames_received_per_track() >=
1550 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001551
Seth Hampson2f0d7022018-02-20 11:54:42 -08001552 // After the combined wait, print out a more detailed message upon
1553 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001554 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001555 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001556 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001557 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001558 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001559 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001560 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001561 total_callee_video_frames_expected);
1562
1563 // We want to make sure nothing unexpected was received.
1564 if (media_expectations.caller_audio_expectation_ ==
1565 MediaExpectations::kExpectNoFrames) {
1566 EXPECT_EQ(caller()->audio_frames_received(),
1567 total_caller_audio_frames_expected);
1568 if (caller()->audio_frames_received() !=
1569 total_caller_audio_frames_expected) {
1570 expectations_correct = false;
1571 }
1572 }
1573 if (media_expectations.caller_video_expectation_ ==
1574 MediaExpectations::kExpectNoFrames) {
1575 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1576 total_caller_video_frames_expected);
1577 if (caller()->min_video_frames_received_per_track() !=
1578 total_caller_video_frames_expected) {
1579 expectations_correct = false;
1580 }
1581 }
1582 if (media_expectations.callee_audio_expectation_ ==
1583 MediaExpectations::kExpectNoFrames) {
1584 EXPECT_EQ(callee()->audio_frames_received(),
1585 total_callee_audio_frames_expected);
1586 if (callee()->audio_frames_received() !=
1587 total_callee_audio_frames_expected) {
1588 expectations_correct = false;
1589 }
1590 }
1591 if (media_expectations.callee_video_expectation_ ==
1592 MediaExpectations::kExpectNoFrames) {
1593 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1594 total_callee_video_frames_expected);
1595 if (callee()->min_video_frames_received_per_track() !=
1596 total_callee_video_frames_expected) {
1597 expectations_correct = false;
1598 }
1599 }
1600 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001601 }
1602
Steve Antond91969e2019-05-30 12:27:03 -07001603 void ClosePeerConnections() {
1604 caller()->pc()->Close();
1605 callee()->pc()->Close();
1606 }
1607
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001608 void TestNegotiatedCipherSuite(
1609 const PeerConnectionFactory::Options& caller_options,
1610 const PeerConnectionFactory::Options& callee_options,
1611 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001612 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1613 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001614 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001615 caller()->AddAudioVideoTracks();
1616 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001617 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001618 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001619 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001620 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001621 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00001622 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001623 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1624 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001625 }
1626
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001627 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1628 bool remote_gcm_enabled,
1629 int expected_cipher_suite) {
1630 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001631 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1632 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001633 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001634 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1635 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001636 TestNegotiatedCipherSuite(caller_options, callee_options,
1637 expected_cipher_suite);
1638 }
1639
Seth Hampson2f0d7022018-02-20 11:54:42 -08001640 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001641 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001642
deadbeef1dcb1642017-03-29 21:08:16 -07001643 private:
1644 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001645 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001646 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001647 // |network_thread_| and |worker_thread_| are used by both
1648 // |caller_| and |callee_| so they must be destroyed
1649 // later.
1650 std::unique_ptr<rtc::Thread> network_thread_;
1651 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001652 // The turn servers and turn customizers should be accessed & deleted on the
1653 // network thread to avoid a race with the socket read/write that occurs
1654 // on the network thread.
1655 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1656 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001657 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001658 std::unique_ptr<PeerConnectionWrapper> caller_;
1659 std::unique_ptr<PeerConnectionWrapper> callee_;
1660};
1661
Seth Hampson2f0d7022018-02-20 11:54:42 -08001662class PeerConnectionIntegrationTest
1663 : public PeerConnectionIntegrationBaseTest,
1664 public ::testing::WithParamInterface<SdpSemantics> {
1665 protected:
1666 PeerConnectionIntegrationTest()
1667 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1668};
1669
1670class PeerConnectionIntegrationTestPlanB
1671 : public PeerConnectionIntegrationBaseTest {
1672 protected:
1673 PeerConnectionIntegrationTestPlanB()
1674 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1675};
1676
1677class PeerConnectionIntegrationTestUnifiedPlan
1678 : public PeerConnectionIntegrationBaseTest {
1679 protected:
1680 PeerConnectionIntegrationTestUnifiedPlan()
1681 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1682};
1683
deadbeef1dcb1642017-03-29 21:08:16 -07001684// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1685// includes testing that the callback is invoked if an observer is connected
1686// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001687TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001688 RtpReceiverObserverOnFirstPacketReceived) {
1689 ASSERT_TRUE(CreatePeerConnectionWrappers());
1690 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001691 caller()->AddAudioVideoTracks();
1692 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001693 // Start offer/answer exchange and wait for it to complete.
1694 caller()->CreateAndSetAndSignalOffer();
1695 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1696 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001697 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1698 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001699 // Wait for all "first packet received" callbacks to be fired.
1700 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001701 absl::c_all_of(caller()->rtp_receiver_observers(),
1702 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1703 return o->first_packet_received();
1704 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001705 kMaxWaitForFramesMs);
1706 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001707 absl::c_all_of(callee()->rtp_receiver_observers(),
1708 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1709 return o->first_packet_received();
1710 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001711 kMaxWaitForFramesMs);
1712 // If new observers are set after the first packet was already received, the
1713 // callback should still be invoked.
1714 caller()->ResetRtpReceiverObservers();
1715 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001716 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1717 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001718 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001719 absl::c_all_of(caller()->rtp_receiver_observers(),
1720 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1721 return o->first_packet_received();
1722 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001723 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001724 absl::c_all_of(callee()->rtp_receiver_observers(),
1725 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1726 return o->first_packet_received();
1727 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001728}
1729
1730class DummyDtmfObserver : public DtmfSenderObserverInterface {
1731 public:
1732 DummyDtmfObserver() : completed_(false) {}
1733
1734 // Implements DtmfSenderObserverInterface.
1735 void OnToneChange(const std::string& tone) override {
1736 tones_.push_back(tone);
1737 if (tone.empty()) {
1738 completed_ = true;
1739 }
1740 }
1741
1742 const std::vector<std::string>& tones() const { return tones_; }
1743 bool completed() const { return completed_; }
1744
1745 private:
1746 bool completed_;
1747 std::vector<std::string> tones_;
1748};
1749
1750// Assumes |sender| already has an audio track added and the offer/answer
1751// exchange is done.
1752void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1753 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001754 // We should be able to get a DTMF sender from the local sender.
1755 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1756 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1757 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001758 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001759 dtmf_sender->RegisterObserver(&observer);
1760
1761 // Test the DtmfSender object just created.
1762 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1763 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1764
1765 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1766 std::vector<std::string> tones = {"1", "a", ""};
1767 EXPECT_EQ(tones, observer.tones());
1768 dtmf_sender->UnregisterObserver();
1769 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1770}
1771
1772// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1773// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001774TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001775 ASSERT_TRUE(CreatePeerConnectionWrappers());
1776 ConnectFakeSignaling();
1777 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001778 caller()->AddAudioTrack();
1779 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001780 caller()->CreateAndSetAndSignalOffer();
1781 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001782 // DTLS must finish before the DTMF sender can be used reliably.
1783 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001784 TestDtmfFromSenderToReceiver(caller(), callee());
1785 TestDtmfFromSenderToReceiver(callee(), caller());
1786}
1787
1788// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1789// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001790TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001791 ASSERT_TRUE(CreatePeerConnectionWrappers());
1792 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001793
deadbeef1dcb1642017-03-29 21:08:16 -07001794 // Do normal offer/answer and wait for some frames to be received in each
1795 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001796 caller()->AddAudioVideoTracks();
1797 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001798 caller()->CreateAndSetAndSignalOffer();
1799 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001800 MediaExpectations media_expectations;
1801 media_expectations.ExpectBidirectionalAudioAndVideo();
1802 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001803 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1804 webrtc::kEnumCounterKeyProtocolDtls));
1805 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1806 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001807}
1808
1809// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001810TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001811 PeerConnectionInterface::RTCConfiguration sdes_config;
1812 sdes_config.enable_dtls_srtp.emplace(false);
1813 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1814 ConnectFakeSignaling();
1815
1816 // Do normal offer/answer and wait for some frames to be received in each
1817 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001818 caller()->AddAudioVideoTracks();
1819 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001820 caller()->CreateAndSetAndSignalOffer();
1821 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001822 MediaExpectations media_expectations;
1823 media_expectations.ExpectBidirectionalAudioAndVideo();
1824 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001825 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1826 webrtc::kEnumCounterKeyProtocolSdes));
1827 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1828 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001829}
1830
Steve Anton9a44b2d2019-07-12 12:58:30 -07001831// Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
1832// option to offer encrypted versions of all header extensions alongside the
1833// unencrypted versions.
1834TEST_P(PeerConnectionIntegrationTest,
1835 EndToEndCallWithEncryptedRtpHeaderExtensions) {
1836 CryptoOptions crypto_options;
1837 crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
1838 PeerConnectionInterface::RTCConfiguration config;
1839 config.crypto_options = crypto_options;
1840 // Note: This allows offering >14 RTP header extensions.
1841 config.offer_extmap_allow_mixed = true;
1842 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
1843 ConnectFakeSignaling();
1844
1845 // Do normal offer/answer and wait for some frames to be received in each
1846 // direction.
1847 caller()->AddAudioVideoTracks();
1848 callee()->AddAudioVideoTracks();
1849 caller()->CreateAndSetAndSignalOffer();
1850 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1851 MediaExpectations media_expectations;
1852 media_expectations.ExpectBidirectionalAudioAndVideo();
1853 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1854}
1855
Steve Anton8c0f7a72017-10-03 10:03:10 -07001856// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1857// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001858TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001859 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1860 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1861 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1862 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1863 return pc->GetRemoteAudioSSLCertificate();
1864 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001865 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1866 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1867 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1868 return pc->GetRemoteAudioSSLCertChain();
1869 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001870
1871 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1872 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1873
1874 // Configure each side with a known certificate so they can be compared later.
1875 PeerConnectionInterface::RTCConfiguration caller_config;
1876 caller_config.enable_dtls_srtp.emplace(true);
1877 caller_config.certificates.push_back(caller_cert);
1878 PeerConnectionInterface::RTCConfiguration callee_config;
1879 callee_config.enable_dtls_srtp.emplace(true);
1880 callee_config.certificates.push_back(callee_cert);
1881 ASSERT_TRUE(
1882 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1883 ConnectFakeSignaling();
1884
1885 // When first initialized, there should not be a remote SSL certificate (and
1886 // calling this method should not crash).
1887 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1888 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001889 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1890 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001891
Steve Anton15324772018-01-16 10:26:49 -08001892 caller()->AddAudioTrack();
1893 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001894 caller()->CreateAndSetAndSignalOffer();
1895 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1896 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1897
1898 // Once DTLS has been connected, each side should return the other's SSL
1899 // certificate when calling GetRemoteAudioSSLCertificate.
1900
1901 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1902 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001903 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001904 caller_remote_cert->ToPEMString());
1905
1906 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1907 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001908 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001909 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001910
1911 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1912 ASSERT_TRUE(caller_remote_cert_chain);
1913 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1914 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001915 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001916 remote_cert->ToPEMString());
1917
1918 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1919 ASSERT_TRUE(callee_remote_cert_chain);
1920 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1921 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001922 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001923 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001924}
1925
deadbeef1dcb1642017-03-29 21:08:16 -07001926// This test sets up a call between two parties with a source resolution of
1927// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001928TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001929 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1930 ASSERT_TRUE(CreatePeerConnectionWrappers());
1931 ConnectFakeSignaling();
1932
Niels Möller5c7efe72018-05-11 10:34:46 +02001933 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1934 webrtc::FakePeriodicVideoSource::Config config;
1935 config.width = 1280;
1936 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001937 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001938 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1939 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001940
1941 // Do normal offer/answer and wait for at least one frame to be received in
1942 // each direction.
1943 caller()->CreateAndSetAndSignalOffer();
1944 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1945 callee()->min_video_frames_received_per_track() > 0,
1946 kMaxWaitForFramesMs);
1947
1948 // Check rendered aspect ratio.
1949 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1950 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1951 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1952 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1953}
1954
1955// This test sets up an one-way call, with media only from caller to
1956// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001957TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001958 ASSERT_TRUE(CreatePeerConnectionWrappers());
1959 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001960 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001961 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001962 MediaExpectations media_expectations;
1963 media_expectations.CalleeExpectsSomeAudioAndVideo();
1964 media_expectations.CallerExpectsNoAudio();
1965 media_expectations.CallerExpectsNoVideo();
1966 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001967}
1968
1969// This test sets up a audio call initially, with the callee rejecting video
1970// initially. Then later the callee decides to upgrade to audio/video, and
1971// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001972TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001973 ASSERT_TRUE(CreatePeerConnectionWrappers());
1974 ConnectFakeSignaling();
1975 // Initially, offer an audio/video stream from the caller, but refuse to
1976 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001977 caller()->AddAudioVideoTracks();
1978 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001979 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1980 PeerConnectionInterface::RTCOfferAnswerOptions options;
1981 options.offer_to_receive_video = 0;
1982 callee()->SetOfferAnswerOptions(options);
1983 } else {
1984 callee()->SetRemoteOfferHandler([this] {
1985 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1986 });
1987 }
deadbeef1dcb1642017-03-29 21:08:16 -07001988 // Do offer/answer and make sure audio is still received end-to-end.
1989 caller()->CreateAndSetAndSignalOffer();
1990 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001991 {
1992 MediaExpectations media_expectations;
1993 media_expectations.ExpectBidirectionalAudio();
1994 media_expectations.ExpectNoVideo();
1995 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1996 }
deadbeef1dcb1642017-03-29 21:08:16 -07001997 // Sanity check that the callee's description has a rejected video section.
1998 ASSERT_NE(nullptr, callee()->pc()->local_description());
1999 const ContentInfo* callee_video_content =
2000 GetFirstVideoContent(callee()->pc()->local_description()->description());
2001 ASSERT_NE(nullptr, callee_video_content);
2002 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002003
deadbeef1dcb1642017-03-29 21:08:16 -07002004 // Now negotiate with video and ensure negotiation succeeds, with video
2005 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08002006 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002007 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2008 PeerConnectionInterface::RTCOfferAnswerOptions options;
2009 options.offer_to_receive_video = 1;
2010 callee()->SetOfferAnswerOptions(options);
2011 } else {
2012 callee()->SetRemoteOfferHandler(nullptr);
2013 caller()->SetRemoteOfferHandler([this] {
2014 // The caller creates a new transceiver to receive video on when receiving
2015 // the offer, but by default it is send only.
2016 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002017 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002018 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
2019 transceivers[2]->receiver()->media_type());
2020 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
2021 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
2022 });
2023 }
deadbeef1dcb1642017-03-29 21:08:16 -07002024 callee()->CreateAndSetAndSignalOffer();
2025 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002026 {
2027 // Expect additional audio frames to be received after the upgrade.
2028 MediaExpectations media_expectations;
2029 media_expectations.ExpectBidirectionalAudioAndVideo();
2030 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2031 }
deadbeef1dcb1642017-03-29 21:08:16 -07002032}
2033
deadbeef4389b4d2017-09-07 09:07:36 -07002034// Simpler than the above test; just add an audio track to an established
2035// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002036TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002037 ASSERT_TRUE(CreatePeerConnectionWrappers());
2038 ConnectFakeSignaling();
2039 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002040 caller()->AddVideoTrack();
2041 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002042 caller()->CreateAndSetAndSignalOffer();
2043 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2044 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002045 caller()->AddAudioTrack();
2046 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002047 caller()->CreateAndSetAndSignalOffer();
2048 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2049 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002050 MediaExpectations media_expectations;
2051 media_expectations.ExpectBidirectionalAudioAndVideo();
2052 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002053}
2054
deadbeef1dcb1642017-03-29 21:08:16 -07002055// This test sets up a call that's transferred to a new caller with a different
2056// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002057TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002058 ASSERT_TRUE(CreatePeerConnectionWrappers());
2059 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002060 caller()->AddAudioVideoTracks();
2061 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002062 caller()->CreateAndSetAndSignalOffer();
2063 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2064
2065 // Keep the original peer around which will still send packets to the
2066 // receiving client. These SRTP packets will be dropped.
2067 std::unique_ptr<PeerConnectionWrapper> original_peer(
2068 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002069 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002070 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2071 // directly above.
2072 original_peer->pc()->Close();
2073
2074 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002075 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002076 caller()->CreateAndSetAndSignalOffer();
2077 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2078 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002079 MediaExpectations media_expectations;
2080 media_expectations.ExpectBidirectionalAudioAndVideo();
2081 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002082}
2083
2084// This test sets up a call that's transferred to a new callee with a different
2085// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002086TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002087 ASSERT_TRUE(CreatePeerConnectionWrappers());
2088 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002089 caller()->AddAudioVideoTracks();
2090 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002091 caller()->CreateAndSetAndSignalOffer();
2092 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2093
2094 // Keep the original peer around which will still send packets to the
2095 // receiving client. These SRTP packets will be dropped.
2096 std::unique_ptr<PeerConnectionWrapper> original_peer(
2097 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002098 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002099 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2100 // directly above.
2101 original_peer->pc()->Close();
2102
2103 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002104 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002105 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2106 caller()->CreateAndSetAndSignalOffer();
2107 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2108 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002109 MediaExpectations media_expectations;
2110 media_expectations.ExpectBidirectionalAudioAndVideo();
2111 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002112}
2113
2114// This test sets up a non-bundled call and negotiates bundling at the same
2115// time as starting an ICE restart. When bundling is in effect in the restart,
2116// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002117TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002118 ASSERT_TRUE(CreatePeerConnectionWrappers());
2119 ConnectFakeSignaling();
2120
Steve Anton15324772018-01-16 10:26:49 -08002121 caller()->AddAudioVideoTracks();
2122 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002123 // Remove the bundle group from the SDP received by the callee.
2124 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2125 desc->RemoveGroupByName("BUNDLE");
2126 });
2127 caller()->CreateAndSetAndSignalOffer();
2128 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002129 {
2130 MediaExpectations media_expectations;
2131 media_expectations.ExpectBidirectionalAudioAndVideo();
2132 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2133 }
deadbeef1dcb1642017-03-29 21:08:16 -07002134 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2135 callee()->SetReceivedSdpMunger(nullptr);
2136 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2137 caller()->CreateAndSetAndSignalOffer();
2138 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2139
2140 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002141 {
2142 MediaExpectations media_expectations;
2143 media_expectations.ExpectBidirectionalAudioAndVideo();
2144 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2145 }
deadbeef1dcb1642017-03-29 21:08:16 -07002146}
2147
2148// Test CVO (Coordination of Video Orientation). If a video source is rotated
2149// and both peers support the CVO RTP header extension, the actual video frames
2150// don't need to be encoded in different resolutions, since the rotation is
2151// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002152TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002153 ASSERT_TRUE(CreatePeerConnectionWrappers());
2154 ConnectFakeSignaling();
2155 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002156 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002157 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002158 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002159 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2160
2161 // Wait for video frames to be received by both sides.
2162 caller()->CreateAndSetAndSignalOffer();
2163 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2164 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2165 callee()->min_video_frames_received_per_track() > 0,
2166 kMaxWaitForFramesMs);
2167
2168 // Ensure that the aspect ratio is unmodified.
2169 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2170 // not just assumed.
2171 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2172 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2173 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2174 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2175 // Ensure that the CVO bits were surfaced to the renderer.
2176 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2177 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2178}
2179
2180// Test that when the CVO extension isn't supported, video is rotated the
2181// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002182TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002183 ASSERT_TRUE(CreatePeerConnectionWrappers());
2184 ConnectFakeSignaling();
2185 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002186 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002187 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002188 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002189 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2190
2191 // Remove the CVO extension from the offered SDP.
2192 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2193 cricket::VideoContentDescription* video =
2194 GetFirstVideoContentDescription(desc);
2195 video->ClearRtpHeaderExtensions();
2196 });
2197 // Wait for video frames to be received by both sides.
2198 caller()->CreateAndSetAndSignalOffer();
2199 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2200 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2201 callee()->min_video_frames_received_per_track() > 0,
2202 kMaxWaitForFramesMs);
2203
2204 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2205 // rotation.
2206 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2207 // not just assumed.
2208 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2209 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2210 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2211 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2212 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2213 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2214 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2215}
2216
deadbeef1dcb1642017-03-29 21:08:16 -07002217// Test that if the answerer rejects the audio m= section, no audio is sent or
2218// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002219TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002220 ASSERT_TRUE(CreatePeerConnectionWrappers());
2221 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002222 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002223 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2224 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2225 // it will reject the audio m= section completely.
2226 PeerConnectionInterface::RTCOfferAnswerOptions options;
2227 options.offer_to_receive_audio = 0;
2228 callee()->SetOfferAnswerOptions(options);
2229 } else {
2230 // Stopping the audio RtpTransceiver will cause the media section to be
2231 // rejected in the answer.
2232 callee()->SetRemoteOfferHandler([this] {
2233 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2234 });
2235 }
Steve Anton15324772018-01-16 10:26:49 -08002236 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002237 // Do offer/answer and wait for successful end-to-end video frames.
2238 caller()->CreateAndSetAndSignalOffer();
2239 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002240 MediaExpectations media_expectations;
2241 media_expectations.ExpectBidirectionalVideo();
2242 media_expectations.ExpectNoAudio();
2243 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2244
deadbeef1dcb1642017-03-29 21:08:16 -07002245 // Sanity check that the callee's description has a rejected audio section.
2246 ASSERT_NE(nullptr, callee()->pc()->local_description());
2247 const ContentInfo* callee_audio_content =
2248 GetFirstAudioContent(callee()->pc()->local_description()->description());
2249 ASSERT_NE(nullptr, callee_audio_content);
2250 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002251 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2252 // The caller's transceiver should have stopped after receiving the answer.
2253 EXPECT_TRUE(caller()
2254 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2255 ->stopped());
2256 }
deadbeef1dcb1642017-03-29 21:08:16 -07002257}
2258
2259// Test that if the answerer rejects the video m= section, no video is sent or
2260// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002261TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002262 ASSERT_TRUE(CreatePeerConnectionWrappers());
2263 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002264 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002265 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2266 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2267 // it will reject the video m= section completely.
2268 PeerConnectionInterface::RTCOfferAnswerOptions options;
2269 options.offer_to_receive_video = 0;
2270 callee()->SetOfferAnswerOptions(options);
2271 } else {
2272 // Stopping the video RtpTransceiver will cause the media section to be
2273 // rejected in the answer.
2274 callee()->SetRemoteOfferHandler([this] {
2275 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2276 });
2277 }
Steve Anton15324772018-01-16 10:26:49 -08002278 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002279 // Do offer/answer and wait for successful end-to-end audio frames.
2280 caller()->CreateAndSetAndSignalOffer();
2281 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002282 MediaExpectations media_expectations;
2283 media_expectations.ExpectBidirectionalAudio();
2284 media_expectations.ExpectNoVideo();
2285 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2286
deadbeef1dcb1642017-03-29 21:08:16 -07002287 // Sanity check that the callee's description has a rejected video section.
2288 ASSERT_NE(nullptr, callee()->pc()->local_description());
2289 const ContentInfo* callee_video_content =
2290 GetFirstVideoContent(callee()->pc()->local_description()->description());
2291 ASSERT_NE(nullptr, callee_video_content);
2292 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002293 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2294 // The caller's transceiver should have stopped after receiving the answer.
2295 EXPECT_TRUE(caller()
2296 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2297 ->stopped());
2298 }
deadbeef1dcb1642017-03-29 21:08:16 -07002299}
2300
2301// Test that if the answerer rejects both audio and video m= sections, nothing
2302// bad happens.
2303// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2304// test anything but the fact that negotiation succeeds, which doesn't mean
2305// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002306TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002307 ASSERT_TRUE(CreatePeerConnectionWrappers());
2308 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002309 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002310 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2311 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2312 // will reject both audio and video m= sections.
2313 PeerConnectionInterface::RTCOfferAnswerOptions options;
2314 options.offer_to_receive_audio = 0;
2315 options.offer_to_receive_video = 0;
2316 callee()->SetOfferAnswerOptions(options);
2317 } else {
2318 callee()->SetRemoteOfferHandler([this] {
2319 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002320 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002321 transceiver->Stop();
2322 }
2323 });
2324 }
deadbeef1dcb1642017-03-29 21:08:16 -07002325 // Do offer/answer and wait for stable signaling state.
2326 caller()->CreateAndSetAndSignalOffer();
2327 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002328
deadbeef1dcb1642017-03-29 21:08:16 -07002329 // Sanity check that the callee's description has rejected m= sections.
2330 ASSERT_NE(nullptr, callee()->pc()->local_description());
2331 const ContentInfo* callee_audio_content =
2332 GetFirstAudioContent(callee()->pc()->local_description()->description());
2333 ASSERT_NE(nullptr, callee_audio_content);
2334 EXPECT_TRUE(callee_audio_content->rejected);
2335 const ContentInfo* callee_video_content =
2336 GetFirstVideoContent(callee()->pc()->local_description()->description());
2337 ASSERT_NE(nullptr, callee_video_content);
2338 EXPECT_TRUE(callee_video_content->rejected);
2339}
2340
2341// This test sets up an audio and video call between two parties. After the
2342// call runs for a while, the caller sends an updated offer with video being
2343// rejected. Once the re-negotiation is done, the video flow should stop and
2344// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002345TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002346 ASSERT_TRUE(CreatePeerConnectionWrappers());
2347 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002348 caller()->AddAudioVideoTracks();
2349 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002350 caller()->CreateAndSetAndSignalOffer();
2351 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002352 {
2353 MediaExpectations media_expectations;
2354 media_expectations.ExpectBidirectionalAudioAndVideo();
2355 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2356 }
deadbeef1dcb1642017-03-29 21:08:16 -07002357 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002358 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2359 caller()->SetGeneratedSdpMunger(
2360 [](cricket::SessionDescription* description) {
2361 for (cricket::ContentInfo& content : description->contents()) {
2362 if (cricket::IsVideoContent(&content)) {
2363 content.rejected = true;
2364 }
2365 }
2366 });
2367 } else {
2368 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2369 }
deadbeef1dcb1642017-03-29 21:08:16 -07002370 caller()->CreateAndSetAndSignalOffer();
2371 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2372
2373 // Sanity check that the caller's description has a rejected video section.
2374 ASSERT_NE(nullptr, caller()->pc()->local_description());
2375 const ContentInfo* caller_video_content =
2376 GetFirstVideoContent(caller()->pc()->local_description()->description());
2377 ASSERT_NE(nullptr, caller_video_content);
2378 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002379 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002380 {
2381 MediaExpectations media_expectations;
2382 media_expectations.ExpectBidirectionalAudio();
2383 media_expectations.ExpectNoVideo();
2384 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2385 }
deadbeef1dcb1642017-03-29 21:08:16 -07002386}
2387
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002388// Do one offer/answer with audio, another that disables it (rejecting the m=
2389// section), and another that re-enables it. Regression test for:
2390// bugs.webrtc.org/6023
2391TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2392 ASSERT_TRUE(CreatePeerConnectionWrappers());
2393 ConnectFakeSignaling();
2394
2395 // Add audio track, do normal offer/answer.
2396 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2397 caller()->CreateLocalAudioTrack();
2398 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2399 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2400 caller()->CreateAndSetAndSignalOffer();
2401 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2402
2403 // Remove audio track, and set offer_to_receive_audio to false to cause the
2404 // m= section to be completely disabled, not just "recvonly".
2405 caller()->pc()->RemoveTrack(sender);
2406 PeerConnectionInterface::RTCOfferAnswerOptions options;
2407 options.offer_to_receive_audio = 0;
2408 caller()->SetOfferAnswerOptions(options);
2409 caller()->CreateAndSetAndSignalOffer();
2410 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2411
2412 // Add the audio track again, expecting negotiation to succeed and frames to
2413 // flow.
2414 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2415 options.offer_to_receive_audio = 1;
2416 caller()->SetOfferAnswerOptions(options);
2417 caller()->CreateAndSetAndSignalOffer();
2418 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2419
2420 MediaExpectations media_expectations;
2421 media_expectations.CalleeExpectsSomeAudio();
2422 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2423}
2424
deadbeef1dcb1642017-03-29 21:08:16 -07002425// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2426// is needed to support legacy endpoints.
2427// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2428// add a test for an end-to-end test without MID signaling either (basically,
2429// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002430TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002431 ASSERT_TRUE(CreatePeerConnectionWrappers());
2432 ConnectFakeSignaling();
2433 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002434 caller()->AddAudioVideoTracks();
2435 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002436 // Remove SSRCs and MSIDs from the received offer SDP.
2437 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002438 caller()->CreateAndSetAndSignalOffer();
2439 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002440 MediaExpectations media_expectations;
2441 media_expectations.ExpectBidirectionalAudioAndVideo();
2442 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002443}
2444
Seth Hampson5897a6e2018-04-03 11:16:33 -07002445// Basic end-to-end test, without SSRC signaling. This means that the track
2446// was created properly and frames are delivered when the MSIDs are communicated
2447// with a=msid lines and no a=ssrc lines.
2448TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2449 EndToEndCallWithoutSsrcSignaling) {
2450 const char kStreamId[] = "streamId";
2451 ASSERT_TRUE(CreatePeerConnectionWrappers());
2452 ConnectFakeSignaling();
2453 // Add just audio tracks.
2454 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2455 callee()->AddAudioTrack();
2456
2457 // Remove SSRCs from the received offer SDP.
2458 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2459 caller()->CreateAndSetAndSignalOffer();
2460 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2461 MediaExpectations media_expectations;
2462 media_expectations.ExpectBidirectionalAudio();
2463 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2464}
2465
Steve Antondf527fd2018-04-27 15:52:03 -07002466// Tests that video flows between multiple video tracks when SSRCs are not
2467// signaled. This exercises the MID RTP header extension which is needed to
2468// demux the incoming video tracks.
2469TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2470 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2471 ASSERT_TRUE(CreatePeerConnectionWrappers());
2472 ConnectFakeSignaling();
2473 caller()->AddVideoTrack();
2474 caller()->AddVideoTrack();
2475 callee()->AddVideoTrack();
2476 callee()->AddVideoTrack();
2477
2478 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2479 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2480 caller()->CreateAndSetAndSignalOffer();
2481 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2482 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2483 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2484
2485 // Expect video to be received in both directions on both tracks.
2486 MediaExpectations media_expectations;
2487 media_expectations.ExpectBidirectionalVideo();
2488 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2489}
2490
Henrik Boström5b147782018-12-04 11:25:05 +01002491TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2492 ASSERT_TRUE(CreatePeerConnectionWrappers());
2493 ConnectFakeSignaling();
2494 caller()->AddAudioTrack();
2495 caller()->AddVideoTrack();
2496 caller()->CreateAndSetAndSignalOffer();
2497 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2498 auto callee_receivers = callee()->pc()->GetReceivers();
2499 ASSERT_EQ(2u, callee_receivers.size());
2500 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2501 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2502}
2503
2504TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2505 ASSERT_TRUE(CreatePeerConnectionWrappers());
2506 ConnectFakeSignaling();
2507 caller()->AddAudioTrack();
2508 caller()->AddVideoTrack();
2509 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2510 caller()->CreateAndSetAndSignalOffer();
2511 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2512 auto callee_receivers = callee()->pc()->GetReceivers();
2513 ASSERT_EQ(2u, callee_receivers.size());
2514 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2515 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2516 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2517 callee_receivers[1]->stream_ids()[0]);
2518 EXPECT_EQ(callee_receivers[0]->streams()[0],
2519 callee_receivers[1]->streams()[0]);
2520}
2521
deadbeef1dcb1642017-03-29 21:08:16 -07002522// Test that if two video tracks are sent (from caller to callee, in this test),
2523// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002524TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002525 ASSERT_TRUE(CreatePeerConnectionWrappers());
2526 ConnectFakeSignaling();
2527 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002528 caller()->AddAudioVideoTracks();
2529 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002530 caller()->CreateAndSetAndSignalOffer();
2531 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002532 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002533
2534 MediaExpectations media_expectations;
2535 media_expectations.CalleeExpectsSomeAudioAndVideo();
2536 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002537}
2538
2539static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2540 bool first = true;
2541 for (cricket::ContentInfo& content : desc->contents()) {
2542 if (first) {
2543 first = false;
2544 continue;
2545 }
2546 content.bundle_only = true;
2547 }
2548 first = true;
2549 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2550 if (first) {
2551 first = false;
2552 continue;
2553 }
2554 transport.description.ice_ufrag.clear();
2555 transport.description.ice_pwd.clear();
2556 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2557 transport.description.identity_fingerprint.reset(nullptr);
2558 }
2559}
2560
2561// Test that if applying a true "max bundle" offer, which uses ports of 0,
2562// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2563// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2564// successfully and media flows.
2565// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2566// TODO(deadbeef): Won't need this test once we start generating actual
2567// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002568TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002569 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2570 ASSERT_TRUE(CreatePeerConnectionWrappers());
2571 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002572 caller()->AddAudioVideoTracks();
2573 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002574 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2575 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2576 // but the first m= section.
2577 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2578 caller()->CreateAndSetAndSignalOffer();
2579 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002580 MediaExpectations media_expectations;
2581 media_expectations.ExpectBidirectionalAudioAndVideo();
2582 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002583}
2584
2585// Test that we can receive the audio output level from a remote audio track.
2586// TODO(deadbeef): Use a fake audio source and verify that the output level is
2587// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002588TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002589 ASSERT_TRUE(CreatePeerConnectionWrappers());
2590 ConnectFakeSignaling();
2591 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002592 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002593 caller()->CreateAndSetAndSignalOffer();
2594 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2595
2596 // Get the audio output level stats. Note that the level is not available
2597 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002598 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002599 kMaxWaitForFramesMs);
2600}
2601
2602// Test that an audio input level is reported.
2603// TODO(deadbeef): Use a fake audio source and verify that the input level is
2604// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002605TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002606 ASSERT_TRUE(CreatePeerConnectionWrappers());
2607 ConnectFakeSignaling();
2608 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002609 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002610 caller()->CreateAndSetAndSignalOffer();
2611 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2612
2613 // Get the audio input level stats. The level should be available very
2614 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002615 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002616 kMaxWaitForStatsMs);
2617}
2618
2619// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002620TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002621 ASSERT_TRUE(CreatePeerConnectionWrappers());
2622 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002623 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002624 // Do offer/answer, wait for the callee to receive some frames.
2625 caller()->CreateAndSetAndSignalOffer();
2626 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002627
2628 MediaExpectations media_expectations;
2629 media_expectations.CalleeExpectsSomeAudioAndVideo();
2630 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002631
2632 // Get a handle to the remote tracks created, so they can be used as GetStats
2633 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002634 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002635 // We received frames, so we definitely should have nonzero "received bytes"
2636 // stats at this point.
2637 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2638 0);
2639 }
deadbeef1dcb1642017-03-29 21:08:16 -07002640}
2641
2642// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002643TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002644 ASSERT_TRUE(CreatePeerConnectionWrappers());
2645 ConnectFakeSignaling();
2646 auto audio_track = caller()->CreateLocalAudioTrack();
2647 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002648 caller()->AddTrack(audio_track);
2649 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002650 // Do offer/answer, wait for the callee to receive some frames.
2651 caller()->CreateAndSetAndSignalOffer();
2652 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002653 MediaExpectations media_expectations;
2654 media_expectations.CalleeExpectsSomeAudioAndVideo();
2655 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002656
2657 // The callee received frames, so we definitely should have nonzero "sent
2658 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002659 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2660 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2661}
2662
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002663// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002664TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002665 ASSERT_TRUE(CreatePeerConnectionWrappers());
2666 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002667 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002668
Steve Anton15324772018-01-16 10:26:49 -08002669 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002670
2671 // Do offer/answer, wait for the callee to receive some frames.
2672 caller()->CreateAndSetAndSignalOffer();
2673 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2674
2675 // Get the remote audio track created on the receiver, so they can be used as
2676 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002677 auto receivers = callee()->pc()->GetReceivers();
2678 ASSERT_EQ(1u, receivers.size());
2679 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002680
2681 // Get the audio output level stats. Note that the level is not available
2682 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002683 EXPECT_TRUE_WAIT(
2684 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2685 0,
2686 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002687}
2688
Steve Antona41959e2018-11-28 11:15:33 -08002689// Test that the track ID is associated with all local and remote SSRC stats
2690// using the old GetStats() and more than 1 audio and more than 1 video track.
2691// This is a regression test for crbug.com/906988
2692TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2693 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2694 ASSERT_TRUE(CreatePeerConnectionWrappers());
2695 ConnectFakeSignaling();
2696 auto audio_sender_1 = caller()->AddAudioTrack();
2697 auto video_sender_1 = caller()->AddVideoTrack();
2698 auto audio_sender_2 = caller()->AddAudioTrack();
2699 auto video_sender_2 = caller()->AddVideoTrack();
2700 caller()->CreateAndSetAndSignalOffer();
2701 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2702
2703 MediaExpectations media_expectations;
2704 media_expectations.CalleeExpectsSomeAudioAndVideo();
2705 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2706
2707 std::vector<std::string> track_ids = {
2708 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2709 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2710
2711 auto caller_stats = caller()->OldGetStats();
2712 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2713 auto callee_stats = callee()->OldGetStats();
2714 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2715}
2716
Steve Antonffa6ce42018-11-30 09:26:08 -08002717// Test that the new GetStats() returns stats for all outgoing/incoming streams
2718// with the correct track IDs if there are more than one audio and more than one
2719// video senders/receivers.
2720TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2721 ASSERT_TRUE(CreatePeerConnectionWrappers());
2722 ConnectFakeSignaling();
2723 auto audio_sender_1 = caller()->AddAudioTrack();
2724 auto video_sender_1 = caller()->AddVideoTrack();
2725 auto audio_sender_2 = caller()->AddAudioTrack();
2726 auto video_sender_2 = caller()->AddVideoTrack();
2727 caller()->CreateAndSetAndSignalOffer();
2728 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2729
2730 MediaExpectations media_expectations;
2731 media_expectations.CalleeExpectsSomeAudioAndVideo();
2732 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2733
2734 std::vector<std::string> track_ids = {
2735 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2736 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2737
2738 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2739 caller()->NewGetStats();
2740 ASSERT_TRUE(caller_report);
2741 auto outbound_stream_stats =
2742 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2743 ASSERT_EQ(4u, outbound_stream_stats.size());
2744 std::vector<std::string> outbound_track_ids;
2745 for (const auto& stat : outbound_stream_stats) {
2746 ASSERT_TRUE(stat->bytes_sent.is_defined());
2747 EXPECT_LT(0u, *stat->bytes_sent);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002748 if (*stat->kind == "video") {
2749 ASSERT_TRUE(stat->key_frames_encoded.is_defined());
2750 EXPECT_GT(*stat->key_frames_encoded, 0u);
2751 ASSERT_TRUE(stat->frames_encoded.is_defined());
2752 EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
2753 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002754 ASSERT_TRUE(stat->track_id.is_defined());
2755 const auto* track_stat =
2756 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2757 ASSERT_TRUE(track_stat);
2758 outbound_track_ids.push_back(*track_stat->track_identifier);
2759 }
2760 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2761
2762 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2763 callee()->NewGetStats();
2764 ASSERT_TRUE(callee_report);
2765 auto inbound_stream_stats =
2766 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2767 ASSERT_EQ(4u, inbound_stream_stats.size());
2768 std::vector<std::string> inbound_track_ids;
2769 for (const auto& stat : inbound_stream_stats) {
2770 ASSERT_TRUE(stat->bytes_received.is_defined());
2771 EXPECT_LT(0u, *stat->bytes_received);
Rasmus Brandt2efae772019-06-27 14:29:34 +02002772 if (*stat->kind == "video") {
2773 ASSERT_TRUE(stat->key_frames_decoded.is_defined());
2774 EXPECT_GT(*stat->key_frames_decoded, 0u);
2775 ASSERT_TRUE(stat->frames_decoded.is_defined());
2776 EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
2777 }
Steve Antonffa6ce42018-11-30 09:26:08 -08002778 ASSERT_TRUE(stat->track_id.is_defined());
2779 const auto* track_stat =
2780 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2781 ASSERT_TRUE(track_stat);
2782 inbound_track_ids.push_back(*track_stat->track_identifier);
2783 }
2784 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2785}
2786
2787// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002788// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2789// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002790TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002791 GetStatsForUnsignaledStreamWithNewStatsApi) {
2792 ASSERT_TRUE(CreatePeerConnectionWrappers());
2793 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002794 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002795 // Remove SSRCs and MSIDs from the received offer SDP.
2796 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2797 caller()->CreateAndSetAndSignalOffer();
2798 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002799 MediaExpectations media_expectations;
2800 media_expectations.CalleeExpectsSomeAudio(1);
2801 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002802
2803 // We received a frame, so we should have nonzero "bytes received" stats for
2804 // the unsignaled stream, if stats are working for it.
2805 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2806 callee()->NewGetStats();
2807 ASSERT_NE(nullptr, report);
2808 auto inbound_stream_stats =
2809 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2810 ASSERT_EQ(1U, inbound_stream_stats.size());
2811 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2812 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002813 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2814}
2815
Taylor Brandstettera4653442018-06-19 09:44:26 -07002816// Same as above but for the legacy stats implementation.
2817TEST_P(PeerConnectionIntegrationTest,
2818 GetStatsForUnsignaledStreamWithOldStatsApi) {
2819 ASSERT_TRUE(CreatePeerConnectionWrappers());
2820 ConnectFakeSignaling();
2821 caller()->AddAudioTrack();
2822 // Remove SSRCs and MSIDs from the received offer SDP.
2823 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2824 caller()->CreateAndSetAndSignalOffer();
2825 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2826
2827 // Note that, since the old stats implementation associates SSRCs with tracks
2828 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2829 // associated track ID. So we can't use the track "selector" argument.
2830 //
2831 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2832 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002833 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002834 kDefaultTimeout);
2835}
2836
zhihuangf8164932017-05-19 13:09:47 -07002837// Test that we can successfully get the media related stats (audio level
2838// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002839TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002840 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2841 ASSERT_TRUE(CreatePeerConnectionWrappers());
2842 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002843 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002844 // Remove SSRCs and MSIDs from the received offer SDP.
2845 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2846 caller()->CreateAndSetAndSignalOffer();
2847 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002848 MediaExpectations media_expectations;
2849 media_expectations.CalleeExpectsSomeAudio(1);
2850 media_expectations.CalleeExpectsSomeVideo(1);
2851 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002852
2853 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2854 callee()->NewGetStats();
2855 ASSERT_NE(nullptr, report);
2856
2857 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2858 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2859 ASSERT_GE(audio_index, 0);
2860 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002861}
2862
deadbeef4e2deab2017-09-20 13:56:21 -07002863// Helper for test below.
2864void ModifySsrcs(cricket::SessionDescription* desc) {
2865 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002866 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002867 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002868 for (uint32_t& ssrc : stream.ssrcs) {
2869 ssrc = rtc::CreateRandomId();
2870 }
2871 }
2872 }
2873}
2874
2875// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2876// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2877// This should result in two "RTCInboundRTPStreamStats", but only one
2878// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2879// being reset to 0 once the SSRC change occurs.
2880//
2881// Regression test for this bug:
2882// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2883//
2884// The bug causes the track stats to only represent one of the two streams:
2885// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2886// that the track stat counters would reset to 0 when the new stream is
2887// received, and a 50% chance that they'll stop updating (while
2888// "concealed_samples" continues increasing, due to silence being generated for
2889// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002890TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002891 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002892 ASSERT_TRUE(CreatePeerConnectionWrappers());
2893 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002894 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002895 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2896 // that doesn't signal SSRCs (from the callee's perspective).
2897 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2898 caller()->CreateAndSetAndSignalOffer();
2899 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2900 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002901 {
2902 MediaExpectations media_expectations;
2903 media_expectations.CalleeExpectsSomeAudio(50);
2904 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2905 }
deadbeef4e2deab2017-09-20 13:56:21 -07002906 // Some audio frames were received, so we should have nonzero "samples
2907 // received" for the track.
2908 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2909 callee()->NewGetStats();
2910 ASSERT_NE(nullptr, report);
2911 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2912 ASSERT_EQ(1U, track_stats.size());
2913 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2914 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2915 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2916
2917 // Create a new offer and munge it to cause the caller to use a new SSRC.
2918 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2919 caller()->CreateAndSetAndSignalOffer();
2920 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2921 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2922 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002923 {
2924 MediaExpectations media_expectations;
2925 media_expectations.CalleeExpectsSomeAudio(25);
2926 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2927 }
deadbeef4e2deab2017-09-20 13:56:21 -07002928
2929 report = callee()->NewGetStats();
2930 ASSERT_NE(nullptr, report);
2931 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2932 ASSERT_EQ(1U, track_stats.size());
2933 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2934 // The "total samples received" stat should only be greater than it was
2935 // before.
2936 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2937 // Right now, the new SSRC will cause the counters to reset to 0.
2938 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2939
2940 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002941 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002942 // good sign that we're seeing stats from the old stream that's no longer
2943 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002944 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002945 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2946 EXPECT_LT(*track_stats[0]->concealed_samples,
2947 *track_stats[0]->total_samples_received *
2948 kAcceptableConcealedSamplesPercentage);
2949
2950 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2951 // sanity check that the SSRC really changed.
2952 // TODO(deadbeef): This isn't working right now, because we're not returning
2953 // *any* stats for the inactive stream. Uncomment when the bug is completely
2954 // fixed.
2955 // auto inbound_stream_stats =
2956 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2957 // ASSERT_EQ(2U, inbound_stream_stats.size());
2958}
2959
deadbeef1dcb1642017-03-29 21:08:16 -07002960// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002961TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002962 PeerConnectionFactory::Options dtls_10_options;
2963 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2964 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2965 dtls_10_options));
2966 ConnectFakeSignaling();
2967 // Do normal offer/answer and wait for some frames to be received in each
2968 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002969 caller()->AddAudioVideoTracks();
2970 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002971 caller()->CreateAndSetAndSignalOffer();
2972 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002973 MediaExpectations media_expectations;
2974 media_expectations.ExpectBidirectionalAudioAndVideo();
2975 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002976}
2977
2978// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002979TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002980 PeerConnectionFactory::Options dtls_10_options;
2981 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2982 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2983 dtls_10_options));
2984 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002985 caller()->AddAudioVideoTracks();
2986 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002987 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002988 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002989 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002990 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002991 kDefaultTimeout);
2992 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002993 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002994 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002995 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002996 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2997 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002998}
2999
3000// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003001TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07003002 PeerConnectionFactory::Options dtls_12_options;
3003 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3004 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
3005 dtls_12_options));
3006 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08003007 caller()->AddAudioVideoTracks();
3008 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003009 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003010 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003011 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07003012 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07003013 kDefaultTimeout);
3014 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07003015 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003016 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00003017 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07003018 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
3019 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07003020}
3021
3022// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
3023// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003024TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07003025 PeerConnectionFactory::Options caller_options;
3026 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3027 PeerConnectionFactory::Options callee_options;
3028 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3029 ASSERT_TRUE(
3030 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3031 ConnectFakeSignaling();
3032 // Do normal offer/answer and wait for some frames to be received in each
3033 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003034 caller()->AddAudioVideoTracks();
3035 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003036 caller()->CreateAndSetAndSignalOffer();
3037 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003038 MediaExpectations media_expectations;
3039 media_expectations.ExpectBidirectionalAudioAndVideo();
3040 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003041}
3042
3043// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
3044// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003045TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003046 PeerConnectionFactory::Options caller_options;
3047 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3048 PeerConnectionFactory::Options callee_options;
3049 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3050 ASSERT_TRUE(
3051 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3052 ConnectFakeSignaling();
3053 // Do normal offer/answer and wait for some frames to be received in each
3054 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003055 caller()->AddAudioVideoTracks();
3056 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003057 caller()->CreateAndSetAndSignalOffer();
3058 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003059 MediaExpectations media_expectations;
3060 media_expectations.ExpectBidirectionalAudioAndVideo();
3061 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003062}
3063
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003064// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3065// works as expected; the cipher should only be used if enabled by both sides.
3066TEST_P(PeerConnectionIntegrationTest,
3067 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3068 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003069 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003070 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003071 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3072 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003073 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3074 TestNegotiatedCipherSuite(caller_options, callee_options,
3075 expected_cipher_suite);
3076}
3077
3078TEST_P(PeerConnectionIntegrationTest,
3079 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3080 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003081 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3082 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003083 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003084 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003085 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3086 TestNegotiatedCipherSuite(caller_options, callee_options,
3087 expected_cipher_suite);
3088}
3089
3090TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3091 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003092 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003093 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003094 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003095 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3096 TestNegotiatedCipherSuite(caller_options, callee_options,
3097 expected_cipher_suite);
3098}
3099
deadbeef1dcb1642017-03-29 21:08:16 -07003100// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003101TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003102 bool local_gcm_enabled = false;
3103 bool remote_gcm_enabled = false;
3104 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3105 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3106 expected_cipher_suite);
3107}
3108
3109// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003110TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003111 bool local_gcm_enabled = true;
3112 bool remote_gcm_enabled = true;
3113 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3114 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3115 expected_cipher_suite);
3116}
3117
3118// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003119TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003120 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
3121 bool local_gcm_enabled = true;
3122 bool remote_gcm_enabled = false;
3123 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3124 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3125 expected_cipher_suite);
3126}
3127
3128// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003129TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003130 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
3131 bool local_gcm_enabled = false;
3132 bool remote_gcm_enabled = true;
3133 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3134 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3135 expected_cipher_suite);
3136}
3137
deadbeef7914b8c2017-04-21 03:23:33 -07003138// Verify that media can be transmitted end-to-end when GCM crypto suites are
3139// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3140// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3141// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003142TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003143 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003144 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07003145 ASSERT_TRUE(
3146 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3147 ConnectFakeSignaling();
3148 // Do normal offer/answer and wait for some frames to be received in each
3149 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003150 caller()->AddAudioVideoTracks();
3151 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003152 caller()->CreateAndSetAndSignalOffer();
3153 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003154 MediaExpectations media_expectations;
3155 media_expectations.ExpectBidirectionalAudioAndVideo();
3156 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003157}
3158
deadbeef1dcb1642017-03-29 21:08:16 -07003159// This test sets up a call between two parties with audio, video and an RTP
3160// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003161TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003162 PeerConnectionInterface::RTCConfiguration rtc_config;
3163 rtc_config.enable_rtp_data_channel = true;
3164 rtc_config.enable_dtls_srtp = false;
3165 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003166 ConnectFakeSignaling();
3167 // Expect that data channel created on caller side will show up for callee as
3168 // well.
3169 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003170 caller()->AddAudioVideoTracks();
3171 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003172 caller()->CreateAndSetAndSignalOffer();
3173 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3174 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003175 MediaExpectations media_expectations;
3176 media_expectations.ExpectBidirectionalAudioAndVideo();
3177 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003178 ASSERT_NE(nullptr, caller()->data_channel());
3179 ASSERT_NE(nullptr, callee()->data_channel());
3180 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3181 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3182
3183 // Ensure data can be sent in both directions.
3184 std::string data = "hello world";
3185 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3186 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3187 kDefaultTimeout);
3188 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3189 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3190 kDefaultTimeout);
3191}
3192
3193// Ensure that an RTP data channel is signaled as closed for the caller when
3194// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003195TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003196 RtpDataChannelSignaledClosedInCalleeOffer) {
3197 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003198 PeerConnectionInterface::RTCConfiguration rtc_config;
3199 rtc_config.enable_rtp_data_channel = true;
3200 rtc_config.enable_dtls_srtp = false;
3201 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003202 ConnectFakeSignaling();
3203 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003204 caller()->AddAudioVideoTracks();
3205 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003206 caller()->CreateAndSetAndSignalOffer();
3207 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3208 ASSERT_NE(nullptr, caller()->data_channel());
3209 ASSERT_NE(nullptr, callee()->data_channel());
3210 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3211 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3212
3213 // Close the data channel on the callee, and do an updated offer/answer.
3214 callee()->data_channel()->Close();
3215 callee()->CreateAndSetAndSignalOffer();
3216 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3217 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3218 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3219}
3220
3221// Tests that data is buffered in an RTP data channel until an observer is
3222// registered for it.
3223//
3224// NOTE: RTP data channels can receive data before the underlying
3225// transport has detected that a channel is writable and thus data can be
3226// received before the data channel state changes to open. That is hard to test
3227// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003228TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003229 DataBufferedUntilRtpDataChannelObserverRegistered) {
3230 // Use fake clock and simulated network delay so that we predictably can wait
3231 // until an SCTP message has been delivered without "sleep()"ing.
3232 rtc::ScopedFakeClock fake_clock;
3233 // Some things use a time of "0" as a special value, so we need to start out
3234 // the fake clock at a nonzero time.
3235 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003236 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003237 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3238 virtual_socket_server()->UpdateDelayDistribution();
3239
Niels Möllerf06f9232018-08-07 12:32:18 +02003240 PeerConnectionInterface::RTCConfiguration rtc_config;
3241 rtc_config.enable_rtp_data_channel = true;
3242 rtc_config.enable_dtls_srtp = false;
3243 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003244 ConnectFakeSignaling();
3245 caller()->CreateDataChannel();
3246 caller()->CreateAndSetAndSignalOffer();
3247 ASSERT_TRUE(caller()->data_channel() != nullptr);
3248 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3249 kDefaultTimeout, fake_clock);
3250 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3251 kDefaultTimeout, fake_clock);
3252 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3253 callee()->data_channel()->state(), kDefaultTimeout,
3254 fake_clock);
3255
3256 // Unregister the observer which is normally automatically registered.
3257 callee()->data_channel()->UnregisterObserver();
3258 // Send data and advance fake clock until it should have been received.
3259 std::string data = "hello world";
3260 caller()->data_channel()->Send(DataBuffer(data));
3261 SIMULATED_WAIT(false, 50, fake_clock);
3262
3263 // Attach data channel and expect data to be received immediately. Note that
3264 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3265 // further, but data can be received even if the callback is asynchronous.
3266 MockDataChannelObserver new_observer(callee()->data_channel());
3267 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3268 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003269 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3270 // If this is not done a DCHECK can be hit in ports.cc, because a large
3271 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07003272 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07003273}
3274
3275// This test sets up a call between two parties with audio, video and but only
3276// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003277TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003278 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3279 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003280 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003281 rtc_config_1.enable_dtls_srtp = false;
3282 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3283 rtc_config_2.enable_dtls_srtp = false;
3284 rtc_config_2.enable_dtls_srtp = false;
3285 ASSERT_TRUE(
3286 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003287 ConnectFakeSignaling();
3288 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003289 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003290 caller()->AddAudioVideoTracks();
3291 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003292 caller()->CreateAndSetAndSignalOffer();
3293 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3294 // The caller should still have a data channel, but it should be closed, and
3295 // one should ever have been created for the callee.
3296 EXPECT_TRUE(caller()->data_channel() != nullptr);
3297 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3298 EXPECT_EQ(nullptr, callee()->data_channel());
3299}
3300
3301// This test sets up a call between two parties with audio, and video. When
3302// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003303TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003304 PeerConnectionInterface::RTCConfiguration rtc_config;
3305 rtc_config.enable_rtp_data_channel = true;
3306 rtc_config.enable_dtls_srtp = false;
3307 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003308 ConnectFakeSignaling();
3309 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003310 caller()->AddAudioVideoTracks();
3311 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003312 caller()->CreateAndSetAndSignalOffer();
3313 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3314 // Create data channel and do new offer and answer.
3315 caller()->CreateDataChannel();
3316 caller()->CreateAndSetAndSignalOffer();
3317 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3318 ASSERT_NE(nullptr, caller()->data_channel());
3319 ASSERT_NE(nullptr, callee()->data_channel());
3320 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3321 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3322 // Ensure data can be sent in both directions.
3323 std::string data = "hello world";
3324 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3325 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3326 kDefaultTimeout);
3327 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3328 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3329 kDefaultTimeout);
3330}
3331
3332#ifdef HAVE_SCTP
3333
3334// This test sets up a call between two parties with audio, video and an SCTP
3335// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003336TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003337 ASSERT_TRUE(CreatePeerConnectionWrappers());
3338 ConnectFakeSignaling();
3339 // Expect that data channel created on caller side will show up for callee as
3340 // well.
3341 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003342 caller()->AddAudioVideoTracks();
3343 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003344 caller()->CreateAndSetAndSignalOffer();
3345 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3346 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003347 MediaExpectations media_expectations;
3348 media_expectations.ExpectBidirectionalAudioAndVideo();
3349 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003350 // Caller data channel should already exist (it created one). Callee data
3351 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3352 ASSERT_NE(nullptr, caller()->data_channel());
3353 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3354 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3355 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3356
3357 // Ensure data can be sent in both directions.
3358 std::string data = "hello world";
3359 caller()->data_channel()->Send(DataBuffer(data));
3360 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3361 kDefaultTimeout);
3362 callee()->data_channel()->Send(DataBuffer(data));
3363 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3364 kDefaultTimeout);
3365}
3366
3367// Ensure that when the callee closes an SCTP data channel, the closing
3368// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003369TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003370 // Same procedure as above test.
3371 ASSERT_TRUE(CreatePeerConnectionWrappers());
3372 ConnectFakeSignaling();
3373 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003374 caller()->AddAudioVideoTracks();
3375 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003376 caller()->CreateAndSetAndSignalOffer();
3377 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3378 ASSERT_NE(nullptr, caller()->data_channel());
3379 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3380 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3381 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3382
3383 // Close the data channel on the callee side, and wait for it to reach the
3384 // "closed" state on both sides.
3385 callee()->data_channel()->Close();
3386 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3387 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3388}
3389
Seth Hampson2f0d7022018-02-20 11:54:42 -08003390TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003391 ASSERT_TRUE(CreatePeerConnectionWrappers());
3392 ConnectFakeSignaling();
3393 webrtc::DataChannelInit init;
3394 init.id = 53;
3395 init.maxRetransmits = 52;
3396 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003397 caller()->AddAudioVideoTracks();
3398 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003399 caller()->CreateAndSetAndSignalOffer();
3400 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003401 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3402 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003403 // Since "negotiated" is false, the "id" parameter should be ignored.
3404 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003405 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3406 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3407 EXPECT_FALSE(callee()->data_channel()->negotiated());
3408}
3409
deadbeef1dcb1642017-03-29 21:08:16 -07003410// Test usrsctp's ability to process unordered data stream, where data actually
3411// arrives out of order using simulated delays. Previously there have been some
3412// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003413TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003414 // Introduce random network delays.
3415 // Otherwise it's not a true "unordered" test.
3416 virtual_socket_server()->set_delay_mean(20);
3417 virtual_socket_server()->set_delay_stddev(5);
3418 virtual_socket_server()->UpdateDelayDistribution();
3419 // Normal procedure, but with unordered data channel config.
3420 ASSERT_TRUE(CreatePeerConnectionWrappers());
3421 ConnectFakeSignaling();
3422 webrtc::DataChannelInit init;
3423 init.ordered = false;
3424 caller()->CreateDataChannel(&init);
3425 caller()->CreateAndSetAndSignalOffer();
3426 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3427 ASSERT_NE(nullptr, caller()->data_channel());
3428 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3429 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3430 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3431
3432 static constexpr int kNumMessages = 100;
3433 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3434 static constexpr size_t kMaxMessageSize = 4096;
3435 // Create and send random messages.
3436 std::vector<std::string> sent_messages;
3437 for (int i = 0; i < kNumMessages; ++i) {
3438 size_t length =
3439 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3440 std::string message;
3441 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3442 caller()->data_channel()->Send(DataBuffer(message));
3443 callee()->data_channel()->Send(DataBuffer(message));
3444 sent_messages.push_back(message);
3445 }
3446
3447 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003448 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003449 caller()->data_observer()->received_message_count(),
3450 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003451 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003452 callee()->data_observer()->received_message_count(),
3453 kDefaultTimeout);
3454
3455 // Sort and compare to make sure none of the messages were corrupted.
3456 std::vector<std::string> caller_received_messages =
3457 caller()->data_observer()->messages();
3458 std::vector<std::string> callee_received_messages =
3459 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003460 absl::c_sort(sent_messages);
3461 absl::c_sort(caller_received_messages);
3462 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003463 EXPECT_EQ(sent_messages, caller_received_messages);
3464 EXPECT_EQ(sent_messages, callee_received_messages);
3465}
3466
3467// This test sets up a call between two parties with audio, and video. When
3468// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003469TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003470 ASSERT_TRUE(CreatePeerConnectionWrappers());
3471 ConnectFakeSignaling();
3472 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003473 caller()->AddAudioVideoTracks();
3474 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003475 caller()->CreateAndSetAndSignalOffer();
3476 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3477 // Create data channel and do new offer and answer.
3478 caller()->CreateDataChannel();
3479 caller()->CreateAndSetAndSignalOffer();
3480 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3481 // Caller data channel should already exist (it created one). Callee data
3482 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3483 ASSERT_NE(nullptr, caller()->data_channel());
3484 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3485 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3486 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3487 // Ensure data can be sent in both directions.
3488 std::string data = "hello world";
3489 caller()->data_channel()->Send(DataBuffer(data));
3490 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3491 kDefaultTimeout);
3492 callee()->data_channel()->Send(DataBuffer(data));
3493 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3494 kDefaultTimeout);
3495}
3496
deadbeef7914b8c2017-04-21 03:23:33 -07003497// Set up a connection initially just using SCTP data channels, later upgrading
3498// to audio/video, ensuring frames are received end-to-end. Effectively the
3499// inverse of the test above.
3500// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003501TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003502 ASSERT_TRUE(CreatePeerConnectionWrappers());
3503 ConnectFakeSignaling();
3504 // Do initial offer/answer with just data channel.
3505 caller()->CreateDataChannel();
3506 caller()->CreateAndSetAndSignalOffer();
3507 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3508 // Wait until data can be sent over the data channel.
3509 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3510 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3511 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3512
3513 // Do subsequent offer/answer with two-way audio and video. Audio and video
3514 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003515 caller()->AddAudioVideoTracks();
3516 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003517 caller()->CreateAndSetAndSignalOffer();
3518 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003519 MediaExpectations media_expectations;
3520 media_expectations.ExpectBidirectionalAudioAndVideo();
3521 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003522}
3523
deadbeef8b7e9ad2017-05-25 09:38:55 -07003524static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003525 cricket::SctpDataContentDescription* dcd_offer =
3526 GetFirstSctpDataContentDescription(desc);
Steve Antonb1c1de12017-12-21 15:14:30 -08003527 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003528 dcd_offer->set_use_sctpmap(false);
3529 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3530}
3531
3532// Test that the data channel works when a spec-compliant SCTP m= section is
3533// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3534// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003535TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003536 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3537 ASSERT_TRUE(CreatePeerConnectionWrappers());
3538 ConnectFakeSignaling();
3539 caller()->CreateDataChannel();
3540 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3541 caller()->CreateAndSetAndSignalOffer();
3542 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3543 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3544 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3545 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3546
3547 // Ensure data can be sent in both directions.
3548 std::string data = "hello world";
3549 caller()->data_channel()->Send(DataBuffer(data));
3550 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3551 kDefaultTimeout);
3552 callee()->data_channel()->Send(DataBuffer(data));
3553 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3554 kDefaultTimeout);
3555}
3556
deadbeef1dcb1642017-03-29 21:08:16 -07003557#endif // HAVE_SCTP
3558
Bjorn Mellema2eb0a72018-11-09 10:13:51 -08003559// This test sets up a call between two parties with a media transport data
3560// channel.
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003561TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelEndToEnd) {
3562 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003563 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3564 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003565 rtc_config.use_media_transport_for_data_channels = true;
3566 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3567 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3568 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3569 loopback_media_transports()->second_factory()));
3570 ConnectFakeSignaling();
3571
3572 // Expect that data channel created on caller side will show up for callee as
3573 // well.
3574 caller()->CreateDataChannel();
3575 caller()->CreateAndSetAndSignalOffer();
3576 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3577
3578 // Ensure that the media transport is ready.
3579 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3580 loopback_media_transports()->FlushAsyncInvokes();
3581
3582 // Caller data channel should already exist (it created one). Callee data
3583 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3584 ASSERT_NE(nullptr, caller()->data_channel());
3585 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3586 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3587 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3588
3589 // Ensure data can be sent in both directions.
3590 std::string data = "hello world";
3591 caller()->data_channel()->Send(DataBuffer(data));
3592 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3593 kDefaultTimeout);
3594 callee()->data_channel()->Send(DataBuffer(data));
3595 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3596 kDefaultTimeout);
3597}
3598
3599// Ensure that when the callee closes a media transport data channel, the
3600// closing procedure results in the data channel being closed for the caller
3601// as well.
3602TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelCalleeCloses) {
3603 PeerConnectionInterface::RTCConfiguration rtc_config;
3604 rtc_config.use_media_transport_for_data_channels = true;
3605 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3606 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3607 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3608 loopback_media_transports()->second_factory()));
3609 ConnectFakeSignaling();
3610
3611 // Create a data channel on the caller and signal it to the callee.
3612 caller()->CreateDataChannel();
3613 caller()->CreateAndSetAndSignalOffer();
3614 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3615
3616 // Ensure that the media transport is ready.
3617 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3618 loopback_media_transports()->FlushAsyncInvokes();
3619
3620 // Data channels exist and open on both ends of the connection.
3621 ASSERT_NE(nullptr, caller()->data_channel());
3622 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3623 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3624 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3625
3626 // Close the data channel on the callee side, and wait for it to reach the
3627 // "closed" state on both sides.
3628 callee()->data_channel()->Close();
3629 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3630 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3631}
3632
3633TEST_P(PeerConnectionIntegrationTest,
3634 MediaTransportDataChannelConfigSentToOtherSide) {
3635 PeerConnectionInterface::RTCConfiguration rtc_config;
3636 rtc_config.use_media_transport_for_data_channels = true;
3637 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3638 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3639 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3640 loopback_media_transports()->second_factory()));
3641 ConnectFakeSignaling();
3642
3643 // Create a data channel with a non-default configuration and signal it to the
3644 // callee.
3645 webrtc::DataChannelInit init;
3646 init.id = 53;
3647 init.maxRetransmits = 52;
3648 caller()->CreateDataChannel("data-channel", &init);
3649 caller()->CreateAndSetAndSignalOffer();
3650 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3651
3652 // Ensure that the media transport is ready.
3653 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3654 loopback_media_transports()->FlushAsyncInvokes();
3655
3656 // Ensure that the data channel exists on the callee with the correct
3657 // configuration.
3658 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3659 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003660 // Since "negotiate" is false, the "id" parameter is ignored.
3661 EXPECT_NE(init.id, callee()->data_channel()->id());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003662 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3663 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3664 EXPECT_FALSE(callee()->data_channel()->negotiated());
3665}
3666
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003667TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgrade) {
3668 PeerConnectionInterface::RTCConfiguration rtc_config;
3669 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3670 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3671 rtc_config.use_media_transport = true;
3672 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3673 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3674 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3675 loopback_media_transports()->second_factory()));
3676 ConnectFakeSignaling();
3677
3678 // Do initial offer/answer with just a video track.
3679 caller()->AddVideoTrack();
3680 callee()->AddVideoTrack();
3681 caller()->CreateAndSetAndSignalOffer();
3682 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3683
3684 // Ensure that the media transport is ready.
3685 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3686 loopback_media_transports()->FlushAsyncInvokes();
3687
3688 // Now add an audio track and do another offer/answer.
3689 caller()->AddAudioTrack();
3690 callee()->AddAudioTrack();
3691 caller()->CreateAndSetAndSignalOffer();
3692 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3693
3694 // Ensure both audio and video frames are received end-to-end.
3695 MediaExpectations media_expectations;
3696 media_expectations.ExpectBidirectionalAudioAndVideo();
3697 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3698
3699 // The second offer should not have generated another media transport.
3700 // Media transport was kept alive, and was not recreated.
3701 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3702 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3703}
3704
3705TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgradeOnTheCallee) {
3706 PeerConnectionInterface::RTCConfiguration rtc_config;
3707 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3708 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3709 rtc_config.use_media_transport = true;
3710 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3711 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3712 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3713 loopback_media_transports()->second_factory()));
3714 ConnectFakeSignaling();
3715
3716 // Do initial offer/answer with just a video track.
3717 caller()->AddVideoTrack();
3718 callee()->AddVideoTrack();
3719 caller()->CreateAndSetAndSignalOffer();
3720 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3721
3722 // Ensure that the media transport is ready.
3723 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3724 loopback_media_transports()->FlushAsyncInvokes();
3725
3726 // Now add an audio track and do another offer/answer.
3727 caller()->AddAudioTrack();
3728 callee()->AddAudioTrack();
3729 callee()->CreateAndSetAndSignalOffer();
3730 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3731
3732 // Ensure both audio and video frames are received end-to-end.
3733 MediaExpectations media_expectations;
3734 media_expectations.ExpectBidirectionalAudioAndVideo();
3735 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3736
3737 // The second offer should not have generated another media transport.
3738 // Media transport was kept alive, and was not recreated.
3739 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3740 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3741}
3742
Niels Möllerc68d2822018-11-20 14:52:05 +01003743TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalAudio) {
3744 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003745 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3746 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Niels Möllerc68d2822018-11-20 14:52:05 +01003747 rtc_config.use_media_transport = true;
3748 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3749 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3750 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3751 loopback_media_transports()->second_factory()));
3752 ConnectFakeSignaling();
3753
3754 caller()->AddAudioTrack();
3755 callee()->AddAudioTrack();
3756 // Start offer/answer exchange and wait for it to complete.
3757 caller()->CreateAndSetAndSignalOffer();
3758 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3759
3760 // Ensure that the media transport is ready.
3761 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3762 loopback_media_transports()->FlushAsyncInvokes();
3763
3764 MediaExpectations media_expectations;
3765 media_expectations.ExpectBidirectionalAudio();
3766 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3767
3768 webrtc::MediaTransportPair::Stats first_stats =
3769 loopback_media_transports()->FirstStats();
3770 webrtc::MediaTransportPair::Stats second_stats =
3771 loopback_media_transports()->SecondStats();
3772
3773 EXPECT_GT(first_stats.received_audio_frames, 0);
3774 EXPECT_GE(second_stats.sent_audio_frames, first_stats.received_audio_frames);
3775
3776 EXPECT_GT(second_stats.received_audio_frames, 0);
3777 EXPECT_GE(first_stats.sent_audio_frames, second_stats.received_audio_frames);
3778}
3779
Niels Möller46879152019-01-07 15:54:47 +01003780TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalVideo) {
3781 PeerConnectionInterface::RTCConfiguration rtc_config;
3782 rtc_config.use_media_transport = true;
3783 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3784 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3785 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3786 loopback_media_transports()->second_factory()));
3787 ConnectFakeSignaling();
3788
3789 caller()->AddVideoTrack();
3790 callee()->AddVideoTrack();
3791 // Start offer/answer exchange and wait for it to complete.
3792 caller()->CreateAndSetAndSignalOffer();
3793 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3794
3795 // Ensure that the media transport is ready.
3796 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3797 loopback_media_transports()->FlushAsyncInvokes();
3798
3799 MediaExpectations media_expectations;
3800 media_expectations.ExpectBidirectionalVideo();
3801 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3802
3803 webrtc::MediaTransportPair::Stats first_stats =
3804 loopback_media_transports()->FirstStats();
3805 webrtc::MediaTransportPair::Stats second_stats =
3806 loopback_media_transports()->SecondStats();
3807
3808 EXPECT_GT(first_stats.received_video_frames, 0);
3809 EXPECT_GE(second_stats.sent_video_frames, first_stats.received_video_frames);
3810
3811 EXPECT_GT(second_stats.received_video_frames, 0);
3812 EXPECT_GE(first_stats.sent_video_frames, second_stats.received_video_frames);
3813}
3814
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003815TEST_P(PeerConnectionIntegrationTest,
3816 MediaTransportDataChannelUsesRtpBidirectionalVideo) {
3817 PeerConnectionInterface::RTCConfiguration rtc_config;
3818 rtc_config.use_media_transport = false;
3819 rtc_config.use_media_transport_for_data_channels = true;
3820 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3821 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3822 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3823 loopback_media_transports()->second_factory()));
3824 ConnectFakeSignaling();
3825
3826 caller()->AddVideoTrack();
3827 callee()->AddVideoTrack();
3828 // Start offer/answer exchange and wait for it to complete.
3829 caller()->CreateAndSetAndSignalOffer();
3830 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3831
3832 MediaExpectations media_expectations;
3833 media_expectations.ExpectBidirectionalVideo();
3834 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3835}
3836
deadbeef1dcb1642017-03-29 21:08:16 -07003837// Test that the ICE connection and gathering states eventually reach
3838// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003839TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003840 ASSERT_TRUE(CreatePeerConnectionWrappers());
3841 ConnectFakeSignaling();
3842 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003843 caller()->AddAudioVideoTracks();
3844 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003845 caller()->CreateAndSetAndSignalOffer();
3846 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3847 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3848 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3849 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3850 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3851 // After the best candidate pair is selected and all candidates are signaled,
3852 // the ICE connection state should reach "complete".
3853 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3854 // answerer/"callee" by default) only reaches "connected". When this is
3855 // fixed, this test should be updated.
3856 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3857 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00003858 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3859 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003860}
3861
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003862constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
3863 cricket::PORTALLOCATOR_DISABLE_RELAY |
3864 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003865
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003866// Use a mock resolver to resolve the hostname back to the original IP on both
3867// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003868TEST_P(PeerConnectionIntegrationTest,
3869 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003870 auto caller_resolver_factory =
3871 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3872 auto callee_resolver_factory =
3873 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3874 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
3875 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003876
3877 // This also verifies that the injected AsyncResolverFactory is used by
3878 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003879 EXPECT_CALL(*caller_resolver_factory, Create())
3880 .WillOnce(Return(&caller_async_resolver));
3881 webrtc::PeerConnectionDependencies caller_deps(nullptr);
3882 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
3883
3884 EXPECT_CALL(*callee_resolver_factory, Create())
3885 .WillOnce(Return(&callee_async_resolver));
3886 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3887 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
3888
3889 PeerConnectionInterface::RTCConfiguration config;
3890 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3891 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3892
3893 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3894 config, std::move(caller_deps), config, std::move(callee_deps)));
3895
3896 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
3897 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
3898
3899 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07003900 caller()->SetMdnsResponder(
3901 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
3902 callee()->SetMdnsResponder(
3903 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003904
3905 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003906
3907 ConnectFakeSignaling();
3908 caller()->AddAudioVideoTracks();
3909 callee()->AddAudioVideoTracks();
3910 caller()->CreateAndSetAndSignalOffer();
3911 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3912 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3913 caller()->ice_connection_state(), kDefaultTimeout);
3914 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3915 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08003916
3917 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3918 "WebRTC.PeerConnection.CandidatePairType_UDP",
3919 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003920}
3921
Steve Antonede9ca52017-10-16 13:04:27 -07003922// Test that firewalling the ICE connection causes the clients to identify the
3923// disconnected state and then removing the firewall causes them to reconnect.
3924class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003925 : public PeerConnectionIntegrationBaseTest,
3926 public ::testing::WithParamInterface<
3927 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003928 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003929 PeerConnectionIntegrationIceStatesTest()
3930 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3931 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003932 }
3933
3934 void StartStunServer(const SocketAddress& server_address) {
3935 stun_server_.reset(
3936 cricket::TestStunServer::Create(network_thread(), server_address));
3937 }
3938
3939 bool TestIPv6() {
3940 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3941 }
3942
3943 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003944 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
3945 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07003946 }
3947
3948 std::vector<SocketAddress> CallerAddresses() {
3949 std::vector<SocketAddress> addresses;
3950 addresses.push_back(SocketAddress("1.1.1.1", 0));
3951 if (TestIPv6()) {
3952 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3953 }
3954 return addresses;
3955 }
3956
3957 std::vector<SocketAddress> CalleeAddresses() {
3958 std::vector<SocketAddress> addresses;
3959 addresses.push_back(SocketAddress("2.2.2.2", 0));
3960 if (TestIPv6()) {
3961 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3962 }
3963 return addresses;
3964 }
3965
3966 void SetUpNetworkInterfaces() {
3967 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07003968 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
3969 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07003970
3971 // Add network addresses for test.
3972 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003973 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003974 }
3975 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003976 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003977 }
3978 }
3979
3980 private:
3981 uint32_t port_allocator_flags_;
3982 std::unique_ptr<cricket::TestStunServer> stun_server_;
3983};
3984
3985// Tests that the PeerConnection goes through all the ICE gathering/connection
3986// states over the duration of the call. This includes Disconnected and Failed
3987// states, induced by putting a firewall between the peers and waiting for them
3988// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003989TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01003990 rtc::ScopedFakeClock fake_clock;
3991 // Some things use a time of "0" as a special value, so we need to start out
3992 // the fake clock at a nonzero time.
3993 fake_clock.AdvanceTime(TimeDelta::seconds(1));
Steve Antonede9ca52017-10-16 13:04:27 -07003994
3995 const SocketAddress kStunServerAddress =
3996 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3997 StartStunServer(kStunServerAddress);
3998
3999 PeerConnectionInterface::RTCConfiguration config;
4000 PeerConnectionInterface::IceServer ice_stun_server;
4001 ice_stun_server.urls.push_back(
4002 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
4003 kStunServerAddress.PortAsString());
4004 config.servers.push_back(ice_stun_server);
4005
4006 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4007 ConnectFakeSignaling();
4008 SetPortAllocatorFlags();
4009 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004010 caller()->AddAudioVideoTracks();
4011 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004012
4013 // Initial state before anything happens.
4014 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
4015 caller()->ice_gathering_state());
4016 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4017 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004018 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
4019 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004020
4021 // Start the call by creating the offer, setting it as the local description,
4022 // then sending it to the peer who will respond with an answer. This happens
4023 // asynchronously so that we can watch the states as it runs in the
4024 // background.
4025 caller()->CreateAndSetAndSignalOffer();
4026
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004027 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
4028 caller()->ice_connection_state());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004029 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olsson7a6739e2019-01-15 16:31:55 +01004030 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07004031
4032 // Verify that the observer was notified of the intermediate transitions.
4033 EXPECT_THAT(caller()->ice_connection_state_history(),
4034 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4035 PeerConnectionInterface::kIceConnectionConnected,
4036 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004037 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
4038 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
4039 PeerConnectionInterface::kIceConnectionConnected,
4040 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02004041 EXPECT_THAT(
4042 caller()->peer_connection_state_history(),
4043 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02004044 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07004045 EXPECT_THAT(caller()->ice_gathering_state_history(),
4046 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4047 PeerConnectionInterface::kIceGatheringComplete));
4048
4049 // Block connections to/from the caller and wait for ICE to become
4050 // disconnected.
4051 for (const auto& caller_address : CallerAddresses()) {
4052 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4053 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004054 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004055 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4056 caller()->ice_connection_state(), kDefaultTimeout,
4057 fake_clock);
4058 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4059 caller()->standardized_ice_connection_state(),
4060 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004061
4062 // Let ICE re-establish by removing the firewall rules.
4063 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004064 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004065 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4066 caller()->ice_connection_state(), kDefaultTimeout,
4067 fake_clock);
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004068 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004069 caller()->standardized_ice_connection_state(),
4070 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004071
4072 // According to RFC7675, if there is no response within 30 seconds then the
4073 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004074 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004075 constexpr int kConsentTimeout = 30000;
4076 for (const auto& caller_address : CallerAddresses()) {
4077 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4078 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004079 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004080 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4081 caller()->ice_connection_state(), kConsentTimeout,
4082 fake_clock);
4083 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4084 caller()->standardized_ice_connection_state(),
4085 kConsentTimeout, fake_clock);
4086
4087 // We need to manually close the peerconnections before the fake clock goes
4088 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4089 // return to using non-faked time.
4090 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4091 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
4092}
4093
4094// Tests that if the connection doesn't get set up properly we eventually reach
4095// the "failed" iceConnectionState.
4096TEST_P(PeerConnectionIntegrationIceStatesTest, IceStateSetupFailure) {
4097 rtc::ScopedFakeClock fake_clock;
4098 // Some things use a time of "0" as a special value, so we need to start out
4099 // the fake clock at a nonzero time.
4100 fake_clock.AdvanceTime(TimeDelta::seconds(1));
4101
4102 // Block connections to/from the caller and wait for ICE to become
4103 // disconnected.
4104 for (const auto& caller_address : CallerAddresses()) {
4105 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4106 }
4107
4108 ASSERT_TRUE(CreatePeerConnectionWrappers());
4109 ConnectFakeSignaling();
4110 SetPortAllocatorFlags();
4111 SetUpNetworkInterfaces();
4112 caller()->AddAudioVideoTracks();
4113 caller()->CreateAndSetAndSignalOffer();
4114
4115 // According to RFC7675, if there is no response within 30 seconds then the
4116 // peer should consider the other side to have rejected the connection. This
4117 // is signaled by the state transitioning to "failed".
4118 constexpr int kConsentTimeout = 30000;
4119 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4120 caller()->standardized_ice_connection_state(),
4121 kConsentTimeout, fake_clock);
4122
4123 // We need to manually close the peerconnections before the fake clock goes
4124 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4125 // return to using non-faked time.
4126 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4127 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
Steve Antonede9ca52017-10-16 13:04:27 -07004128}
4129
4130// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4131// and that the statistics in the metric observers are updated correctly.
4132TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4133 ASSERT_TRUE(CreatePeerConnectionWrappers());
4134 ConnectFakeSignaling();
4135 SetPortAllocatorFlags();
4136 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004137 caller()->AddAudioVideoTracks();
4138 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004139 caller()->CreateAndSetAndSignalOffer();
4140
4141 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4142
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004143 // TODO(bugs.webrtc.org/9456): Fix it.
4144 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4145 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4146 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4147 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004148 if (TestIPv6()) {
4149 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4150 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004151 EXPECT_EQ(0, num_best_ipv4);
4152 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004153 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004154 EXPECT_EQ(1, num_best_ipv4);
4155 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004156 }
4157
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004158 EXPECT_EQ(0, webrtc::metrics::NumEvents(
4159 "WebRTC.PeerConnection.CandidatePairType_UDP",
4160 webrtc::kIceCandidatePairHostHost));
4161 EXPECT_EQ(1, webrtc::metrics::NumEvents(
4162 "WebRTC.PeerConnection.CandidatePairType_UDP",
4163 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004164}
4165
4166constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4167 cricket::PORTALLOCATOR_DISABLE_STUN |
4168 cricket::PORTALLOCATOR_DISABLE_RELAY;
4169constexpr uint32_t kFlagsIPv6NoStun =
4170 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4171 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4172constexpr uint32_t kFlagsIPv4Stun =
4173 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4174
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004175INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004176 PeerConnectionIntegrationTest,
4177 PeerConnectionIntegrationIceStatesTest,
4178 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4179 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4180 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4181 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004182
deadbeef1dcb1642017-03-29 21:08:16 -07004183// This test sets up a call between two parties with audio and video.
4184// During the call, the caller restarts ICE and the test verifies that
4185// new ICE candidates are generated and audio and video still can flow, and the
4186// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004187TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004188 ASSERT_TRUE(CreatePeerConnectionWrappers());
4189 ConnectFakeSignaling();
4190 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004191 caller()->AddAudioVideoTracks();
4192 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004193 caller()->CreateAndSetAndSignalOffer();
4194 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4195 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4196 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004197 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4198 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004199
4200 // To verify that the ICE restart actually occurs, get
4201 // ufrag/password/candidates before and after restart.
4202 // Create an SDP string of the first audio candidate for both clients.
4203 const webrtc::IceCandidateCollection* audio_candidates_caller =
4204 caller()->pc()->local_description()->candidates(0);
4205 const webrtc::IceCandidateCollection* audio_candidates_callee =
4206 callee()->pc()->local_description()->candidates(0);
4207 ASSERT_GT(audio_candidates_caller->count(), 0u);
4208 ASSERT_GT(audio_candidates_callee->count(), 0u);
4209 std::string caller_candidate_pre_restart;
4210 ASSERT_TRUE(
4211 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4212 std::string callee_candidate_pre_restart;
4213 ASSERT_TRUE(
4214 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4215 const cricket::SessionDescription* desc =
4216 caller()->pc()->local_description()->description();
4217 std::string caller_ufrag_pre_restart =
4218 desc->transport_infos()[0].description.ice_ufrag;
4219 desc = callee()->pc()->local_description()->description();
4220 std::string callee_ufrag_pre_restart =
4221 desc->transport_infos()[0].description.ice_ufrag;
4222
Alex Drake00c7ecf2019-08-06 10:54:47 -07004223 EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004224 // Have the caller initiate an ICE restart.
4225 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4226 caller()->CreateAndSetAndSignalOffer();
4227 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4228 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4229 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004230 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004231 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4232
4233 // Grab the ufrags/candidates again.
4234 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4235 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4236 ASSERT_GT(audio_candidates_caller->count(), 0u);
4237 ASSERT_GT(audio_candidates_callee->count(), 0u);
4238 std::string caller_candidate_post_restart;
4239 ASSERT_TRUE(
4240 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4241 std::string callee_candidate_post_restart;
4242 ASSERT_TRUE(
4243 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4244 desc = caller()->pc()->local_description()->description();
4245 std::string caller_ufrag_post_restart =
4246 desc->transport_infos()[0].description.ice_ufrag;
4247 desc = callee()->pc()->local_description()->description();
4248 std::string callee_ufrag_post_restart =
4249 desc->transport_infos()[0].description.ice_ufrag;
4250 // Sanity check that an ICE restart was actually negotiated in SDP.
4251 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4252 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4253 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4254 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
Alex Drake00c7ecf2019-08-06 10:54:47 -07004255 EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
deadbeef1dcb1642017-03-29 21:08:16 -07004256
4257 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004258 MediaExpectations media_expectations;
4259 media_expectations.ExpectBidirectionalAudioAndVideo();
4260 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004261}
4262
4263// Verify that audio/video can be received end-to-end when ICE renomination is
4264// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004265TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004266 PeerConnectionInterface::RTCConfiguration config;
4267 config.enable_ice_renomination = true;
4268 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4269 ConnectFakeSignaling();
4270 // Do normal offer/answer and wait for some frames to be received in each
4271 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004272 caller()->AddAudioVideoTracks();
4273 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004274 caller()->CreateAndSetAndSignalOffer();
4275 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4276 // Sanity check that ICE renomination was actually negotiated.
4277 const cricket::SessionDescription* desc =
4278 caller()->pc()->local_description()->description();
4279 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004280 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004281 }
4282 desc = callee()->pc()->local_description()->description();
4283 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004284 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004285 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004286 MediaExpectations media_expectations;
4287 media_expectations.ExpectBidirectionalAudioAndVideo();
4288 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004289}
4290
Steve Anton6f25b092017-10-23 09:39:20 -07004291// With a max bundle policy and RTCP muxing, adding a new media description to
4292// the connection should not affect ICE at all because the new media will use
4293// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004294TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004295 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004296 PeerConnectionInterface::RTCConfiguration config;
4297 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4298 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4299 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4300 config, PeerConnectionInterface::RTCConfiguration()));
4301 ConnectFakeSignaling();
4302
Steve Anton15324772018-01-16 10:26:49 -08004303 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004304 caller()->CreateAndSetAndSignalOffer();
4305 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004306 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4307 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004308
4309 caller()->clear_ice_connection_state_history();
4310
Steve Anton15324772018-01-16 10:26:49 -08004311 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004312 caller()->CreateAndSetAndSignalOffer();
4313 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4314
4315 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4316}
4317
deadbeef1dcb1642017-03-29 21:08:16 -07004318// This test sets up a call between two parties with audio and video. It then
4319// renegotiates setting the video m-line to "port 0", then later renegotiates
4320// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004321TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004322 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4323 ASSERT_TRUE(CreatePeerConnectionWrappers());
4324 ConnectFakeSignaling();
4325
4326 // Do initial negotiation, only sending media from the caller. Will result in
4327 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004328 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004329 caller()->CreateAndSetAndSignalOffer();
4330 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4331
4332 // Negotiate again, disabling the video "m=" section (the callee will set the
4333 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004334 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4335 PeerConnectionInterface::RTCOfferAnswerOptions options;
4336 options.offer_to_receive_video = 0;
4337 callee()->SetOfferAnswerOptions(options);
4338 } else {
4339 callee()->SetRemoteOfferHandler([this] {
4340 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4341 });
4342 }
deadbeef1dcb1642017-03-29 21:08:16 -07004343 caller()->CreateAndSetAndSignalOffer();
4344 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4345 // Sanity check that video "m=" section was actually rejected.
4346 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4347 callee()->pc()->local_description()->description());
4348 ASSERT_NE(nullptr, answer_video_content);
4349 ASSERT_TRUE(answer_video_content->rejected);
4350
4351 // Enable video and do negotiation again, making sure video is received
4352 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004353 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4354 PeerConnectionInterface::RTCOfferAnswerOptions options;
4355 options.offer_to_receive_video = 1;
4356 callee()->SetOfferAnswerOptions(options);
4357 } else {
4358 // The caller's transceiver is stopped, so we need to add another track.
4359 auto caller_transceiver =
4360 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4361 EXPECT_TRUE(caller_transceiver->stopped());
4362 caller()->AddVideoTrack();
4363 }
4364 callee()->AddVideoTrack();
4365 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004366 caller()->CreateAndSetAndSignalOffer();
4367 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004368
deadbeef1dcb1642017-03-29 21:08:16 -07004369 // Verify the caller receives frames from the newly added stream, and the
4370 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004371 MediaExpectations media_expectations;
4372 media_expectations.CalleeExpectsSomeAudio();
4373 media_expectations.ExpectBidirectionalVideo();
4374 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004375}
4376
deadbeef1dcb1642017-03-29 21:08:16 -07004377// This tests that if we negotiate after calling CreateSender but before we
4378// have a track, then set a track later, frames from the newly-set track are
4379// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004380TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004381 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4382 ASSERT_TRUE(CreatePeerConnectionWrappers());
4383 ConnectFakeSignaling();
4384 auto caller_audio_sender =
4385 caller()->pc()->CreateSender("audio", "caller_stream");
4386 auto caller_video_sender =
4387 caller()->pc()->CreateSender("video", "caller_stream");
4388 auto callee_audio_sender =
4389 callee()->pc()->CreateSender("audio", "callee_stream");
4390 auto callee_video_sender =
4391 callee()->pc()->CreateSender("video", "callee_stream");
4392 caller()->CreateAndSetAndSignalOffer();
4393 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4394 // Wait for ICE to complete, without any tracks being set.
4395 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4396 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4397 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4398 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4399 // Now set the tracks, and expect frames to immediately start flowing.
4400 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4401 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4402 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4403 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004404 MediaExpectations media_expectations;
4405 media_expectations.ExpectBidirectionalAudioAndVideo();
4406 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4407}
4408
4409// This tests that if we negotiate after calling AddTransceiver but before we
4410// have a track, then set a track later, frames from the newly-set tracks are
4411// received end-to-end.
4412TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4413 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4414 ASSERT_TRUE(CreatePeerConnectionWrappers());
4415 ConnectFakeSignaling();
4416 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4417 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4418 auto caller_audio_sender = audio_result.MoveValue()->sender();
4419 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4420 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4421 auto caller_video_sender = video_result.MoveValue()->sender();
4422 callee()->SetRemoteOfferHandler([this] {
4423 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4424 callee()->pc()->GetTransceivers()[0]->SetDirection(
4425 RtpTransceiverDirection::kSendRecv);
4426 callee()->pc()->GetTransceivers()[1]->SetDirection(
4427 RtpTransceiverDirection::kSendRecv);
4428 });
4429 caller()->CreateAndSetAndSignalOffer();
4430 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4431 // Wait for ICE to complete, without any tracks being set.
4432 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4433 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4434 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4435 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4436 // Now set the tracks, and expect frames to immediately start flowing.
4437 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4438 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4439 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4440 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4441 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4442 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4443 MediaExpectations media_expectations;
4444 media_expectations.ExpectBidirectionalAudioAndVideo();
4445 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004446}
4447
4448// This test verifies that a remote video track can be added via AddStream,
4449// and sent end-to-end. For this particular test, it's simply echoed back
4450// from the caller to the callee, rather than being forwarded to a third
4451// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004452TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004453 ASSERT_TRUE(CreatePeerConnectionWrappers());
4454 ConnectFakeSignaling();
4455 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004456 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004457 caller()->CreateAndSetAndSignalOffer();
4458 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004459 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004460
4461 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4462 // time).
4463 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4464 callee()->CreateAndSetAndSignalOffer();
4465 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4466
Seth Hampson2f0d7022018-02-20 11:54:42 -08004467 MediaExpectations media_expectations;
4468 media_expectations.ExpectBidirectionalVideo();
4469 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004470}
4471
4472// Test that we achieve the expected end-to-end connection time, using a
4473// fake clock and simulated latency on the media and signaling paths.
4474// We use a TURN<->TURN connection because this is usually the quickest to
4475// set up initially, especially when we're confident the connection will work
4476// and can start sending media before we get a STUN response.
4477//
4478// With various optimizations enabled, here are the network delays we expect to
4479// be on the critical path:
4480// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4481// signaling answer (with DTLS fingerprint).
4482// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4483// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4484// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004485TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004486 rtc::ScopedFakeClock fake_clock;
4487 // Some things use a time of "0" as a special value, so we need to start out
4488 // the fake clock at a nonzero time.
4489 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02004490 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07004491
4492 static constexpr int media_hop_delay_ms = 50;
4493 static constexpr int signaling_trip_delay_ms = 500;
4494 // For explanation of these values, see comment above.
4495 static constexpr int required_media_hops = 9;
4496 static constexpr int required_signaling_trips = 2;
4497 // For internal delays (such as posting an event asychronously).
4498 static constexpr int allowed_internal_delay_ms = 20;
4499 static constexpr int total_connection_time_ms =
4500 media_hop_delay_ms * required_media_hops +
4501 signaling_trip_delay_ms * required_signaling_trips +
4502 allowed_internal_delay_ms;
4503
4504 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4505 3478};
4506 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4507 0};
4508 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4509 3478};
4510 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4511 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004512 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4513 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004514
Seth Hampsonaed71642018-06-11 07:41:32 -07004515 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4516 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004517 // Bypass permission check on received packets so media can be sent before
4518 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004519 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4520 turn_server_1->set_enable_permission_checks(false);
4521 });
4522 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4523 turn_server_2->set_enable_permission_checks(false);
4524 });
deadbeef1dcb1642017-03-29 21:08:16 -07004525
4526 PeerConnectionInterface::RTCConfiguration client_1_config;
4527 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4528 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4529 ice_server_1.username = "test";
4530 ice_server_1.password = "test";
4531 client_1_config.servers.push_back(ice_server_1);
4532 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4533 client_1_config.presume_writable_when_fully_relayed = true;
4534
4535 PeerConnectionInterface::RTCConfiguration client_2_config;
4536 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4537 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4538 ice_server_2.username = "test";
4539 ice_server_2.password = "test";
4540 client_2_config.servers.push_back(ice_server_2);
4541 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4542 client_2_config.presume_writable_when_fully_relayed = true;
4543
4544 ASSERT_TRUE(
4545 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4546 // Set up the simulated delays.
4547 SetSignalingDelayMs(signaling_trip_delay_ms);
4548 ConnectFakeSignaling();
4549 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4550 virtual_socket_server()->UpdateDelayDistribution();
4551
4552 // Set "offer to receive audio/video" without adding any tracks, so we just
4553 // set up ICE/DTLS with no media.
4554 PeerConnectionInterface::RTCOfferAnswerOptions options;
4555 options.offer_to_receive_audio = 1;
4556 options.offer_to_receive_video = 1;
4557 caller()->SetOfferAnswerOptions(options);
4558 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004559 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4560 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004561 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4562 // If this is not done a DCHECK can be hit in ports.cc, because a large
4563 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07004564 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07004565}
4566
Jonas Orelandbdcee282017-10-10 14:01:40 +02004567// Verify that a TurnCustomizer passed in through RTCConfiguration
4568// is actually used by the underlying TURN candidate pair.
4569// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004570TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004571 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4572 3478};
4573 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4574 0};
4575 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4576 3478};
4577 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4578 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004579 CreateTurnServer(turn_server_1_internal_address,
4580 turn_server_1_external_address);
4581 CreateTurnServer(turn_server_2_internal_address,
4582 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004583
4584 PeerConnectionInterface::RTCConfiguration client_1_config;
4585 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4586 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4587 ice_server_1.username = "test";
4588 ice_server_1.password = "test";
4589 client_1_config.servers.push_back(ice_server_1);
4590 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004591 auto* customizer1 = CreateTurnCustomizer();
4592 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004593
4594 PeerConnectionInterface::RTCConfiguration client_2_config;
4595 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4596 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4597 ice_server_2.username = "test";
4598 ice_server_2.password = "test";
4599 client_2_config.servers.push_back(ice_server_2);
4600 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004601 auto* customizer2 = CreateTurnCustomizer();
4602 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004603
4604 ASSERT_TRUE(
4605 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4606 ConnectFakeSignaling();
4607
4608 // Set "offer to receive audio/video" without adding any tracks, so we just
4609 // set up ICE/DTLS with no media.
4610 PeerConnectionInterface::RTCOfferAnswerOptions options;
4611 options.offer_to_receive_audio = 1;
4612 options.offer_to_receive_video = 1;
4613 caller()->SetOfferAnswerOptions(options);
4614 caller()->CreateAndSetAndSignalOffer();
4615 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4616
Seth Hampsonaed71642018-06-11 07:41:32 -07004617 ExpectTurnCustomizerCountersIncremented(customizer1);
4618 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004619}
4620
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004621// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4622// send media between the caller and the callee.
4623TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4624 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4625 3478};
4626 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4627
4628 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004629 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4630 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004631
4632 webrtc::PeerConnectionInterface::IceServer ice_server;
4633 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4634 ice_server.username = "test";
4635 ice_server.password = "test";
4636
4637 PeerConnectionInterface::RTCConfiguration client_1_config;
4638 client_1_config.servers.push_back(ice_server);
4639 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4640
4641 PeerConnectionInterface::RTCConfiguration client_2_config;
4642 client_2_config.servers.push_back(ice_server);
4643 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4644
4645 ASSERT_TRUE(
4646 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4647
4648 // Do normal offer/answer and wait for ICE to complete.
4649 ConnectFakeSignaling();
4650 caller()->AddAudioVideoTracks();
4651 callee()->AddAudioVideoTracks();
4652 caller()->CreateAndSetAndSignalOffer();
4653 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4654 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4655 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4656
4657 MediaExpectations media_expectations;
4658 media_expectations.ExpectBidirectionalAudioAndVideo();
4659 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4660}
4661
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004662// Verify that a SSLCertificateVerifier passed in through
4663// PeerConnectionDependencies is actually used by the underlying SSL
4664// implementation to determine whether a certificate presented by the TURN
4665// server is accepted by the client. Note that openssladapter_unittest.cc
4666// contains more detailed, lower-level tests.
4667TEST_P(PeerConnectionIntegrationTest,
4668 SSLCertificateVerifierUsedForTurnConnections) {
4669 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4670 3478};
4671 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4672
4673 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4674 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004675 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4676 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004677
4678 webrtc::PeerConnectionInterface::IceServer ice_server;
4679 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4680 ice_server.username = "test";
4681 ice_server.password = "test";
4682
4683 PeerConnectionInterface::RTCConfiguration client_1_config;
4684 client_1_config.servers.push_back(ice_server);
4685 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4686
4687 PeerConnectionInterface::RTCConfiguration client_2_config;
4688 client_2_config.servers.push_back(ice_server);
4689 // Setting the type to kRelay forces the connection to go through a TURN
4690 // server.
4691 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4692
4693 // Get a copy to the pointer so we can verify calls later.
4694 rtc::TestCertificateVerifier* client_1_cert_verifier =
4695 new rtc::TestCertificateVerifier();
4696 client_1_cert_verifier->verify_certificate_ = true;
4697 rtc::TestCertificateVerifier* client_2_cert_verifier =
4698 new rtc::TestCertificateVerifier();
4699 client_2_cert_verifier->verify_certificate_ = true;
4700
4701 // Create the dependencies with the test certificate verifier.
4702 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4703 client_1_deps.tls_cert_verifier =
4704 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4705 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4706 client_2_deps.tls_cert_verifier =
4707 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4708
4709 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4710 client_1_config, std::move(client_1_deps), client_2_config,
4711 std::move(client_2_deps)));
4712 ConnectFakeSignaling();
4713
4714 // Set "offer to receive audio/video" without adding any tracks, so we just
4715 // set up ICE/DTLS with no media.
4716 PeerConnectionInterface::RTCOfferAnswerOptions options;
4717 options.offer_to_receive_audio = 1;
4718 options.offer_to_receive_video = 1;
4719 caller()->SetOfferAnswerOptions(options);
4720 caller()->CreateAndSetAndSignalOffer();
4721 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4722
4723 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4724 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004725}
4726
4727TEST_P(PeerConnectionIntegrationTest,
4728 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4729 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4730 3478};
4731 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4732
4733 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4734 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004735 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4736 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004737
4738 webrtc::PeerConnectionInterface::IceServer ice_server;
4739 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4740 ice_server.username = "test";
4741 ice_server.password = "test";
4742
4743 PeerConnectionInterface::RTCConfiguration client_1_config;
4744 client_1_config.servers.push_back(ice_server);
4745 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4746
4747 PeerConnectionInterface::RTCConfiguration client_2_config;
4748 client_2_config.servers.push_back(ice_server);
4749 // Setting the type to kRelay forces the connection to go through a TURN
4750 // server.
4751 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4752
4753 // Get a copy to the pointer so we can verify calls later.
4754 rtc::TestCertificateVerifier* client_1_cert_verifier =
4755 new rtc::TestCertificateVerifier();
4756 client_1_cert_verifier->verify_certificate_ = false;
4757 rtc::TestCertificateVerifier* client_2_cert_verifier =
4758 new rtc::TestCertificateVerifier();
4759 client_2_cert_verifier->verify_certificate_ = false;
4760
4761 // Create the dependencies with the test certificate verifier.
4762 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4763 client_1_deps.tls_cert_verifier =
4764 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4765 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4766 client_2_deps.tls_cert_verifier =
4767 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4768
4769 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4770 client_1_config, std::move(client_1_deps), client_2_config,
4771 std::move(client_2_deps)));
4772 ConnectFakeSignaling();
4773
4774 // Set "offer to receive audio/video" without adding any tracks, so we just
4775 // set up ICE/DTLS with no media.
4776 PeerConnectionInterface::RTCOfferAnswerOptions options;
4777 options.offer_to_receive_audio = 1;
4778 options.offer_to_receive_video = 1;
4779 caller()->SetOfferAnswerOptions(options);
4780 caller()->CreateAndSetAndSignalOffer();
4781 bool wait_res = true;
4782 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4783 // properly, should be able to just wait for a state of "failed" instead of
4784 // waiting a fixed 10 seconds.
4785 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4786 ASSERT_FALSE(wait_res);
4787
4788 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4789 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004790}
4791
deadbeefc964d0b2017-04-03 10:03:35 -07004792// Test that audio and video flow end-to-end when codec names don't use the
4793// expected casing, given that they're supposed to be case insensitive. To test
4794// this, all but one codec is removed from each media description, and its
4795// casing is changed.
4796//
4797// In the past, this has regressed and caused crashes/black video, due to the
4798// fact that code at some layers was doing case-insensitive comparisons and
4799// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004800TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004801 ASSERT_TRUE(CreatePeerConnectionWrappers());
4802 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004803 caller()->AddAudioVideoTracks();
4804 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004805
4806 // Remove all but one audio/video codec (opus and VP8), and change the
4807 // casing of the caller's generated offer.
4808 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4809 cricket::AudioContentDescription* audio =
4810 GetFirstAudioContentDescription(description);
4811 ASSERT_NE(nullptr, audio);
4812 auto audio_codecs = audio->codecs();
4813 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4814 [](const cricket::AudioCodec& codec) {
4815 return codec.name != "opus";
4816 }),
4817 audio_codecs.end());
4818 ASSERT_EQ(1u, audio_codecs.size());
4819 audio_codecs[0].name = "OpUs";
4820 audio->set_codecs(audio_codecs);
4821
4822 cricket::VideoContentDescription* video =
4823 GetFirstVideoContentDescription(description);
4824 ASSERT_NE(nullptr, video);
4825 auto video_codecs = video->codecs();
4826 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4827 [](const cricket::VideoCodec& codec) {
4828 return codec.name != "VP8";
4829 }),
4830 video_codecs.end());
4831 ASSERT_EQ(1u, video_codecs.size());
4832 video_codecs[0].name = "vP8";
4833 video->set_codecs(video_codecs);
4834 });
4835
4836 caller()->CreateAndSetAndSignalOffer();
4837 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4838
4839 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004840 MediaExpectations media_expectations;
4841 media_expectations.ExpectBidirectionalAudioAndVideo();
4842 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004843}
4844
Jonas Oreland49ac5952018-09-26 16:04:32 +02004845TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004846 ASSERT_TRUE(CreatePeerConnectionWrappers());
4847 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004848 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004849 caller()->CreateAndSetAndSignalOffer();
4850 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004851 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004852 MediaExpectations media_expectations;
4853 media_expectations.CalleeExpectsSomeAudio(1);
4854 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004855 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004856 auto receiver = callee()->pc()->GetReceivers()[0];
4857 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004858 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004859 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4860 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004861 sources[0].source_id());
4862 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4863}
4864
4865TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4866 ASSERT_TRUE(CreatePeerConnectionWrappers());
4867 ConnectFakeSignaling();
4868 caller()->AddVideoTrack();
4869 caller()->CreateAndSetAndSignalOffer();
4870 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4871 // Wait for one video frame to be received by the callee.
4872 MediaExpectations media_expectations;
4873 media_expectations.CalleeExpectsSomeVideo(1);
4874 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4875 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4876 auto receiver = callee()->pc()->GetReceivers()[0];
4877 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4878 auto sources = receiver->GetSources();
4879 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
Yves Gereyf781bb52019-07-23 19:15:39 +02004880 ASSERT_GT(sources.size(), 0u);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004881 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4882 sources[0].source_id());
4883 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004884}
4885
deadbeef2f425aa2017-04-14 10:41:32 -07004886// Test that if a track is removed and added again with a different stream ID,
4887// the new stream ID is successfully communicated in SDP and media continues to
4888// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004889// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4890// it will not reuse a transceiver that has already been sending. After creating
4891// a new transceiver it tries to create an offer with two senders of the same
4892// track ids and it fails.
4893TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004894 ASSERT_TRUE(CreatePeerConnectionWrappers());
4895 ConnectFakeSignaling();
4896
deadbeef2f425aa2017-04-14 10:41:32 -07004897 // Add track using stream 1, do offer/answer.
4898 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4899 caller()->CreateLocalAudioTrack();
4900 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004901 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004902 caller()->CreateAndSetAndSignalOffer();
4903 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004904 {
4905 MediaExpectations media_expectations;
4906 media_expectations.CalleeExpectsSomeAudio(1);
4907 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4908 }
deadbeef2f425aa2017-04-14 10:41:32 -07004909 // Remove the sender, and create a new one with the new stream.
4910 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004911 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004912 caller()->CreateAndSetAndSignalOffer();
4913 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4914 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004915 {
4916 MediaExpectations media_expectations;
4917 media_expectations.CalleeExpectsSomeAudio();
4918 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4919 }
deadbeef2f425aa2017-04-14 10:41:32 -07004920}
4921
Seth Hampson2f0d7022018-02-20 11:54:42 -08004922TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004923 ASSERT_TRUE(CreatePeerConnectionWrappers());
4924 ConnectFakeSignaling();
4925
Karl Wiberg918f50c2018-07-05 11:40:33 +02004926 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02004927 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
4928 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02004929 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004930 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4931 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004932
Steve Anton15324772018-01-16 10:26:49 -08004933 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004934 caller()->CreateAndSetAndSignalOffer();
4935 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4936}
4937
Steve Antonede9ca52017-10-16 13:04:27 -07004938// Test that if candidates are only signaled by applying full session
4939// descriptions (instead of using AddIceCandidate), the peers can connect to
4940// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004941TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004942 ASSERT_TRUE(CreatePeerConnectionWrappers());
4943 // Each side will signal the session descriptions but not candidates.
4944 ConnectFakeSignalingForSdpOnly();
4945
4946 // Add audio video track and exchange the initial offer/answer with media
4947 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004948 caller()->AddAudioVideoTracks();
4949 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004950 caller()->CreateAndSetAndSignalOffer();
4951
4952 // Wait for all candidates to be gathered on both the caller and callee.
4953 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4954 caller()->ice_gathering_state(), kDefaultTimeout);
4955 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4956 callee()->ice_gathering_state(), kDefaultTimeout);
4957
4958 // The candidates will now be included in the session description, so
4959 // signaling them will start the ICE connection.
4960 caller()->CreateAndSetAndSignalOffer();
4961 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4962
4963 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004964 MediaExpectations media_expectations;
4965 media_expectations.ExpectBidirectionalAudioAndVideo();
4966 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004967}
4968
henrika5f6bf242017-11-01 11:06:56 +01004969// Test that SetAudioPlayout can be used to disable audio playout from the
4970// start, then later enable it. This may be useful, for example, if the caller
4971// needs to play a local ringtone until some event occurs, after which it
4972// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004973TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004974 ASSERT_TRUE(CreatePeerConnectionWrappers());
4975 ConnectFakeSignaling();
4976
4977 // Set up audio-only call where audio playout is disabled on caller's side.
4978 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004979 caller()->AddAudioTrack();
4980 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004981 caller()->CreateAndSetAndSignalOffer();
4982 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4983
4984 // Pump messages for a second.
4985 WAIT(false, 1000);
4986 // Since audio playout is disabled, the caller shouldn't have received
4987 // anything (at the playout level, at least).
4988 EXPECT_EQ(0, caller()->audio_frames_received());
4989 // As a sanity check, make sure the callee (for which playout isn't disabled)
4990 // did still see frames on its audio level.
4991 ASSERT_GT(callee()->audio_frames_received(), 0);
4992
4993 // Enable playout again, and ensure audio starts flowing.
4994 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004995 MediaExpectations media_expectations;
4996 media_expectations.ExpectBidirectionalAudio();
4997 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004998}
4999
5000double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
5001 auto report = pc->NewGetStats();
5002 auto track_stats_list =
5003 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
5004 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
5005 for (const auto* track_stats : track_stats_list) {
5006 if (track_stats->remote_source.is_defined() &&
5007 *track_stats->remote_source) {
5008 remote_track_stats = track_stats;
5009 break;
5010 }
5011 }
5012
5013 if (!remote_track_stats->total_audio_energy.is_defined()) {
5014 return 0.0;
5015 }
5016 return *remote_track_stats->total_audio_energy;
5017}
5018
5019// Test that if audio playout is disabled via the SetAudioPlayout() method, then
5020// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005021TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01005022 DisableAudioPlayoutStillGeneratesAudioStats) {
5023 ASSERT_TRUE(CreatePeerConnectionWrappers());
5024 ConnectFakeSignaling();
5025
5026 // Set up audio-only call where playout is disabled but audio-processing is
5027 // still active.
Steve Anton15324772018-01-16 10:26:49 -08005028 caller()->AddAudioTrack();
5029 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01005030 caller()->pc()->SetAudioPlayout(false);
5031
5032 caller()->CreateAndSetAndSignalOffer();
5033 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5034
5035 // Wait for the callee to receive audio stats.
5036 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
5037}
5038
henrika4f167df2017-11-01 14:45:55 +01005039// Test that SetAudioRecording can be used to disable audio recording from the
5040// start, then later enable it. This may be useful, for example, if the caller
5041// wants to ensure that no audio resources are active before a certain state
5042// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08005043TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01005044 ASSERT_TRUE(CreatePeerConnectionWrappers());
5045 ConnectFakeSignaling();
5046
5047 // Set up audio-only call where audio recording is disabled on caller's side.
5048 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005049 caller()->AddAudioTrack();
5050 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005051 caller()->CreateAndSetAndSignalOffer();
5052 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5053
5054 // Pump messages for a second.
5055 WAIT(false, 1000);
5056 // Since caller has disabled audio recording, the callee shouldn't have
5057 // received anything.
5058 EXPECT_EQ(0, callee()->audio_frames_received());
5059 // As a sanity check, make sure the caller did still see frames on its
5060 // audio level since audio recording is enabled on the calle side.
5061 ASSERT_GT(caller()->audio_frames_received(), 0);
5062
5063 // Enable audio recording again, and ensure audio starts flowing.
5064 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005065 MediaExpectations media_expectations;
5066 media_expectations.ExpectBidirectionalAudio();
5067 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005068}
5069
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005070// Test that after closing PeerConnections, they stop sending any packets (ICE,
5071// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005072TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005073 // Set up audio/video/data, wait for some frames to be received.
5074 ASSERT_TRUE(CreatePeerConnectionWrappers());
5075 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005076 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005077#ifdef HAVE_SCTP
5078 caller()->CreateDataChannel();
5079#endif
5080 caller()->CreateAndSetAndSignalOffer();
5081 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005082 MediaExpectations media_expectations;
5083 media_expectations.CalleeExpectsSomeAudioAndVideo();
5084 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005085 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005086 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005087 // Pump messages for a second, and ensure no new packets end up sent.
5088 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5089 WAIT(false, 1000);
5090 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5091 EXPECT_EQ(sent_packets_a, sent_packets_b);
5092}
5093
Steve Anton7eca0932018-03-30 15:18:41 -07005094// Test that transport stats are generated by the RTCStatsCollector for a
5095// connection that only involves data channels. This is a regression test for
5096// crbug.com/826972.
5097#ifdef HAVE_SCTP
5098TEST_P(PeerConnectionIntegrationTest,
5099 TransportStatsReportedForDataChannelOnlyConnection) {
5100 ASSERT_TRUE(CreatePeerConnectionWrappers());
5101 ConnectFakeSignaling();
5102 caller()->CreateDataChannel();
5103
5104 caller()->CreateAndSetAndSignalOffer();
5105 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5106 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5107
5108 auto caller_report = caller()->NewGetStats();
5109 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5110 auto callee_report = callee()->NewGetStats();
5111 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5112}
5113#endif // HAVE_SCTP
5114
Qingsi Wang7685e862018-06-11 20:15:46 -07005115TEST_P(PeerConnectionIntegrationTest,
5116 IceEventsGeneratedAndLoggedInRtcEventLog) {
5117 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5118 ConnectFakeSignaling();
5119 PeerConnectionInterface::RTCOfferAnswerOptions options;
5120 options.offer_to_receive_audio = 1;
5121 caller()->SetOfferAnswerOptions(options);
5122 caller()->CreateAndSetAndSignalOffer();
5123 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5124 ASSERT_NE(nullptr, caller()->event_log_factory());
5125 ASSERT_NE(nullptr, callee()->event_log_factory());
5126 webrtc::FakeRtcEventLog* caller_event_log =
5127 static_cast<webrtc::FakeRtcEventLog*>(
5128 caller()->event_log_factory()->last_log_created());
5129 webrtc::FakeRtcEventLog* callee_event_log =
5130 static_cast<webrtc::FakeRtcEventLog*>(
5131 callee()->event_log_factory()->last_log_created());
5132 ASSERT_NE(nullptr, caller_event_log);
5133 ASSERT_NE(nullptr, callee_event_log);
5134 int caller_ice_config_count = caller_event_log->GetEventCount(
5135 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5136 int caller_ice_event_count = caller_event_log->GetEventCount(
5137 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5138 int callee_ice_config_count = callee_event_log->GetEventCount(
5139 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5140 int callee_ice_event_count = callee_event_log->GetEventCount(
5141 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5142 EXPECT_LT(0, caller_ice_config_count);
5143 EXPECT_LT(0, caller_ice_event_count);
5144 EXPECT_LT(0, callee_ice_config_count);
5145 EXPECT_LT(0, callee_ice_event_count);
5146}
5147
Qingsi Wangc129c352019-04-18 10:41:58 -07005148TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005149 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5150 3478};
5151 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5152
5153 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5154
5155 webrtc::PeerConnectionInterface::IceServer ice_server;
5156 ice_server.urls.push_back("turn:88.88.88.0:3478");
5157 ice_server.username = "test";
5158 ice_server.password = "test";
5159
5160 PeerConnectionInterface::RTCConfiguration caller_config;
5161 caller_config.servers.push_back(ice_server);
5162 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5163 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005164 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005165
5166 PeerConnectionInterface::RTCConfiguration callee_config;
5167 callee_config.servers.push_back(ice_server);
5168 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5169 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005170 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005171
5172 ASSERT_TRUE(
5173 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5174
5175 // Do normal offer/answer and wait for ICE to complete.
5176 ConnectFakeSignaling();
5177 caller()->AddAudioVideoTracks();
5178 callee()->AddAudioVideoTracks();
5179 caller()->CreateAndSetAndSignalOffer();
5180 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5181 // Since we are doing continual gathering, the ICE transport does not reach
5182 // kIceGatheringComplete (see
5183 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5184 // kIceConnectionComplete.
5185 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5186 caller()->ice_connection_state(), kDefaultTimeout);
5187 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5188 callee()->ice_connection_state(), kDefaultTimeout);
5189 // Note that we cannot use the metric
5190 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5191 // metric is only populated when we reach kIceConnectionComplete in the
5192 // current implementation.
5193 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5194 caller()->last_candidate_gathered().type());
5195 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5196 callee()->last_candidate_gathered().type());
5197
5198 // Loosen the caller's candidate filter.
5199 caller_config = caller()->pc()->GetConfiguration();
5200 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5201 caller()->pc()->SetConfiguration(caller_config);
5202 // We should have gathered a new host candidate.
5203 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5204 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5205
5206 // Loosen the callee's candidate filter.
5207 callee_config = callee()->pc()->GetConfiguration();
5208 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5209 callee()->pc()->SetConfiguration(callee_config);
5210 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5211 callee()->last_candidate_gathered().type(), kDefaultTimeout);
5212}
5213
Eldar Relloda13ea22019-06-01 12:23:43 +03005214TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03005215 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5216 3478};
5217 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5218
5219 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5220
5221 webrtc::PeerConnectionInterface::IceServer ice_server;
5222 ice_server.urls.push_back("turn:88.88.88.0:3478");
5223 ice_server.username = "test";
5224 ice_server.password = "123";
5225
5226 PeerConnectionInterface::RTCConfiguration caller_config;
5227 caller_config.servers.push_back(ice_server);
5228 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5229 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5230
5231 PeerConnectionInterface::RTCConfiguration callee_config;
5232 callee_config.servers.push_back(ice_server);
5233 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5234 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5235
5236 ASSERT_TRUE(
5237 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5238
5239 // Do normal offer/answer and wait for ICE to complete.
5240 ConnectFakeSignaling();
5241 caller()->AddAudioVideoTracks();
5242 callee()->AddAudioVideoTracks();
5243 caller()->CreateAndSetAndSignalOffer();
5244 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5245 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5246 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5247 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
5248 EXPECT_NE(std::string::npos,
5249 caller()->error_event().host_candidate.find(":"));
5250}
5251
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005252INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5253 PeerConnectionIntegrationTest,
5254 Values(SdpSemantics::kPlanB,
5255 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005256
Steve Anton74255ff2018-01-24 18:32:57 -08005257// Tests that verify interoperability between Plan B and Unified Plan
5258// PeerConnections.
5259class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08005260 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08005261 public ::testing::WithParamInterface<
5262 std::tuple<SdpSemantics, SdpSemantics>> {
5263 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08005264 // Setting the SdpSemantics for the base test to kDefault does not matter
5265 // because we specify not to use the test semantics when creating
5266 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08005267 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07005268 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08005269 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08005270 callee_semantics_(std::get<1>(GetParam())) {}
5271
5272 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07005273 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5274 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08005275 }
5276
5277 const SdpSemantics caller_semantics_;
5278 const SdpSemantics callee_semantics_;
5279};
5280
5281TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5282 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5283 ConnectFakeSignaling();
5284
5285 caller()->CreateAndSetAndSignalOffer();
5286 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5287}
5288
5289TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
5290 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5291 ConnectFakeSignaling();
5292 auto audio_sender = caller()->AddAudioTrack();
5293
5294 caller()->CreateAndSetAndSignalOffer();
5295 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5296
5297 // Verify that one audio receiver has been created on the remote and that it
5298 // has the same track ID as the sending track.
5299 auto receivers = callee()->pc()->GetReceivers();
5300 ASSERT_EQ(1u, receivers.size());
5301 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
5302 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
5303
Seth Hampson2f0d7022018-02-20 11:54:42 -08005304 MediaExpectations media_expectations;
5305 media_expectations.CalleeExpectsSomeAudio();
5306 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005307}
5308
5309TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
5310 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5311 ConnectFakeSignaling();
5312 auto video_sender = caller()->AddVideoTrack();
5313 auto audio_sender = caller()->AddAudioTrack();
5314
5315 caller()->CreateAndSetAndSignalOffer();
5316 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5317
5318 // Verify that one audio and one video receiver have been created on the
5319 // remote and that they have the same track IDs as the sending tracks.
5320 auto audio_receivers =
5321 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5322 ASSERT_EQ(1u, audio_receivers.size());
5323 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5324 auto video_receivers =
5325 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5326 ASSERT_EQ(1u, video_receivers.size());
5327 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5328
Seth Hampson2f0d7022018-02-20 11:54:42 -08005329 MediaExpectations media_expectations;
5330 media_expectations.CalleeExpectsSomeAudioAndVideo();
5331 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005332}
5333
5334TEST_P(PeerConnectionIntegrationInteropTest,
5335 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5336 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5337 ConnectFakeSignaling();
5338 caller()->AddAudioVideoTracks();
5339 callee()->AddAudioVideoTracks();
5340
5341 caller()->CreateAndSetAndSignalOffer();
5342 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5343
Seth Hampson2f0d7022018-02-20 11:54:42 -08005344 MediaExpectations media_expectations;
5345 media_expectations.ExpectBidirectionalAudioAndVideo();
5346 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005347}
5348
5349TEST_P(PeerConnectionIntegrationInteropTest,
5350 ReverseRolesOneAudioLocalToOneVideoRemote) {
5351 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5352 ConnectFakeSignaling();
5353 caller()->AddAudioTrack();
5354 callee()->AddVideoTrack();
5355
5356 caller()->CreateAndSetAndSignalOffer();
5357 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5358
5359 // Verify that only the audio track has been negotiated.
5360 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5361 // Might also check that the callee's NegotiationNeeded flag is set.
5362
5363 // Reverse roles.
5364 callee()->CreateAndSetAndSignalOffer();
5365 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5366
Seth Hampson2f0d7022018-02-20 11:54:42 -08005367 MediaExpectations media_expectations;
5368 media_expectations.CallerExpectsSomeVideo();
5369 media_expectations.CalleeExpectsSomeAudio();
5370 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005371}
5372
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005373INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07005374 PeerConnectionIntegrationTest,
5375 PeerConnectionIntegrationInteropTest,
5376 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5377 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5378
5379// Test that if the Unified Plan side offers two video tracks then the Plan B
5380// side will only see the first one and ignore the second.
5381TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005382 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5383 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005384 ConnectFakeSignaling();
5385 auto first_sender = caller()->AddVideoTrack();
5386 caller()->AddVideoTrack();
5387
5388 caller()->CreateAndSetAndSignalOffer();
5389 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5390
5391 // Verify that there is only one receiver and it corresponds to the first
5392 // added track.
5393 auto receivers = callee()->pc()->GetReceivers();
5394 ASSERT_EQ(1u, receivers.size());
5395 EXPECT_TRUE(receivers[0]->track()->enabled());
5396 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5397
Seth Hampson2f0d7022018-02-20 11:54:42 -08005398 MediaExpectations media_expectations;
5399 media_expectations.CalleeExpectsSomeVideo();
5400 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005401}
5402
Steve Anton2bed3972019-01-04 17:04:30 -08005403// Test that if the initial offer tagged BUNDLE section is rejected due to its
5404// associated RtpTransceiver being stopped and another transceiver is added,
5405// then renegotiation causes the callee to receive the new video track without
5406// error.
5407// This is a regression test for bugs.webrtc.org/9954
5408TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5409 ReOfferWithStoppedBundleTaggedTransceiver) {
5410 RTCConfiguration config;
5411 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5412 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5413 ConnectFakeSignaling();
5414 auto audio_transceiver_or_error =
5415 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5416 ASSERT_TRUE(audio_transceiver_or_error.ok());
5417 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5418
5419 caller()->CreateAndSetAndSignalOffer();
5420 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5421 {
5422 MediaExpectations media_expectations;
5423 media_expectations.CalleeExpectsSomeAudio();
5424 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5425 }
5426
5427 audio_transceiver->Stop();
5428 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5429
5430 caller()->CreateAndSetAndSignalOffer();
5431 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5432 {
5433 MediaExpectations media_expectations;
5434 media_expectations.CalleeExpectsSomeVideo();
5435 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5436 }
5437}
5438
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005439#ifdef HAVE_SCTP
5440
5441TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5442 EndToEndCallWithBundledSctpDataChannel) {
5443 ASSERT_TRUE(CreatePeerConnectionWrappers());
5444 ConnectFakeSignaling();
5445 caller()->CreateDataChannel();
5446 caller()->AddAudioVideoTracks();
5447 callee()->AddAudioVideoTracks();
5448 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
5449 caller()->CreateAndSetAndSignalOffer();
5450 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5451 // Ensure that media and data are multiplexed on the same DTLS transport.
5452 // This only works on Unified Plan, because transports are not exposed in plan
5453 // B.
5454 auto sctp_info = caller()->pc()->GetSctpTransport()->Information();
5455 EXPECT_EQ(sctp_info.dtls_transport(),
5456 caller()->pc()->GetSenders()[0]->dtls_transport());
5457}
5458
5459#endif // HAVE_SCTP
5460
deadbeef1dcb1642017-03-29 21:08:16 -07005461} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01005462} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07005463
5464#endif // if !defined(THREAD_SANITIZER)