blob: c368ec0396998bcbb534027a1ac30f3e3c5e9a26 [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 }
301
Steve Anton15324772018-01-16 10:26:49 -0800302 void AddAudioVideoTracks() {
303 AddAudioTrack();
304 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700305 }
306
Steve Anton74255ff2018-01-24 18:32:57 -0800307 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
308 return AddTrack(CreateLocalAudioTrack());
309 }
deadbeef1dcb1642017-03-29 21:08:16 -0700310
Steve Anton74255ff2018-01-24 18:32:57 -0800311 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
312 return AddTrack(CreateLocalVideoTrack());
313 }
deadbeef1dcb1642017-03-29 21:08:16 -0700314
315 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200316 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700317 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200318 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700319 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200320 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700321 // TODO(perkj): Test audio source when it is implemented. Currently audio
322 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700323 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700324 source);
325 }
326
327 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200328 webrtc::FakePeriodicVideoSource::Config config;
329 config.timestamp_offset_ms = rtc::TimeMillis();
330 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700331 }
332
333 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200334 CreateLocalVideoTrackWithConfig(
335 webrtc::FakePeriodicVideoSource::Config config) {
336 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700337 }
338
339 rtc::scoped_refptr<webrtc::VideoTrackInterface>
340 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200341 webrtc::FakePeriodicVideoSource::Config config;
342 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200343 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200344 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700345 }
346
Steve Anton74255ff2018-01-24 18:32:57 -0800347 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
348 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800349 const std::vector<std::string>& stream_ids = {}) {
350 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800351 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800352 return result.MoveValue();
353 }
354
355 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
356 cricket::MediaType media_type) {
357 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +0100358 for (const auto& receiver : pc()->GetReceivers()) {
Steve Anton74255ff2018-01-24 18:32:57 -0800359 if (receiver->media_type() == media_type) {
360 receivers.push_back(receiver);
361 }
362 }
363 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700364 }
365
Seth Hampson2f0d7022018-02-20 11:54:42 -0800366 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
367 cricket::MediaType media_type) {
368 for (auto transceiver : pc()->GetTransceivers()) {
369 if (transceiver->receiver()->media_type() == media_type) {
370 return transceiver;
371 }
372 }
373 return nullptr;
374 }
375
deadbeef1dcb1642017-03-29 21:08:16 -0700376 bool SignalingStateStable() {
377 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
378 }
379
380 void CreateDataChannel() { CreateDataChannel(nullptr); }
381
382 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700383 CreateDataChannel(kDataChannelLabel, init);
384 }
385
386 void CreateDataChannel(const std::string& label,
387 const webrtc::DataChannelInit* init) {
388 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700389 ASSERT_TRUE(data_channel_.get() != nullptr);
390 data_observer_.reset(new MockDataChannelObserver(data_channel_));
391 }
392
393 DataChannelInterface* data_channel() { return data_channel_; }
394 const MockDataChannelObserver* data_observer() const {
395 return data_observer_.get();
396 }
397
398 int audio_frames_received() const {
399 return fake_audio_capture_module_->frames_received();
400 }
401
402 // Takes minimum of video frames received for each track.
403 //
404 // Can be used like:
405 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
406 //
407 // To ensure that all video tracks received at least a certain number of
408 // frames.
409 int min_video_frames_received_per_track() const {
410 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200411 if (fake_video_renderers_.empty()) {
412 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700413 }
deadbeef1dcb1642017-03-29 21:08:16 -0700414
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200415 for (const auto& pair : fake_video_renderers_) {
416 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700417 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200418 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700419 }
420
421 // Returns a MockStatsObserver in a state after stats gathering finished,
422 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700423 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700424 webrtc::MediaStreamTrackInterface* track) {
425 rtc::scoped_refptr<MockStatsObserver> observer(
426 new rtc::RefCountedObject<MockStatsObserver>());
427 EXPECT_TRUE(peer_connection_->GetStats(
428 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
429 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
430 return observer;
431 }
432
433 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700434 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
435 return OldGetStatsForTrack(nullptr);
436 }
437
438 // Synchronously gets stats and returns them. If it times out, fails the test
439 // and returns null.
440 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
441 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
442 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
443 peer_connection_->GetStats(callback);
444 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
445 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700446 }
447
448 int rendered_width() {
449 EXPECT_FALSE(fake_video_renderers_.empty());
450 return fake_video_renderers_.empty()
451 ? 0
452 : fake_video_renderers_.begin()->second->width();
453 }
454
455 int rendered_height() {
456 EXPECT_FALSE(fake_video_renderers_.empty());
457 return fake_video_renderers_.empty()
458 ? 0
459 : fake_video_renderers_.begin()->second->height();
460 }
461
462 double rendered_aspect_ratio() {
463 if (rendered_height() == 0) {
464 return 0.0;
465 }
466 return static_cast<double>(rendered_width()) / rendered_height();
467 }
468
469 webrtc::VideoRotation rendered_rotation() {
470 EXPECT_FALSE(fake_video_renderers_.empty());
471 return fake_video_renderers_.empty()
472 ? webrtc::kVideoRotation_0
473 : fake_video_renderers_.begin()->second->rotation();
474 }
475
476 int local_rendered_width() {
477 return local_video_renderer_ ? local_video_renderer_->width() : 0;
478 }
479
480 int local_rendered_height() {
481 return local_video_renderer_ ? local_video_renderer_->height() : 0;
482 }
483
484 double local_rendered_aspect_ratio() {
485 if (local_rendered_height() == 0) {
486 return 0.0;
487 }
488 return static_cast<double>(local_rendered_width()) /
489 local_rendered_height();
490 }
491
492 size_t number_of_remote_streams() {
493 if (!pc()) {
494 return 0;
495 }
496 return pc()->remote_streams()->count();
497 }
498
499 StreamCollectionInterface* remote_streams() const {
500 if (!pc()) {
501 ADD_FAILURE();
502 return nullptr;
503 }
504 return pc()->remote_streams();
505 }
506
507 StreamCollectionInterface* local_streams() {
508 if (!pc()) {
509 ADD_FAILURE();
510 return nullptr;
511 }
512 return pc()->local_streams();
513 }
514
515 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
516 return pc()->signaling_state();
517 }
518
519 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
520 return pc()->ice_connection_state();
521 }
522
Jonas Olsson7a6739e2019-01-15 16:31:55 +0100523 webrtc::PeerConnectionInterface::IceConnectionState
524 standardized_ice_connection_state() {
525 return pc()->standardized_ice_connection_state();
526 }
527
deadbeef1dcb1642017-03-29 21:08:16 -0700528 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
529 return pc()->ice_gathering_state();
530 }
531
532 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
533 // GetReceivers. They're updated automatically when a remote offer/answer
534 // from the fake signaling channel is applied, or when
535 // ResetRtpReceiverObservers below is called.
536 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
537 rtp_receiver_observers() {
538 return rtp_receiver_observers_;
539 }
540
541 void ResetRtpReceiverObservers() {
542 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100543 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
544 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700545 std::unique_ptr<MockRtpReceiverObserver> observer(
546 new MockRtpReceiverObserver(receiver->media_type()));
547 receiver->SetObserver(observer.get());
548 rtp_receiver_observers_.push_back(std::move(observer));
549 }
550 }
551
Qingsi Wangecd30542019-05-22 14:34:56 -0700552 rtc::FakeNetworkManager* network_manager() const {
Steve Antonede9ca52017-10-16 13:04:27 -0700553 return fake_network_manager_.get();
554 }
555 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
556
Qingsi Wang7685e862018-06-11 20:15:46 -0700557 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
558 return event_log_factory_;
559 }
560
Qingsi Wangc129c352019-04-18 10:41:58 -0700561 const cricket::Candidate& last_candidate_gathered() const {
562 return last_candidate_gathered_;
563 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300564 const cricket::IceCandidateErrorEvent& error_event() const {
565 return error_event_;
566 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700567
Qingsi Wangecd30542019-05-22 14:34:56 -0700568 // Sets the mDNS responder for the owned fake network manager and keeps a
569 // reference to the responder.
570 void SetMdnsResponder(
571 std::unique_ptr<webrtc::FakeMdnsResponder> mdns_responder) {
572 RTC_DCHECK(mdns_responder != nullptr);
573 mdns_responder_ = mdns_responder.get();
574 network_manager()->set_mdns_responder(std::move(mdns_responder));
575 }
576
deadbeef1dcb1642017-03-29 21:08:16 -0700577 private:
578 explicit PeerConnectionWrapper(const std::string& debug_name)
579 : debug_name_(debug_name) {}
580
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800581 bool Init(
582 const PeerConnectionFactory::Options* options,
583 const PeerConnectionInterface::RTCConfiguration* config,
584 webrtc::PeerConnectionDependencies dependencies,
585 rtc::Thread* network_thread,
586 rtc::Thread* worker_thread,
587 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
588 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700589 // There's an error in this test code if Init ends up being called twice.
590 RTC_DCHECK(!peer_connection_);
591 RTC_DCHECK(!peer_connection_factory_);
592
593 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700594 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700595
596 std::unique_ptr<cricket::PortAllocator> port_allocator(
597 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700598 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700599 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
600 if (!fake_audio_capture_module_) {
601 return false;
602 }
deadbeef1dcb1642017-03-29 21:08:16 -0700603 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700604
605 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
606 pc_factory_dependencies.network_thread = network_thread;
607 pc_factory_dependencies.worker_thread = worker_thread;
608 pc_factory_dependencies.signaling_thread = signaling_thread;
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200609 pc_factory_dependencies.task_queue_factory =
610 webrtc::CreateDefaultTaskQueueFactory();
611 cricket::MediaEngineDependencies media_deps;
612 media_deps.task_queue_factory =
613 pc_factory_dependencies.task_queue_factory.get();
614 media_deps.adm = fake_audio_capture_module_;
615 webrtc::SetMediaEngineDefaults(&media_deps);
Qingsi Wang7685e862018-06-11 20:15:46 -0700616 pc_factory_dependencies.media_engine =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200617 cricket::CreateMediaEngine(std::move(media_deps));
Qingsi Wang7685e862018-06-11 20:15:46 -0700618 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
619 if (event_log_factory) {
620 event_log_factory_ = event_log_factory.get();
621 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
622 } else {
623 pc_factory_dependencies.event_log_factory =
Danil Chapovalov9da25bd2019-06-20 10:19:42 +0200624 absl::make_unique<webrtc::RtcEventLogFactory>(
625 pc_factory_dependencies.task_queue_factory.get());
Qingsi Wang7685e862018-06-11 20:15:46 -0700626 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800627 if (media_transport_factory) {
628 pc_factory_dependencies.media_transport_factory =
629 std::move(media_transport_factory);
630 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700631 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
632 std::move(pc_factory_dependencies));
633
deadbeef1dcb1642017-03-29 21:08:16 -0700634 if (!peer_connection_factory_) {
635 return false;
636 }
637 if (options) {
638 peer_connection_factory_->SetOptions(*options);
639 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800640 if (config) {
641 sdp_semantics_ = config->sdp_semantics;
642 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700643
644 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200645 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700646 return peer_connection_.get() != nullptr;
647 }
648
649 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700650 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700651 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700652 PeerConnectionInterface::RTCConfiguration modified_config;
653 // If |config| is null, this will result in a default configuration being
654 // used.
655 if (config) {
656 modified_config = *config;
657 }
658 // Disable resolution adaptation; we don't want it interfering with the
659 // test results.
660 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
661 // ratios and not specific resolutions, is this even necessary?
662 modified_config.set_cpu_adaptation(false);
663
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700664 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700665 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700666 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700667 }
668
669 void set_signaling_message_receiver(
670 SignalingMessageReceiver* signaling_message_receiver) {
671 signaling_message_receiver_ = signaling_message_receiver;
672 }
673
674 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
675
Steve Antonede9ca52017-10-16 13:04:27 -0700676 void set_signal_ice_candidates(bool signal) {
677 signal_ice_candidates_ = signal;
678 }
679
deadbeef1dcb1642017-03-29 21:08:16 -0700680 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200681 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700682 // Set max frame rate to 10fps to reduce the risk of test flakiness.
683 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200684 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700685
Niels Möller5c7efe72018-05-11 10:34:46 +0200686 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200687 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
688 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700689 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200690 peer_connection_factory_->CreateVideoTrack(
691 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700692 if (!local_video_renderer_) {
693 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
694 }
695 return track;
696 }
697
698 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100699 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800700 std::unique_ptr<SessionDescriptionInterface> desc =
701 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700702 if (received_sdp_munger_) {
703 received_sdp_munger_(desc->description());
704 }
705
706 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
707 // Setting a remote description may have changed the number of receivers,
708 // so reset the receiver observers.
709 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800710 if (remote_offer_handler_) {
711 remote_offer_handler_();
712 }
deadbeef1dcb1642017-03-29 21:08:16 -0700713 auto answer = CreateAnswer();
714 ASSERT_NE(nullptr, answer);
715 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
716 }
717
718 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100719 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800720 std::unique_ptr<SessionDescriptionInterface> desc =
721 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700722 if (received_sdp_munger_) {
723 received_sdp_munger_(desc->description());
724 }
725
726 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
727 // Set the RtpReceiverObserver after receivers are created.
728 ResetRtpReceiverObservers();
729 }
730
731 // Returns null on failure.
732 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
733 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
734 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
735 pc()->CreateOffer(observer, offer_answer_options_);
736 return WaitForDescriptionFromObserver(observer);
737 }
738
739 // Returns null on failure.
740 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
741 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
742 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
743 pc()->CreateAnswer(observer, offer_answer_options_);
744 return WaitForDescriptionFromObserver(observer);
745 }
746
747 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100748 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700749 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
750 if (!observer->result()) {
751 return nullptr;
752 }
753 auto description = observer->MoveDescription();
754 if (generated_sdp_munger_) {
755 generated_sdp_munger_(description->description());
756 }
757 return description;
758 }
759
760 // Setting the local description and sending the SDP message over the fake
761 // signaling channel are combined into the same method because the SDP
762 // message needs to be sent as soon as SetLocalDescription finishes, without
763 // waiting for the observer to be called. This ensures that ICE candidates
764 // don't outrace the description.
765 bool SetLocalDescriptionAndSendSdpMessage(
766 std::unique_ptr<SessionDescriptionInterface> desc) {
767 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
768 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100769 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800770 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700771 std::string sdp;
772 EXPECT_TRUE(desc->ToString(&sdp));
773 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800774 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
775 RemoveUnusedVideoRenderers();
776 }
deadbeef1dcb1642017-03-29 21:08:16 -0700777 // As mentioned above, we need to send the message immediately after
778 // SetLocalDescription.
779 SendSdpMessage(type, sdp);
780 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
781 return true;
782 }
783
784 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
785 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
786 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100787 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700788 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800789 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
790 RemoveUnusedVideoRenderers();
791 }
deadbeef1dcb1642017-03-29 21:08:16 -0700792 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
793 return observer->result();
794 }
795
Seth Hampson2f0d7022018-02-20 11:54:42 -0800796 // This is a work around to remove unused fake_video_renderers from
797 // transceivers that have either stopped or are no longer receiving.
798 void RemoveUnusedVideoRenderers() {
799 auto transceivers = pc()->GetTransceivers();
800 for (auto& transceiver : transceivers) {
801 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
802 continue;
803 }
804 // Remove fake video renderers from any stopped transceivers.
805 if (transceiver->stopped()) {
806 auto it =
807 fake_video_renderers_.find(transceiver->receiver()->track()->id());
808 if (it != fake_video_renderers_.end()) {
809 fake_video_renderers_.erase(it);
810 }
811 }
812 // Remove fake video renderers from any transceivers that are no longer
813 // receiving.
814 if ((transceiver->current_direction() &&
815 !webrtc::RtpTransceiverDirectionHasRecv(
816 *transceiver->current_direction()))) {
817 auto it =
818 fake_video_renderers_.find(transceiver->receiver()->track()->id());
819 if (it != fake_video_renderers_.end()) {
820 fake_video_renderers_.erase(it);
821 }
822 }
823 }
824 }
825
deadbeef1dcb1642017-03-29 21:08:16 -0700826 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
827 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800828 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700829 if (signaling_delay_ms_ == 0) {
830 RelaySdpMessageIfReceiverExists(type, msg);
831 } else {
832 invoker_.AsyncInvokeDelayed<void>(
833 RTC_FROM_HERE, rtc::Thread::Current(),
834 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
835 this, type, msg),
836 signaling_delay_ms_);
837 }
838 }
839
Steve Antona3a92c22017-12-07 10:27:41 -0800840 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700841 if (signaling_message_receiver_) {
842 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
843 }
844 }
845
846 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
847 // default).
848 void SendIceMessage(const std::string& sdp_mid,
849 int sdp_mline_index,
850 const std::string& msg) {
851 if (signaling_delay_ms_ == 0) {
852 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
853 } else {
854 invoker_.AsyncInvokeDelayed<void>(
855 RTC_FROM_HERE, rtc::Thread::Current(),
856 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
857 this, sdp_mid, sdp_mline_index, msg),
858 signaling_delay_ms_);
859 }
860 }
861
862 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
863 int sdp_mline_index,
864 const std::string& msg) {
865 if (signaling_message_receiver_) {
866 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
867 msg);
868 }
869 }
870
871 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800872 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
873 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700874 HandleIncomingOffer(msg);
875 } else {
876 HandleIncomingAnswer(msg);
877 }
878 }
879
880 void ReceiveIceMessage(const std::string& sdp_mid,
881 int sdp_mline_index,
882 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100883 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700884 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
885 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
886 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
887 }
888
889 // PeerConnectionObserver callbacks.
890 void OnSignalingChange(
891 webrtc::PeerConnectionInterface::SignalingState new_state) override {
892 EXPECT_EQ(pc()->signaling_state(), new_state);
893 }
Steve Anton15324772018-01-16 10:26:49 -0800894 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
895 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
896 streams) override {
897 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
898 rtc::scoped_refptr<VideoTrackInterface> video_track(
899 static_cast<VideoTrackInterface*>(receiver->track().get()));
900 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700901 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800902 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200903 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700904 }
905 }
Steve Anton15324772018-01-16 10:26:49 -0800906 void OnRemoveTrack(
907 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
908 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
909 auto it = fake_video_renderers_.find(receiver->track()->id());
910 RTC_DCHECK(it != fake_video_renderers_.end());
911 fake_video_renderers_.erase(it);
912 }
913 }
deadbeef1dcb1642017-03-29 21:08:16 -0700914 void OnRenegotiationNeeded() override {}
915 void OnIceConnectionChange(
916 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
917 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700918 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700919 }
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100920 void OnStandardizedIceConnectionChange(
921 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
922 standardized_ice_connection_state_history_.push_back(new_state);
923 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200924 void OnConnectionChange(
925 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
926 peer_connection_state_history_.push_back(new_state);
927 }
928
deadbeef1dcb1642017-03-29 21:08:16 -0700929 void OnIceGatheringChange(
930 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700931 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700932 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700933 }
934 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100935 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700936
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800937 if (remote_async_resolver_) {
938 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800939 if (local_candidate.address().IsUnresolvedIP()) {
940 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
941 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700942 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800943 local_candidate.address().hostname());
944 RTC_DCHECK(!resolved_ip.IsNil());
945 resolved_addr.SetResolvedIP(resolved_ip);
946 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
947 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
948 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700949 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700950 }
951
deadbeef1dcb1642017-03-29 21:08:16 -0700952 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800953 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700954 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700955 // Remote party may be deleted.
956 return;
957 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800958 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700959 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700960 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300961 void OnIceCandidateError(const std::string& host_candidate,
962 const std::string& url,
963 int error_code,
964 const std::string& error_text) override {
965 error_event_ = cricket::IceCandidateErrorEvent(host_candidate, url,
966 error_code, error_text);
967 }
deadbeef1dcb1642017-03-29 21:08:16 -0700968 void OnDataChannel(
969 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100970 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700971 data_channel_ = data_channel;
972 data_observer_.reset(new MockDataChannelObserver(data_channel));
973 }
974
deadbeef1dcb1642017-03-29 21:08:16 -0700975 std::string debug_name_;
976
977 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -0700978 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
979 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -0700980
981 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
982 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
983 peer_connection_factory_;
984
Steve Antonede9ca52017-10-16 13:04:27 -0700985 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700986 // Needed to keep track of number of frames sent.
987 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
988 // Needed to keep track of number of frames received.
989 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
990 fake_video_renderers_;
991 // Needed to ensure frames aren't received for removed tracks.
992 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
993 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -0700994
995 // For remote peer communication.
996 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
997 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -0700998 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -0700999 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001000 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001001
Niels Möller5c7efe72018-05-11 10:34:46 +02001002 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001003 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001004 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1005 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001006 // |local_video_renderer_| attached to the first created local video track.
1007 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1008
Seth Hampson2f0d7022018-02-20 11:54:42 -08001009 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001010 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1011 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1012 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001013 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001014 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001015 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1016 std::unique_ptr<MockDataChannelObserver> data_observer_;
1017
1018 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1019
Steve Antonede9ca52017-10-16 13:04:27 -07001020 std::vector<PeerConnectionInterface::IceConnectionState>
1021 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001022 std::vector<PeerConnectionInterface::IceConnectionState>
1023 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001024 std::vector<PeerConnectionInterface::PeerConnectionState>
1025 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001026 std::vector<PeerConnectionInterface::IceGatheringState>
1027 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001028
Qingsi Wang7685e862018-06-11 20:15:46 -07001029 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1030
deadbeef1dcb1642017-03-29 21:08:16 -07001031 rtc::AsyncInvoker invoker_;
1032
Seth Hampson2f0d7022018-02-20 11:54:42 -08001033 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001034};
1035
Elad Alon99c3fe52017-10-13 16:29:40 +02001036class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1037 public:
1038 virtual ~MockRtcEventLogOutput() = default;
1039 MOCK_CONST_METHOD0(IsActive, bool());
1040 MOCK_METHOD1(Write, bool(const std::string&));
1041};
1042
Seth Hampson2f0d7022018-02-20 11:54:42 -08001043// This helper object is used for both specifying how many audio/video frames
1044// are expected to be received for a caller/callee. It provides helper functions
1045// to specify these expectations. The object initially starts in a state of no
1046// expectations.
1047class MediaExpectations {
1048 public:
1049 enum ExpectFrames {
1050 kExpectSomeFrames,
1051 kExpectNoFrames,
1052 kNoExpectation,
1053 };
1054
1055 void ExpectBidirectionalAudioAndVideo() {
1056 ExpectBidirectionalAudio();
1057 ExpectBidirectionalVideo();
1058 }
1059
1060 void ExpectBidirectionalAudio() {
1061 CallerExpectsSomeAudio();
1062 CalleeExpectsSomeAudio();
1063 }
1064
1065 void ExpectNoAudio() {
1066 CallerExpectsNoAudio();
1067 CalleeExpectsNoAudio();
1068 }
1069
1070 void ExpectBidirectionalVideo() {
1071 CallerExpectsSomeVideo();
1072 CalleeExpectsSomeVideo();
1073 }
1074
1075 void ExpectNoVideo() {
1076 CallerExpectsNoVideo();
1077 CalleeExpectsNoVideo();
1078 }
1079
1080 void CallerExpectsSomeAudioAndVideo() {
1081 CallerExpectsSomeAudio();
1082 CallerExpectsSomeVideo();
1083 }
1084
1085 void CalleeExpectsSomeAudioAndVideo() {
1086 CalleeExpectsSomeAudio();
1087 CalleeExpectsSomeVideo();
1088 }
1089
1090 // Caller's audio functions.
1091 void CallerExpectsSomeAudio(
1092 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1093 caller_audio_expectation_ = kExpectSomeFrames;
1094 caller_audio_frames_expected_ = expected_audio_frames;
1095 }
1096
1097 void CallerExpectsNoAudio() {
1098 caller_audio_expectation_ = kExpectNoFrames;
1099 caller_audio_frames_expected_ = 0;
1100 }
1101
1102 // Caller's video functions.
1103 void CallerExpectsSomeVideo(
1104 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1105 caller_video_expectation_ = kExpectSomeFrames;
1106 caller_video_frames_expected_ = expected_video_frames;
1107 }
1108
1109 void CallerExpectsNoVideo() {
1110 caller_video_expectation_ = kExpectNoFrames;
1111 caller_video_frames_expected_ = 0;
1112 }
1113
1114 // Callee's audio functions.
1115 void CalleeExpectsSomeAudio(
1116 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1117 callee_audio_expectation_ = kExpectSomeFrames;
1118 callee_audio_frames_expected_ = expected_audio_frames;
1119 }
1120
1121 void CalleeExpectsNoAudio() {
1122 callee_audio_expectation_ = kExpectNoFrames;
1123 callee_audio_frames_expected_ = 0;
1124 }
1125
1126 // Callee's video functions.
1127 void CalleeExpectsSomeVideo(
1128 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1129 callee_video_expectation_ = kExpectSomeFrames;
1130 callee_video_frames_expected_ = expected_video_frames;
1131 }
1132
1133 void CalleeExpectsNoVideo() {
1134 callee_video_expectation_ = kExpectNoFrames;
1135 callee_video_frames_expected_ = 0;
1136 }
1137
1138 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1139 ExpectFrames caller_video_expectation_ = kNoExpectation;
1140 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1141 ExpectFrames callee_video_expectation_ = kNoExpectation;
1142 int caller_audio_frames_expected_ = 0;
1143 int caller_video_frames_expected_ = 0;
1144 int callee_audio_frames_expected_ = 0;
1145 int callee_video_frames_expected_ = 0;
1146};
1147
deadbeef1dcb1642017-03-29 21:08:16 -07001148// Tests two PeerConnections connecting to each other end-to-end, using a
1149// virtual network, fake A/V capture and fake encoder/decoders. The
1150// PeerConnections share the threads/socket servers, but use separate versions
1151// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001152class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001153 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001154 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1155 : sdp_semantics_(sdp_semantics),
1156 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001157 fss_(new rtc::FirewallSocketServer(ss_.get())),
1158 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001159 worker_thread_(rtc::Thread::Create()),
1160 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001161 network_thread_->SetName("PCNetworkThread", this);
1162 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001163 RTC_CHECK(network_thread_->Start());
1164 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001165 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001166 }
1167
Seth Hampson2f0d7022018-02-20 11:54:42 -08001168 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001169 // The PeerConnections should deleted before the TurnCustomizers.
1170 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1171 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1172 // that the TurnCustomizer outlives the life of the PeerConnection or else
1173 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001174 if (caller_) {
1175 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001176 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001177 }
1178 if (callee_) {
1179 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001180 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001181 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001182
1183 // If turn servers were created for the test they need to be destroyed on
1184 // the network thread.
1185 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1186 turn_servers_.clear();
1187 turn_customizers_.clear();
1188 });
deadbeef1dcb1642017-03-29 21:08:16 -07001189 }
1190
1191 bool SignalingStateStable() {
1192 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1193 }
1194
deadbeef71452802017-05-07 17:21:01 -07001195 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001196 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1197 // are connected. This is an important distinction. Once we have separate
1198 // ICE and DTLS state, this check needs to use the DTLS state.
1199 return (callee()->ice_connection_state() ==
1200 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1201 callee()->ice_connection_state() ==
1202 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1203 (caller()->ice_connection_state() ==
1204 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1205 caller()->ice_connection_state() ==
1206 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001207 }
1208
Qingsi Wang7685e862018-06-11 20:15:46 -07001209 // When |event_log_factory| is null, the default implementation of the event
1210 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001211 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1212 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001213 const PeerConnectionFactory::Options* options,
1214 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001215 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001216 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1217 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001218 RTCConfiguration modified_config;
1219 if (config) {
1220 modified_config = *config;
1221 }
Steve Anton3acffc32018-04-12 17:21:03 -07001222 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001223 if (!dependencies.cert_generator) {
1224 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001225 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001226 }
1227 std::unique_ptr<PeerConnectionWrapper> client(
1228 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001229
Niels Möllerf06f9232018-08-07 12:32:18 +02001230 if (!client->Init(options, &modified_config, std::move(dependencies),
1231 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001232 std::move(event_log_factory),
1233 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001234 return nullptr;
1235 }
1236 return client;
1237 }
1238
Qingsi Wang7685e862018-06-11 20:15:46 -07001239 std::unique_ptr<PeerConnectionWrapper>
1240 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1241 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001242 const PeerConnectionFactory::Options* options,
1243 const RTCConfiguration* config,
1244 webrtc::PeerConnectionDependencies dependencies) {
1245 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1246 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001247 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001248 std::move(dependencies),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001249 std::move(event_log_factory),
1250 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001251 }
1252
deadbeef1dcb1642017-03-29 21:08:16 -07001253 bool CreatePeerConnectionWrappers() {
1254 return CreatePeerConnectionWrappersWithConfig(
1255 PeerConnectionInterface::RTCConfiguration(),
1256 PeerConnectionInterface::RTCConfiguration());
1257 }
1258
Steve Anton3acffc32018-04-12 17:21:03 -07001259 bool CreatePeerConnectionWrappersWithSdpSemantics(
1260 SdpSemantics caller_semantics,
1261 SdpSemantics callee_semantics) {
1262 // Can't specify the sdp_semantics in the passed-in configuration since it
1263 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1264 // stored in sdp_semantics_. So get around this by modifying the instance
1265 // variable before calling CreatePeerConnectionWrapper for the caller and
1266 // callee PeerConnections.
1267 SdpSemantics original_semantics = sdp_semantics_;
1268 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001269 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001270 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001271 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001272 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001273 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001274 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001275 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001276 sdp_semantics_ = original_semantics;
1277 return caller_ && callee_;
1278 }
1279
deadbeef1dcb1642017-03-29 21:08:16 -07001280 bool CreatePeerConnectionWrappersWithConfig(
1281 const PeerConnectionInterface::RTCConfiguration& caller_config,
1282 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001283 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001284 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001285 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1286 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001287 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001288 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001289 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1290 /*media_transport_factory=*/nullptr);
1291 return caller_ && callee_;
1292 }
1293
1294 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1295 const PeerConnectionInterface::RTCConfiguration& caller_config,
1296 const PeerConnectionInterface::RTCConfiguration& callee_config,
1297 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1298 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
1299 caller_ =
1300 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1301 webrtc::PeerConnectionDependencies(nullptr),
1302 nullptr, std::move(caller_factory));
1303 callee_ =
1304 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1305 webrtc::PeerConnectionDependencies(nullptr),
1306 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001307 return caller_ && callee_;
1308 }
1309
1310 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1311 const PeerConnectionInterface::RTCConfiguration& caller_config,
1312 webrtc::PeerConnectionDependencies caller_dependencies,
1313 const PeerConnectionInterface::RTCConfiguration& callee_config,
1314 webrtc::PeerConnectionDependencies callee_dependencies) {
1315 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001316 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001317 std::move(caller_dependencies), nullptr,
1318 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001319 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001320 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001321 std::move(callee_dependencies), nullptr,
1322 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001323 return caller_ && callee_;
1324 }
1325
1326 bool CreatePeerConnectionWrappersWithOptions(
1327 const PeerConnectionFactory::Options& caller_options,
1328 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001329 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001330 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001331 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1332 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001333 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001334 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001335 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1336 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001337 return caller_ && callee_;
1338 }
1339
1340 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1341 PeerConnectionInterface::RTCConfiguration default_config;
1342 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001343 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001344 webrtc::PeerConnectionDependencies(nullptr));
1345 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001346 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001347 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001348 return caller_ && callee_;
1349 }
1350
Seth Hampson2f0d7022018-02-20 11:54:42 -08001351 std::unique_ptr<PeerConnectionWrapper>
1352 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001353 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1354 new FakeRTCCertificateGenerator());
1355 cert_generator->use_alternate_key();
1356
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001357 webrtc::PeerConnectionDependencies dependencies(nullptr);
1358 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001359 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001360 std::move(dependencies), nullptr,
1361 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001362 }
1363
Seth Hampsonaed71642018-06-11 07:41:32 -07001364 cricket::TestTurnServer* CreateTurnServer(
1365 rtc::SocketAddress internal_address,
1366 rtc::SocketAddress external_address,
1367 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1368 const std::string& common_name = "test turn server") {
1369 rtc::Thread* thread = network_thread();
1370 std::unique_ptr<cricket::TestTurnServer> turn_server =
1371 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1372 RTC_FROM_HERE,
1373 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001374 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001375 thread, internal_address, external_address, type,
1376 /*ignore_bad_certs=*/true, common_name);
1377 });
1378 turn_servers_.push_back(std::move(turn_server));
1379 // Interactions with the turn server should be done on the network thread.
1380 return turn_servers_.back().get();
1381 }
1382
1383 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1384 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1385 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1386 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001387 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001388 turn_customizers_.push_back(std::move(turn_customizer));
1389 // Interactions with the turn customizer should be done on the network
1390 // thread.
1391 return turn_customizers_.back().get();
1392 }
1393
1394 // Checks that the function counters for a TestTurnCustomizer are greater than
1395 // 0.
1396 void ExpectTurnCustomizerCountersIncremented(
1397 cricket::TestTurnCustomizer* turn_customizer) {
1398 unsigned int allow_channel_data_counter =
1399 network_thread()->Invoke<unsigned int>(
1400 RTC_FROM_HERE, [turn_customizer] {
1401 return turn_customizer->allow_channel_data_cnt_;
1402 });
1403 EXPECT_GT(allow_channel_data_counter, 0u);
1404 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1405 RTC_FROM_HERE,
1406 [turn_customizer] { return turn_customizer->modify_cnt_; });
1407 EXPECT_GT(modify_counter, 0u);
1408 }
1409
deadbeef1dcb1642017-03-29 21:08:16 -07001410 // Once called, SDP blobs and ICE candidates will be automatically signaled
1411 // between PeerConnections.
1412 void ConnectFakeSignaling() {
1413 caller_->set_signaling_message_receiver(callee_.get());
1414 callee_->set_signaling_message_receiver(caller_.get());
1415 }
1416
Steve Antonede9ca52017-10-16 13:04:27 -07001417 // Once called, SDP blobs will be automatically signaled between
1418 // PeerConnections. Note that ICE candidates will not be signaled unless they
1419 // are in the exchanged SDP blobs.
1420 void ConnectFakeSignalingForSdpOnly() {
1421 ConnectFakeSignaling();
1422 SetSignalIceCandidates(false);
1423 }
1424
deadbeef1dcb1642017-03-29 21:08:16 -07001425 void SetSignalingDelayMs(int delay_ms) {
1426 caller_->set_signaling_delay_ms(delay_ms);
1427 callee_->set_signaling_delay_ms(delay_ms);
1428 }
1429
Steve Antonede9ca52017-10-16 13:04:27 -07001430 void SetSignalIceCandidates(bool signal) {
1431 caller_->set_signal_ice_candidates(signal);
1432 callee_->set_signal_ice_candidates(signal);
1433 }
1434
deadbeef1dcb1642017-03-29 21:08:16 -07001435 // Messages may get lost on the unreliable DataChannel, so we send multiple
1436 // times to avoid test flakiness.
1437 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1438 const std::string& data,
1439 int retries) {
1440 for (int i = 0; i < retries; ++i) {
1441 dc->Send(DataBuffer(data));
1442 }
1443 }
1444
1445 rtc::Thread* network_thread() { return network_thread_.get(); }
1446
1447 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1448
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001449 webrtc::MediaTransportPair* loopback_media_transports() {
1450 return &loopback_media_transports_;
1451 }
1452
deadbeef1dcb1642017-03-29 21:08:16 -07001453 PeerConnectionWrapper* caller() { return caller_.get(); }
1454
1455 // Set the |caller_| to the |wrapper| passed in and return the
1456 // original |caller_|.
1457 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1458 PeerConnectionWrapper* wrapper) {
1459 PeerConnectionWrapper* old = caller_.release();
1460 caller_.reset(wrapper);
1461 return old;
1462 }
1463
1464 PeerConnectionWrapper* callee() { return callee_.get(); }
1465
1466 // Set the |callee_| to the |wrapper| passed in and return the
1467 // original |callee_|.
1468 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1469 PeerConnectionWrapper* wrapper) {
1470 PeerConnectionWrapper* old = callee_.release();
1471 callee_.reset(wrapper);
1472 return old;
1473 }
1474
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001475 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1476 network_thread()->Invoke<void>(
1477 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1478 caller()->port_allocator(), caller_flags));
1479 network_thread()->Invoke<void>(
1480 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1481 callee()->port_allocator(), callee_flags));
1482 }
1483
Steve Antonede9ca52017-10-16 13:04:27 -07001484 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1485
Seth Hampson2f0d7022018-02-20 11:54:42 -08001486 // Expects the provided number of new frames to be received within
1487 // kMaxWaitForFramesMs. The new expected frames are specified in
1488 // |media_expectations|. Returns false if any of the expectations were
1489 // not met.
1490 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1491 // First initialize the expected frame counts based upon the current
1492 // frame count.
1493 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1494 if (media_expectations.caller_audio_expectation_ ==
1495 MediaExpectations::kExpectSomeFrames) {
1496 total_caller_audio_frames_expected +=
1497 media_expectations.caller_audio_frames_expected_;
1498 }
1499 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001500 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001501 if (media_expectations.caller_video_expectation_ ==
1502 MediaExpectations::kExpectSomeFrames) {
1503 total_caller_video_frames_expected +=
1504 media_expectations.caller_video_frames_expected_;
1505 }
1506 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1507 if (media_expectations.callee_audio_expectation_ ==
1508 MediaExpectations::kExpectSomeFrames) {
1509 total_callee_audio_frames_expected +=
1510 media_expectations.callee_audio_frames_expected_;
1511 }
1512 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001513 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001514 if (media_expectations.callee_video_expectation_ ==
1515 MediaExpectations::kExpectSomeFrames) {
1516 total_callee_video_frames_expected +=
1517 media_expectations.callee_video_frames_expected_;
1518 }
deadbeef1dcb1642017-03-29 21:08:16 -07001519
Seth Hampson2f0d7022018-02-20 11:54:42 -08001520 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001521 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001522 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001523 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001524 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001525 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001526 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001527 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001528 total_callee_video_frames_expected,
1529 kMaxWaitForFramesMs);
1530 bool expectations_correct =
1531 caller()->audio_frames_received() >=
1532 total_caller_audio_frames_expected &&
1533 caller()->min_video_frames_received_per_track() >=
1534 total_caller_video_frames_expected &&
1535 callee()->audio_frames_received() >=
1536 total_callee_audio_frames_expected &&
1537 callee()->min_video_frames_received_per_track() >=
1538 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001539
Seth Hampson2f0d7022018-02-20 11:54:42 -08001540 // After the combined wait, print out a more detailed message upon
1541 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001542 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001543 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001544 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001545 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001546 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001547 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001548 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001549 total_callee_video_frames_expected);
1550
1551 // We want to make sure nothing unexpected was received.
1552 if (media_expectations.caller_audio_expectation_ ==
1553 MediaExpectations::kExpectNoFrames) {
1554 EXPECT_EQ(caller()->audio_frames_received(),
1555 total_caller_audio_frames_expected);
1556 if (caller()->audio_frames_received() !=
1557 total_caller_audio_frames_expected) {
1558 expectations_correct = false;
1559 }
1560 }
1561 if (media_expectations.caller_video_expectation_ ==
1562 MediaExpectations::kExpectNoFrames) {
1563 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1564 total_caller_video_frames_expected);
1565 if (caller()->min_video_frames_received_per_track() !=
1566 total_caller_video_frames_expected) {
1567 expectations_correct = false;
1568 }
1569 }
1570 if (media_expectations.callee_audio_expectation_ ==
1571 MediaExpectations::kExpectNoFrames) {
1572 EXPECT_EQ(callee()->audio_frames_received(),
1573 total_callee_audio_frames_expected);
1574 if (callee()->audio_frames_received() !=
1575 total_callee_audio_frames_expected) {
1576 expectations_correct = false;
1577 }
1578 }
1579 if (media_expectations.callee_video_expectation_ ==
1580 MediaExpectations::kExpectNoFrames) {
1581 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1582 total_callee_video_frames_expected);
1583 if (callee()->min_video_frames_received_per_track() !=
1584 total_callee_video_frames_expected) {
1585 expectations_correct = false;
1586 }
1587 }
1588 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001589 }
1590
Steve Antond91969e2019-05-30 12:27:03 -07001591 void ClosePeerConnections() {
1592 caller()->pc()->Close();
1593 callee()->pc()->Close();
1594 }
1595
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001596 void TestNegotiatedCipherSuite(
1597 const PeerConnectionFactory::Options& caller_options,
1598 const PeerConnectionFactory::Options& callee_options,
1599 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001600 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1601 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001602 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001603 caller()->AddAudioVideoTracks();
1604 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001605 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001606 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001607 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001608 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001609 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00001610 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001611 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1612 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001613 }
1614
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001615 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1616 bool remote_gcm_enabled,
1617 int expected_cipher_suite) {
1618 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001619 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1620 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001621 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001622 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1623 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001624 TestNegotiatedCipherSuite(caller_options, callee_options,
1625 expected_cipher_suite);
1626 }
1627
Seth Hampson2f0d7022018-02-20 11:54:42 -08001628 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001629 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001630
deadbeef1dcb1642017-03-29 21:08:16 -07001631 private:
1632 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001633 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001634 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001635 // |network_thread_| and |worker_thread_| are used by both
1636 // |caller_| and |callee_| so they must be destroyed
1637 // later.
1638 std::unique_ptr<rtc::Thread> network_thread_;
1639 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001640 // The turn servers and turn customizers should be accessed & deleted on the
1641 // network thread to avoid a race with the socket read/write that occurs
1642 // on the network thread.
1643 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1644 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001645 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001646 std::unique_ptr<PeerConnectionWrapper> caller_;
1647 std::unique_ptr<PeerConnectionWrapper> callee_;
1648};
1649
Seth Hampson2f0d7022018-02-20 11:54:42 -08001650class PeerConnectionIntegrationTest
1651 : public PeerConnectionIntegrationBaseTest,
1652 public ::testing::WithParamInterface<SdpSemantics> {
1653 protected:
1654 PeerConnectionIntegrationTest()
1655 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1656};
1657
1658class PeerConnectionIntegrationTestPlanB
1659 : public PeerConnectionIntegrationBaseTest {
1660 protected:
1661 PeerConnectionIntegrationTestPlanB()
1662 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1663};
1664
1665class PeerConnectionIntegrationTestUnifiedPlan
1666 : public PeerConnectionIntegrationBaseTest {
1667 protected:
1668 PeerConnectionIntegrationTestUnifiedPlan()
1669 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1670};
1671
deadbeef1dcb1642017-03-29 21:08:16 -07001672// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1673// includes testing that the callback is invoked if an observer is connected
1674// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001675TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001676 RtpReceiverObserverOnFirstPacketReceived) {
1677 ASSERT_TRUE(CreatePeerConnectionWrappers());
1678 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001679 caller()->AddAudioVideoTracks();
1680 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001681 // Start offer/answer exchange and wait for it to complete.
1682 caller()->CreateAndSetAndSignalOffer();
1683 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1684 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001685 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1686 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001687 // Wait for all "first packet received" callbacks to be fired.
1688 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001689 absl::c_all_of(caller()->rtp_receiver_observers(),
1690 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1691 return o->first_packet_received();
1692 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001693 kMaxWaitForFramesMs);
1694 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001695 absl::c_all_of(callee()->rtp_receiver_observers(),
1696 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1697 return o->first_packet_received();
1698 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001699 kMaxWaitForFramesMs);
1700 // If new observers are set after the first packet was already received, the
1701 // callback should still be invoked.
1702 caller()->ResetRtpReceiverObservers();
1703 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001704 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1705 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001706 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001707 absl::c_all_of(caller()->rtp_receiver_observers(),
1708 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1709 return o->first_packet_received();
1710 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001711 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001712 absl::c_all_of(callee()->rtp_receiver_observers(),
1713 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1714 return o->first_packet_received();
1715 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001716}
1717
1718class DummyDtmfObserver : public DtmfSenderObserverInterface {
1719 public:
1720 DummyDtmfObserver() : completed_(false) {}
1721
1722 // Implements DtmfSenderObserverInterface.
1723 void OnToneChange(const std::string& tone) override {
1724 tones_.push_back(tone);
1725 if (tone.empty()) {
1726 completed_ = true;
1727 }
1728 }
1729
1730 const std::vector<std::string>& tones() const { return tones_; }
1731 bool completed() const { return completed_; }
1732
1733 private:
1734 bool completed_;
1735 std::vector<std::string> tones_;
1736};
1737
1738// Assumes |sender| already has an audio track added and the offer/answer
1739// exchange is done.
1740void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1741 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001742 // We should be able to get a DTMF sender from the local sender.
1743 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1744 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1745 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001746 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001747 dtmf_sender->RegisterObserver(&observer);
1748
1749 // Test the DtmfSender object just created.
1750 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1751 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1752
1753 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1754 std::vector<std::string> tones = {"1", "a", ""};
1755 EXPECT_EQ(tones, observer.tones());
1756 dtmf_sender->UnregisterObserver();
1757 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1758}
1759
1760// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1761// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001762TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001763 ASSERT_TRUE(CreatePeerConnectionWrappers());
1764 ConnectFakeSignaling();
1765 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001766 caller()->AddAudioTrack();
1767 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001768 caller()->CreateAndSetAndSignalOffer();
1769 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001770 // DTLS must finish before the DTMF sender can be used reliably.
1771 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001772 TestDtmfFromSenderToReceiver(caller(), callee());
1773 TestDtmfFromSenderToReceiver(callee(), caller());
1774}
1775
1776// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1777// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001778TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001779 ASSERT_TRUE(CreatePeerConnectionWrappers());
1780 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001781
deadbeef1dcb1642017-03-29 21:08:16 -07001782 // Do normal offer/answer and wait for some frames to be received in each
1783 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001784 caller()->AddAudioVideoTracks();
1785 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001786 caller()->CreateAndSetAndSignalOffer();
1787 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001788 MediaExpectations media_expectations;
1789 media_expectations.ExpectBidirectionalAudioAndVideo();
1790 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001791 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1792 webrtc::kEnumCounterKeyProtocolDtls));
1793 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1794 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001795}
1796
1797// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001798TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001799 PeerConnectionInterface::RTCConfiguration sdes_config;
1800 sdes_config.enable_dtls_srtp.emplace(false);
1801 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1802 ConnectFakeSignaling();
1803
1804 // Do normal offer/answer and wait for some frames to be received in each
1805 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001806 caller()->AddAudioVideoTracks();
1807 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001808 caller()->CreateAndSetAndSignalOffer();
1809 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001810 MediaExpectations media_expectations;
1811 media_expectations.ExpectBidirectionalAudioAndVideo();
1812 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001813 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1814 webrtc::kEnumCounterKeyProtocolSdes));
1815 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1816 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001817}
1818
Steve Anton8c0f7a72017-10-03 10:03:10 -07001819// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1820// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001821TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001822 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1823 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1824 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1825 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1826 return pc->GetRemoteAudioSSLCertificate();
1827 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001828 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1829 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1830 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1831 return pc->GetRemoteAudioSSLCertChain();
1832 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001833
1834 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1835 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1836
1837 // Configure each side with a known certificate so they can be compared later.
1838 PeerConnectionInterface::RTCConfiguration caller_config;
1839 caller_config.enable_dtls_srtp.emplace(true);
1840 caller_config.certificates.push_back(caller_cert);
1841 PeerConnectionInterface::RTCConfiguration callee_config;
1842 callee_config.enable_dtls_srtp.emplace(true);
1843 callee_config.certificates.push_back(callee_cert);
1844 ASSERT_TRUE(
1845 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1846 ConnectFakeSignaling();
1847
1848 // When first initialized, there should not be a remote SSL certificate (and
1849 // calling this method should not crash).
1850 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1851 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001852 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1853 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001854
Steve Anton15324772018-01-16 10:26:49 -08001855 caller()->AddAudioTrack();
1856 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001857 caller()->CreateAndSetAndSignalOffer();
1858 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1859 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1860
1861 // Once DTLS has been connected, each side should return the other's SSL
1862 // certificate when calling GetRemoteAudioSSLCertificate.
1863
1864 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1865 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001866 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001867 caller_remote_cert->ToPEMString());
1868
1869 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1870 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001871 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001872 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001873
1874 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1875 ASSERT_TRUE(caller_remote_cert_chain);
1876 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1877 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001878 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001879 remote_cert->ToPEMString());
1880
1881 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1882 ASSERT_TRUE(callee_remote_cert_chain);
1883 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1884 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001885 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001886 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001887}
1888
deadbeef1dcb1642017-03-29 21:08:16 -07001889// This test sets up a call between two parties with a source resolution of
1890// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001891TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001892 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1893 ASSERT_TRUE(CreatePeerConnectionWrappers());
1894 ConnectFakeSignaling();
1895
Niels Möller5c7efe72018-05-11 10:34:46 +02001896 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1897 webrtc::FakePeriodicVideoSource::Config config;
1898 config.width = 1280;
1899 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001900 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001901 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1902 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001903
1904 // Do normal offer/answer and wait for at least one frame to be received in
1905 // each direction.
1906 caller()->CreateAndSetAndSignalOffer();
1907 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1908 callee()->min_video_frames_received_per_track() > 0,
1909 kMaxWaitForFramesMs);
1910
1911 // Check rendered aspect ratio.
1912 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1913 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1914 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1915 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1916}
1917
1918// This test sets up an one-way call, with media only from caller to
1919// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001920TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001921 ASSERT_TRUE(CreatePeerConnectionWrappers());
1922 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001923 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001924 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001925 MediaExpectations media_expectations;
1926 media_expectations.CalleeExpectsSomeAudioAndVideo();
1927 media_expectations.CallerExpectsNoAudio();
1928 media_expectations.CallerExpectsNoVideo();
1929 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001930}
1931
1932// This test sets up a audio call initially, with the callee rejecting video
1933// initially. Then later the callee decides to upgrade to audio/video, and
1934// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001935TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001936 ASSERT_TRUE(CreatePeerConnectionWrappers());
1937 ConnectFakeSignaling();
1938 // Initially, offer an audio/video stream from the caller, but refuse to
1939 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001940 caller()->AddAudioVideoTracks();
1941 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001942 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1943 PeerConnectionInterface::RTCOfferAnswerOptions options;
1944 options.offer_to_receive_video = 0;
1945 callee()->SetOfferAnswerOptions(options);
1946 } else {
1947 callee()->SetRemoteOfferHandler([this] {
1948 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1949 });
1950 }
deadbeef1dcb1642017-03-29 21:08:16 -07001951 // Do offer/answer and make sure audio is still received end-to-end.
1952 caller()->CreateAndSetAndSignalOffer();
1953 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001954 {
1955 MediaExpectations media_expectations;
1956 media_expectations.ExpectBidirectionalAudio();
1957 media_expectations.ExpectNoVideo();
1958 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1959 }
deadbeef1dcb1642017-03-29 21:08:16 -07001960 // Sanity check that the callee's description has a rejected video section.
1961 ASSERT_NE(nullptr, callee()->pc()->local_description());
1962 const ContentInfo* callee_video_content =
1963 GetFirstVideoContent(callee()->pc()->local_description()->description());
1964 ASSERT_NE(nullptr, callee_video_content);
1965 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001966
deadbeef1dcb1642017-03-29 21:08:16 -07001967 // Now negotiate with video and ensure negotiation succeeds, with video
1968 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001969 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001970 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1971 PeerConnectionInterface::RTCOfferAnswerOptions options;
1972 options.offer_to_receive_video = 1;
1973 callee()->SetOfferAnswerOptions(options);
1974 } else {
1975 callee()->SetRemoteOfferHandler(nullptr);
1976 caller()->SetRemoteOfferHandler([this] {
1977 // The caller creates a new transceiver to receive video on when receiving
1978 // the offer, but by default it is send only.
1979 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001980 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08001981 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
1982 transceivers[2]->receiver()->media_type());
1983 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
1984 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
1985 });
1986 }
deadbeef1dcb1642017-03-29 21:08:16 -07001987 callee()->CreateAndSetAndSignalOffer();
1988 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001989 {
1990 // Expect additional audio frames to be received after the upgrade.
1991 MediaExpectations media_expectations;
1992 media_expectations.ExpectBidirectionalAudioAndVideo();
1993 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1994 }
deadbeef1dcb1642017-03-29 21:08:16 -07001995}
1996
deadbeef4389b4d2017-09-07 09:07:36 -07001997// Simpler than the above test; just add an audio track to an established
1998// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001999TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002000 ASSERT_TRUE(CreatePeerConnectionWrappers());
2001 ConnectFakeSignaling();
2002 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002003 caller()->AddVideoTrack();
2004 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002005 caller()->CreateAndSetAndSignalOffer();
2006 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2007 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002008 caller()->AddAudioTrack();
2009 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002010 caller()->CreateAndSetAndSignalOffer();
2011 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2012 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002013 MediaExpectations media_expectations;
2014 media_expectations.ExpectBidirectionalAudioAndVideo();
2015 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002016}
2017
deadbeef1dcb1642017-03-29 21:08:16 -07002018// This test sets up a call that's transferred to a new caller with a different
2019// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002020TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002021 ASSERT_TRUE(CreatePeerConnectionWrappers());
2022 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002023 caller()->AddAudioVideoTracks();
2024 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002025 caller()->CreateAndSetAndSignalOffer();
2026 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2027
2028 // Keep the original peer around which will still send packets to the
2029 // receiving client. These SRTP packets will be dropped.
2030 std::unique_ptr<PeerConnectionWrapper> original_peer(
2031 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002032 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002033 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2034 // directly above.
2035 original_peer->pc()->Close();
2036
2037 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002038 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002039 caller()->CreateAndSetAndSignalOffer();
2040 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2041 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002042 MediaExpectations media_expectations;
2043 media_expectations.ExpectBidirectionalAudioAndVideo();
2044 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002045}
2046
2047// This test sets up a call that's transferred to a new callee with a different
2048// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002049TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002050 ASSERT_TRUE(CreatePeerConnectionWrappers());
2051 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002052 caller()->AddAudioVideoTracks();
2053 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002054 caller()->CreateAndSetAndSignalOffer();
2055 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2056
2057 // Keep the original peer around which will still send packets to the
2058 // receiving client. These SRTP packets will be dropped.
2059 std::unique_ptr<PeerConnectionWrapper> original_peer(
2060 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002061 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002062 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2063 // directly above.
2064 original_peer->pc()->Close();
2065
2066 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002067 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002068 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2069 caller()->CreateAndSetAndSignalOffer();
2070 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2071 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002072 MediaExpectations media_expectations;
2073 media_expectations.ExpectBidirectionalAudioAndVideo();
2074 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002075}
2076
2077// This test sets up a non-bundled call and negotiates bundling at the same
2078// time as starting an ICE restart. When bundling is in effect in the restart,
2079// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002080TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002081 ASSERT_TRUE(CreatePeerConnectionWrappers());
2082 ConnectFakeSignaling();
2083
Steve Anton15324772018-01-16 10:26:49 -08002084 caller()->AddAudioVideoTracks();
2085 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002086 // Remove the bundle group from the SDP received by the callee.
2087 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2088 desc->RemoveGroupByName("BUNDLE");
2089 });
2090 caller()->CreateAndSetAndSignalOffer();
2091 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002092 {
2093 MediaExpectations media_expectations;
2094 media_expectations.ExpectBidirectionalAudioAndVideo();
2095 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2096 }
deadbeef1dcb1642017-03-29 21:08:16 -07002097 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2098 callee()->SetReceivedSdpMunger(nullptr);
2099 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2100 caller()->CreateAndSetAndSignalOffer();
2101 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2102
2103 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002104 {
2105 MediaExpectations media_expectations;
2106 media_expectations.ExpectBidirectionalAudioAndVideo();
2107 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2108 }
deadbeef1dcb1642017-03-29 21:08:16 -07002109}
2110
2111// Test CVO (Coordination of Video Orientation). If a video source is rotated
2112// and both peers support the CVO RTP header extension, the actual video frames
2113// don't need to be encoded in different resolutions, since the rotation is
2114// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002115TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002116 ASSERT_TRUE(CreatePeerConnectionWrappers());
2117 ConnectFakeSignaling();
2118 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002119 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002120 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002121 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002122 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2123
2124 // Wait for video frames to be received by both sides.
2125 caller()->CreateAndSetAndSignalOffer();
2126 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2127 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2128 callee()->min_video_frames_received_per_track() > 0,
2129 kMaxWaitForFramesMs);
2130
2131 // Ensure that the aspect ratio is unmodified.
2132 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2133 // not just assumed.
2134 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2135 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2136 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2137 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2138 // Ensure that the CVO bits were surfaced to the renderer.
2139 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2140 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2141}
2142
2143// Test that when the CVO extension isn't supported, video is rotated the
2144// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002145TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002146 ASSERT_TRUE(CreatePeerConnectionWrappers());
2147 ConnectFakeSignaling();
2148 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002149 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002150 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002151 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002152 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2153
2154 // Remove the CVO extension from the offered SDP.
2155 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2156 cricket::VideoContentDescription* video =
2157 GetFirstVideoContentDescription(desc);
2158 video->ClearRtpHeaderExtensions();
2159 });
2160 // Wait for video frames to be received by both sides.
2161 caller()->CreateAndSetAndSignalOffer();
2162 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2163 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2164 callee()->min_video_frames_received_per_track() > 0,
2165 kMaxWaitForFramesMs);
2166
2167 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2168 // rotation.
2169 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2170 // not just assumed.
2171 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2172 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2173 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2174 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2175 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2176 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2177 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2178}
2179
deadbeef1dcb1642017-03-29 21:08:16 -07002180// Test that if the answerer rejects the audio m= section, no audio is sent or
2181// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002182TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002183 ASSERT_TRUE(CreatePeerConnectionWrappers());
2184 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002185 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002186 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2187 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2188 // it will reject the audio m= section completely.
2189 PeerConnectionInterface::RTCOfferAnswerOptions options;
2190 options.offer_to_receive_audio = 0;
2191 callee()->SetOfferAnswerOptions(options);
2192 } else {
2193 // Stopping the audio RtpTransceiver will cause the media section to be
2194 // rejected in the answer.
2195 callee()->SetRemoteOfferHandler([this] {
2196 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2197 });
2198 }
Steve Anton15324772018-01-16 10:26:49 -08002199 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002200 // Do offer/answer and wait for successful end-to-end video frames.
2201 caller()->CreateAndSetAndSignalOffer();
2202 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002203 MediaExpectations media_expectations;
2204 media_expectations.ExpectBidirectionalVideo();
2205 media_expectations.ExpectNoAudio();
2206 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2207
deadbeef1dcb1642017-03-29 21:08:16 -07002208 // Sanity check that the callee's description has a rejected audio section.
2209 ASSERT_NE(nullptr, callee()->pc()->local_description());
2210 const ContentInfo* callee_audio_content =
2211 GetFirstAudioContent(callee()->pc()->local_description()->description());
2212 ASSERT_NE(nullptr, callee_audio_content);
2213 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002214 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2215 // The caller's transceiver should have stopped after receiving the answer.
2216 EXPECT_TRUE(caller()
2217 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2218 ->stopped());
2219 }
deadbeef1dcb1642017-03-29 21:08:16 -07002220}
2221
2222// Test that if the answerer rejects the video m= section, no video is sent or
2223// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002224TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002225 ASSERT_TRUE(CreatePeerConnectionWrappers());
2226 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002227 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002228 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2229 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2230 // it will reject the video m= section completely.
2231 PeerConnectionInterface::RTCOfferAnswerOptions options;
2232 options.offer_to_receive_video = 0;
2233 callee()->SetOfferAnswerOptions(options);
2234 } else {
2235 // Stopping the video RtpTransceiver will cause the media section to be
2236 // rejected in the answer.
2237 callee()->SetRemoteOfferHandler([this] {
2238 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2239 });
2240 }
Steve Anton15324772018-01-16 10:26:49 -08002241 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002242 // Do offer/answer and wait for successful end-to-end audio frames.
2243 caller()->CreateAndSetAndSignalOffer();
2244 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002245 MediaExpectations media_expectations;
2246 media_expectations.ExpectBidirectionalAudio();
2247 media_expectations.ExpectNoVideo();
2248 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2249
deadbeef1dcb1642017-03-29 21:08:16 -07002250 // Sanity check that the callee's description has a rejected video section.
2251 ASSERT_NE(nullptr, callee()->pc()->local_description());
2252 const ContentInfo* callee_video_content =
2253 GetFirstVideoContent(callee()->pc()->local_description()->description());
2254 ASSERT_NE(nullptr, callee_video_content);
2255 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002256 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2257 // The caller's transceiver should have stopped after receiving the answer.
2258 EXPECT_TRUE(caller()
2259 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2260 ->stopped());
2261 }
deadbeef1dcb1642017-03-29 21:08:16 -07002262}
2263
2264// Test that if the answerer rejects both audio and video m= sections, nothing
2265// bad happens.
2266// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2267// test anything but the fact that negotiation succeeds, which doesn't mean
2268// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002269TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002270 ASSERT_TRUE(CreatePeerConnectionWrappers());
2271 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002272 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002273 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2274 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2275 // will reject both audio and video m= sections.
2276 PeerConnectionInterface::RTCOfferAnswerOptions options;
2277 options.offer_to_receive_audio = 0;
2278 options.offer_to_receive_video = 0;
2279 callee()->SetOfferAnswerOptions(options);
2280 } else {
2281 callee()->SetRemoteOfferHandler([this] {
2282 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002283 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002284 transceiver->Stop();
2285 }
2286 });
2287 }
deadbeef1dcb1642017-03-29 21:08:16 -07002288 // Do offer/answer and wait for stable signaling state.
2289 caller()->CreateAndSetAndSignalOffer();
2290 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002291
deadbeef1dcb1642017-03-29 21:08:16 -07002292 // Sanity check that the callee's description has rejected m= sections.
2293 ASSERT_NE(nullptr, callee()->pc()->local_description());
2294 const ContentInfo* callee_audio_content =
2295 GetFirstAudioContent(callee()->pc()->local_description()->description());
2296 ASSERT_NE(nullptr, callee_audio_content);
2297 EXPECT_TRUE(callee_audio_content->rejected);
2298 const ContentInfo* callee_video_content =
2299 GetFirstVideoContent(callee()->pc()->local_description()->description());
2300 ASSERT_NE(nullptr, callee_video_content);
2301 EXPECT_TRUE(callee_video_content->rejected);
2302}
2303
2304// This test sets up an audio and video call between two parties. After the
2305// call runs for a while, the caller sends an updated offer with video being
2306// rejected. Once the re-negotiation is done, the video flow should stop and
2307// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002308TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002309 ASSERT_TRUE(CreatePeerConnectionWrappers());
2310 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002311 caller()->AddAudioVideoTracks();
2312 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002313 caller()->CreateAndSetAndSignalOffer();
2314 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002315 {
2316 MediaExpectations media_expectations;
2317 media_expectations.ExpectBidirectionalAudioAndVideo();
2318 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2319 }
deadbeef1dcb1642017-03-29 21:08:16 -07002320 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002321 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2322 caller()->SetGeneratedSdpMunger(
2323 [](cricket::SessionDescription* description) {
2324 for (cricket::ContentInfo& content : description->contents()) {
2325 if (cricket::IsVideoContent(&content)) {
2326 content.rejected = true;
2327 }
2328 }
2329 });
2330 } else {
2331 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2332 }
deadbeef1dcb1642017-03-29 21:08:16 -07002333 caller()->CreateAndSetAndSignalOffer();
2334 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2335
2336 // Sanity check that the caller's description has a rejected video section.
2337 ASSERT_NE(nullptr, caller()->pc()->local_description());
2338 const ContentInfo* caller_video_content =
2339 GetFirstVideoContent(caller()->pc()->local_description()->description());
2340 ASSERT_NE(nullptr, caller_video_content);
2341 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002342 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002343 {
2344 MediaExpectations media_expectations;
2345 media_expectations.ExpectBidirectionalAudio();
2346 media_expectations.ExpectNoVideo();
2347 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2348 }
deadbeef1dcb1642017-03-29 21:08:16 -07002349}
2350
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002351// Do one offer/answer with audio, another that disables it (rejecting the m=
2352// section), and another that re-enables it. Regression test for:
2353// bugs.webrtc.org/6023
2354TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2355 ASSERT_TRUE(CreatePeerConnectionWrappers());
2356 ConnectFakeSignaling();
2357
2358 // Add audio track, do normal offer/answer.
2359 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2360 caller()->CreateLocalAudioTrack();
2361 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2362 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2363 caller()->CreateAndSetAndSignalOffer();
2364 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2365
2366 // Remove audio track, and set offer_to_receive_audio to false to cause the
2367 // m= section to be completely disabled, not just "recvonly".
2368 caller()->pc()->RemoveTrack(sender);
2369 PeerConnectionInterface::RTCOfferAnswerOptions options;
2370 options.offer_to_receive_audio = 0;
2371 caller()->SetOfferAnswerOptions(options);
2372 caller()->CreateAndSetAndSignalOffer();
2373 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2374
2375 // Add the audio track again, expecting negotiation to succeed and frames to
2376 // flow.
2377 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2378 options.offer_to_receive_audio = 1;
2379 caller()->SetOfferAnswerOptions(options);
2380 caller()->CreateAndSetAndSignalOffer();
2381 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2382
2383 MediaExpectations media_expectations;
2384 media_expectations.CalleeExpectsSomeAudio();
2385 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2386}
2387
deadbeef1dcb1642017-03-29 21:08:16 -07002388// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2389// is needed to support legacy endpoints.
2390// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2391// add a test for an end-to-end test without MID signaling either (basically,
2392// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002393TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002394 ASSERT_TRUE(CreatePeerConnectionWrappers());
2395 ConnectFakeSignaling();
2396 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002397 caller()->AddAudioVideoTracks();
2398 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002399 // Remove SSRCs and MSIDs from the received offer SDP.
2400 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002401 caller()->CreateAndSetAndSignalOffer();
2402 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002403 MediaExpectations media_expectations;
2404 media_expectations.ExpectBidirectionalAudioAndVideo();
2405 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002406}
2407
Seth Hampson5897a6e2018-04-03 11:16:33 -07002408// Basic end-to-end test, without SSRC signaling. This means that the track
2409// was created properly and frames are delivered when the MSIDs are communicated
2410// with a=msid lines and no a=ssrc lines.
2411TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2412 EndToEndCallWithoutSsrcSignaling) {
2413 const char kStreamId[] = "streamId";
2414 ASSERT_TRUE(CreatePeerConnectionWrappers());
2415 ConnectFakeSignaling();
2416 // Add just audio tracks.
2417 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2418 callee()->AddAudioTrack();
2419
2420 // Remove SSRCs from the received offer SDP.
2421 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2422 caller()->CreateAndSetAndSignalOffer();
2423 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2424 MediaExpectations media_expectations;
2425 media_expectations.ExpectBidirectionalAudio();
2426 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2427}
2428
Steve Antondf527fd2018-04-27 15:52:03 -07002429// Tests that video flows between multiple video tracks when SSRCs are not
2430// signaled. This exercises the MID RTP header extension which is needed to
2431// demux the incoming video tracks.
2432TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2433 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2434 ASSERT_TRUE(CreatePeerConnectionWrappers());
2435 ConnectFakeSignaling();
2436 caller()->AddVideoTrack();
2437 caller()->AddVideoTrack();
2438 callee()->AddVideoTrack();
2439 callee()->AddVideoTrack();
2440
2441 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2442 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2443 caller()->CreateAndSetAndSignalOffer();
2444 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2445 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2446 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2447
2448 // Expect video to be received in both directions on both tracks.
2449 MediaExpectations media_expectations;
2450 media_expectations.ExpectBidirectionalVideo();
2451 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2452}
2453
Henrik Boström5b147782018-12-04 11:25:05 +01002454TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2455 ASSERT_TRUE(CreatePeerConnectionWrappers());
2456 ConnectFakeSignaling();
2457 caller()->AddAudioTrack();
2458 caller()->AddVideoTrack();
2459 caller()->CreateAndSetAndSignalOffer();
2460 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2461 auto callee_receivers = callee()->pc()->GetReceivers();
2462 ASSERT_EQ(2u, callee_receivers.size());
2463 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2464 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2465}
2466
2467TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2468 ASSERT_TRUE(CreatePeerConnectionWrappers());
2469 ConnectFakeSignaling();
2470 caller()->AddAudioTrack();
2471 caller()->AddVideoTrack();
2472 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2473 caller()->CreateAndSetAndSignalOffer();
2474 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2475 auto callee_receivers = callee()->pc()->GetReceivers();
2476 ASSERT_EQ(2u, callee_receivers.size());
2477 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2478 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2479 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2480 callee_receivers[1]->stream_ids()[0]);
2481 EXPECT_EQ(callee_receivers[0]->streams()[0],
2482 callee_receivers[1]->streams()[0]);
2483}
2484
deadbeef1dcb1642017-03-29 21:08:16 -07002485// Test that if two video tracks are sent (from caller to callee, in this test),
2486// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002487TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002488 ASSERT_TRUE(CreatePeerConnectionWrappers());
2489 ConnectFakeSignaling();
2490 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002491 caller()->AddAudioVideoTracks();
2492 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002493 caller()->CreateAndSetAndSignalOffer();
2494 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002495 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002496
2497 MediaExpectations media_expectations;
2498 media_expectations.CalleeExpectsSomeAudioAndVideo();
2499 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002500}
2501
2502static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2503 bool first = true;
2504 for (cricket::ContentInfo& content : desc->contents()) {
2505 if (first) {
2506 first = false;
2507 continue;
2508 }
2509 content.bundle_only = true;
2510 }
2511 first = true;
2512 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2513 if (first) {
2514 first = false;
2515 continue;
2516 }
2517 transport.description.ice_ufrag.clear();
2518 transport.description.ice_pwd.clear();
2519 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2520 transport.description.identity_fingerprint.reset(nullptr);
2521 }
2522}
2523
2524// Test that if applying a true "max bundle" offer, which uses ports of 0,
2525// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2526// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2527// successfully and media flows.
2528// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2529// TODO(deadbeef): Won't need this test once we start generating actual
2530// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002531TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002532 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2533 ASSERT_TRUE(CreatePeerConnectionWrappers());
2534 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002535 caller()->AddAudioVideoTracks();
2536 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002537 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2538 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2539 // but the first m= section.
2540 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2541 caller()->CreateAndSetAndSignalOffer();
2542 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002543 MediaExpectations media_expectations;
2544 media_expectations.ExpectBidirectionalAudioAndVideo();
2545 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002546}
2547
2548// Test that we can receive the audio output level from a remote audio track.
2549// TODO(deadbeef): Use a fake audio source and verify that the output level is
2550// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002551TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002552 ASSERT_TRUE(CreatePeerConnectionWrappers());
2553 ConnectFakeSignaling();
2554 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002555 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002556 caller()->CreateAndSetAndSignalOffer();
2557 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2558
2559 // Get the audio output level stats. Note that the level is not available
2560 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002561 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002562 kMaxWaitForFramesMs);
2563}
2564
2565// Test that an audio input level is reported.
2566// TODO(deadbeef): Use a fake audio source and verify that the input level is
2567// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002568TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002569 ASSERT_TRUE(CreatePeerConnectionWrappers());
2570 ConnectFakeSignaling();
2571 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002572 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002573 caller()->CreateAndSetAndSignalOffer();
2574 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2575
2576 // Get the audio input level stats. The level should be available very
2577 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002578 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002579 kMaxWaitForStatsMs);
2580}
2581
2582// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002583TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002584 ASSERT_TRUE(CreatePeerConnectionWrappers());
2585 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002586 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002587 // Do offer/answer, wait for the callee to receive some frames.
2588 caller()->CreateAndSetAndSignalOffer();
2589 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002590
2591 MediaExpectations media_expectations;
2592 media_expectations.CalleeExpectsSomeAudioAndVideo();
2593 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002594
2595 // Get a handle to the remote tracks created, so they can be used as GetStats
2596 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002597 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002598 // We received frames, so we definitely should have nonzero "received bytes"
2599 // stats at this point.
2600 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2601 0);
2602 }
deadbeef1dcb1642017-03-29 21:08:16 -07002603}
2604
2605// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002606TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002607 ASSERT_TRUE(CreatePeerConnectionWrappers());
2608 ConnectFakeSignaling();
2609 auto audio_track = caller()->CreateLocalAudioTrack();
2610 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002611 caller()->AddTrack(audio_track);
2612 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002613 // Do offer/answer, wait for the callee to receive some frames.
2614 caller()->CreateAndSetAndSignalOffer();
2615 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002616 MediaExpectations media_expectations;
2617 media_expectations.CalleeExpectsSomeAudioAndVideo();
2618 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002619
2620 // The callee received frames, so we definitely should have nonzero "sent
2621 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002622 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2623 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2624}
2625
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002626// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002627TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002628 ASSERT_TRUE(CreatePeerConnectionWrappers());
2629 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002630 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002631
Steve Anton15324772018-01-16 10:26:49 -08002632 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002633
2634 // Do offer/answer, wait for the callee to receive some frames.
2635 caller()->CreateAndSetAndSignalOffer();
2636 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2637
2638 // Get the remote audio track created on the receiver, so they can be used as
2639 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002640 auto receivers = callee()->pc()->GetReceivers();
2641 ASSERT_EQ(1u, receivers.size());
2642 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002643
2644 // Get the audio output level stats. Note that the level is not available
2645 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002646 EXPECT_TRUE_WAIT(
2647 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2648 0,
2649 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002650}
2651
Steve Antona41959e2018-11-28 11:15:33 -08002652// Test that the track ID is associated with all local and remote SSRC stats
2653// using the old GetStats() and more than 1 audio and more than 1 video track.
2654// This is a regression test for crbug.com/906988
2655TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2656 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2657 ASSERT_TRUE(CreatePeerConnectionWrappers());
2658 ConnectFakeSignaling();
2659 auto audio_sender_1 = caller()->AddAudioTrack();
2660 auto video_sender_1 = caller()->AddVideoTrack();
2661 auto audio_sender_2 = caller()->AddAudioTrack();
2662 auto video_sender_2 = caller()->AddVideoTrack();
2663 caller()->CreateAndSetAndSignalOffer();
2664 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2665
2666 MediaExpectations media_expectations;
2667 media_expectations.CalleeExpectsSomeAudioAndVideo();
2668 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2669
2670 std::vector<std::string> track_ids = {
2671 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2672 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2673
2674 auto caller_stats = caller()->OldGetStats();
2675 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2676 auto callee_stats = callee()->OldGetStats();
2677 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2678}
2679
Steve Antonffa6ce42018-11-30 09:26:08 -08002680// Test that the new GetStats() returns stats for all outgoing/incoming streams
2681// with the correct track IDs if there are more than one audio and more than one
2682// video senders/receivers.
2683TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2684 ASSERT_TRUE(CreatePeerConnectionWrappers());
2685 ConnectFakeSignaling();
2686 auto audio_sender_1 = caller()->AddAudioTrack();
2687 auto video_sender_1 = caller()->AddVideoTrack();
2688 auto audio_sender_2 = caller()->AddAudioTrack();
2689 auto video_sender_2 = caller()->AddVideoTrack();
2690 caller()->CreateAndSetAndSignalOffer();
2691 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2692
2693 MediaExpectations media_expectations;
2694 media_expectations.CalleeExpectsSomeAudioAndVideo();
2695 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2696
2697 std::vector<std::string> track_ids = {
2698 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2699 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2700
2701 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2702 caller()->NewGetStats();
2703 ASSERT_TRUE(caller_report);
2704 auto outbound_stream_stats =
2705 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2706 ASSERT_EQ(4u, outbound_stream_stats.size());
2707 std::vector<std::string> outbound_track_ids;
2708 for (const auto& stat : outbound_stream_stats) {
2709 ASSERT_TRUE(stat->bytes_sent.is_defined());
2710 EXPECT_LT(0u, *stat->bytes_sent);
2711 ASSERT_TRUE(stat->track_id.is_defined());
2712 const auto* track_stat =
2713 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2714 ASSERT_TRUE(track_stat);
2715 outbound_track_ids.push_back(*track_stat->track_identifier);
2716 }
2717 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2718
2719 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2720 callee()->NewGetStats();
2721 ASSERT_TRUE(callee_report);
2722 auto inbound_stream_stats =
2723 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2724 ASSERT_EQ(4u, inbound_stream_stats.size());
2725 std::vector<std::string> inbound_track_ids;
2726 for (const auto& stat : inbound_stream_stats) {
2727 ASSERT_TRUE(stat->bytes_received.is_defined());
2728 EXPECT_LT(0u, *stat->bytes_received);
2729 ASSERT_TRUE(stat->track_id.is_defined());
2730 const auto* track_stat =
2731 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2732 ASSERT_TRUE(track_stat);
2733 inbound_track_ids.push_back(*track_stat->track_identifier);
2734 }
2735 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2736}
2737
2738// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002739// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2740// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002741TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002742 GetStatsForUnsignaledStreamWithNewStatsApi) {
2743 ASSERT_TRUE(CreatePeerConnectionWrappers());
2744 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002745 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002746 // Remove SSRCs and MSIDs from the received offer SDP.
2747 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2748 caller()->CreateAndSetAndSignalOffer();
2749 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002750 MediaExpectations media_expectations;
2751 media_expectations.CalleeExpectsSomeAudio(1);
2752 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002753
2754 // We received a frame, so we should have nonzero "bytes received" stats for
2755 // the unsignaled stream, if stats are working for it.
2756 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2757 callee()->NewGetStats();
2758 ASSERT_NE(nullptr, report);
2759 auto inbound_stream_stats =
2760 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2761 ASSERT_EQ(1U, inbound_stream_stats.size());
2762 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2763 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002764 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2765}
2766
Taylor Brandstettera4653442018-06-19 09:44:26 -07002767// Same as above but for the legacy stats implementation.
2768TEST_P(PeerConnectionIntegrationTest,
2769 GetStatsForUnsignaledStreamWithOldStatsApi) {
2770 ASSERT_TRUE(CreatePeerConnectionWrappers());
2771 ConnectFakeSignaling();
2772 caller()->AddAudioTrack();
2773 // Remove SSRCs and MSIDs from the received offer SDP.
2774 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2775 caller()->CreateAndSetAndSignalOffer();
2776 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2777
2778 // Note that, since the old stats implementation associates SSRCs with tracks
2779 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2780 // associated track ID. So we can't use the track "selector" argument.
2781 //
2782 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2783 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002784 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002785 kDefaultTimeout);
2786}
2787
zhihuangf8164932017-05-19 13:09:47 -07002788// Test that we can successfully get the media related stats (audio level
2789// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002790TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002791 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2792 ASSERT_TRUE(CreatePeerConnectionWrappers());
2793 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002794 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -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 media_expectations.CalleeExpectsSomeVideo(1);
2802 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002803
2804 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2805 callee()->NewGetStats();
2806 ASSERT_NE(nullptr, report);
2807
2808 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2809 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2810 ASSERT_GE(audio_index, 0);
2811 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002812}
2813
deadbeef4e2deab2017-09-20 13:56:21 -07002814// Helper for test below.
2815void ModifySsrcs(cricket::SessionDescription* desc) {
2816 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002817 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002818 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002819 for (uint32_t& ssrc : stream.ssrcs) {
2820 ssrc = rtc::CreateRandomId();
2821 }
2822 }
2823 }
2824}
2825
2826// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2827// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2828// This should result in two "RTCInboundRTPStreamStats", but only one
2829// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2830// being reset to 0 once the SSRC change occurs.
2831//
2832// Regression test for this bug:
2833// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2834//
2835// The bug causes the track stats to only represent one of the two streams:
2836// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2837// that the track stat counters would reset to 0 when the new stream is
2838// received, and a 50% chance that they'll stop updating (while
2839// "concealed_samples" continues increasing, due to silence being generated for
2840// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002841TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002842 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002843 ASSERT_TRUE(CreatePeerConnectionWrappers());
2844 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002845 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002846 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2847 // that doesn't signal SSRCs (from the callee's perspective).
2848 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2849 caller()->CreateAndSetAndSignalOffer();
2850 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2851 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002852 {
2853 MediaExpectations media_expectations;
2854 media_expectations.CalleeExpectsSomeAudio(50);
2855 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2856 }
deadbeef4e2deab2017-09-20 13:56:21 -07002857 // Some audio frames were received, so we should have nonzero "samples
2858 // received" for the track.
2859 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2860 callee()->NewGetStats();
2861 ASSERT_NE(nullptr, report);
2862 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2863 ASSERT_EQ(1U, track_stats.size());
2864 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2865 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2866 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2867
2868 // Create a new offer and munge it to cause the caller to use a new SSRC.
2869 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2870 caller()->CreateAndSetAndSignalOffer();
2871 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2872 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2873 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002874 {
2875 MediaExpectations media_expectations;
2876 media_expectations.CalleeExpectsSomeAudio(25);
2877 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2878 }
deadbeef4e2deab2017-09-20 13:56:21 -07002879
2880 report = callee()->NewGetStats();
2881 ASSERT_NE(nullptr, report);
2882 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2883 ASSERT_EQ(1U, track_stats.size());
2884 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2885 // The "total samples received" stat should only be greater than it was
2886 // before.
2887 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2888 // Right now, the new SSRC will cause the counters to reset to 0.
2889 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2890
2891 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002892 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002893 // good sign that we're seeing stats from the old stream that's no longer
2894 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002895 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002896 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2897 EXPECT_LT(*track_stats[0]->concealed_samples,
2898 *track_stats[0]->total_samples_received *
2899 kAcceptableConcealedSamplesPercentage);
2900
2901 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2902 // sanity check that the SSRC really changed.
2903 // TODO(deadbeef): This isn't working right now, because we're not returning
2904 // *any* stats for the inactive stream. Uncomment when the bug is completely
2905 // fixed.
2906 // auto inbound_stream_stats =
2907 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2908 // ASSERT_EQ(2U, inbound_stream_stats.size());
2909}
2910
deadbeef1dcb1642017-03-29 21:08:16 -07002911// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002912TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002913 PeerConnectionFactory::Options dtls_10_options;
2914 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2915 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2916 dtls_10_options));
2917 ConnectFakeSignaling();
2918 // Do normal offer/answer and wait for some frames to be received in each
2919 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002920 caller()->AddAudioVideoTracks();
2921 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002922 caller()->CreateAndSetAndSignalOffer();
2923 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002924 MediaExpectations media_expectations;
2925 media_expectations.ExpectBidirectionalAudioAndVideo();
2926 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002927}
2928
2929// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002930TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002931 PeerConnectionFactory::Options dtls_10_options;
2932 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2933 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2934 dtls_10_options));
2935 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002936 caller()->AddAudioVideoTracks();
2937 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002938 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002939 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002940 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002941 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002942 kDefaultTimeout);
2943 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002944 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002945 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002946 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002947 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2948 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002949}
2950
2951// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002952TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002953 PeerConnectionFactory::Options dtls_12_options;
2954 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2955 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2956 dtls_12_options));
2957 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002958 caller()->AddAudioVideoTracks();
2959 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002960 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002961 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002962 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002963 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002964 kDefaultTimeout);
2965 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002966 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002967 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002968 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002969 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2970 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002971}
2972
2973// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2974// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002975TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002976 PeerConnectionFactory::Options caller_options;
2977 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2978 PeerConnectionFactory::Options callee_options;
2979 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2980 ASSERT_TRUE(
2981 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2982 ConnectFakeSignaling();
2983 // Do normal offer/answer and wait for some frames to be received in each
2984 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002985 caller()->AddAudioVideoTracks();
2986 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002987 caller()->CreateAndSetAndSignalOffer();
2988 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002989 MediaExpectations media_expectations;
2990 media_expectations.ExpectBidirectionalAudioAndVideo();
2991 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002992}
2993
2994// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2995// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002996TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07002997 PeerConnectionFactory::Options caller_options;
2998 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2999 PeerConnectionFactory::Options callee_options;
3000 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3001 ASSERT_TRUE(
3002 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3003 ConnectFakeSignaling();
3004 // Do normal offer/answer and wait for some frames to be received in each
3005 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003006 caller()->AddAudioVideoTracks();
3007 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003008 caller()->CreateAndSetAndSignalOffer();
3009 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003010 MediaExpectations media_expectations;
3011 media_expectations.ExpectBidirectionalAudioAndVideo();
3012 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003013}
3014
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003015// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3016// works as expected; the cipher should only be used if enabled by both sides.
3017TEST_P(PeerConnectionIntegrationTest,
3018 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3019 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003020 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003021 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003022 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3023 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003024 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3025 TestNegotiatedCipherSuite(caller_options, callee_options,
3026 expected_cipher_suite);
3027}
3028
3029TEST_P(PeerConnectionIntegrationTest,
3030 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3031 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003032 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3033 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003034 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003035 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003036 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3037 TestNegotiatedCipherSuite(caller_options, callee_options,
3038 expected_cipher_suite);
3039}
3040
3041TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3042 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003043 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003044 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003045 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003046 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3047 TestNegotiatedCipherSuite(caller_options, callee_options,
3048 expected_cipher_suite);
3049}
3050
deadbeef1dcb1642017-03-29 21:08:16 -07003051// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003052TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003053 bool local_gcm_enabled = false;
3054 bool remote_gcm_enabled = false;
3055 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3056 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3057 expected_cipher_suite);
3058}
3059
3060// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003061TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003062 bool local_gcm_enabled = true;
3063 bool remote_gcm_enabled = true;
3064 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3065 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3066 expected_cipher_suite);
3067}
3068
3069// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003070TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003071 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
3072 bool local_gcm_enabled = true;
3073 bool remote_gcm_enabled = false;
3074 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3075 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3076 expected_cipher_suite);
3077}
3078
3079// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003080TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003081 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
3082 bool local_gcm_enabled = false;
3083 bool remote_gcm_enabled = true;
3084 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3085 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3086 expected_cipher_suite);
3087}
3088
deadbeef7914b8c2017-04-21 03:23:33 -07003089// Verify that media can be transmitted end-to-end when GCM crypto suites are
3090// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3091// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3092// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003093TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003094 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003095 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07003096 ASSERT_TRUE(
3097 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3098 ConnectFakeSignaling();
3099 // Do normal offer/answer and wait for some frames to be received in each
3100 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003101 caller()->AddAudioVideoTracks();
3102 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003103 caller()->CreateAndSetAndSignalOffer();
3104 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003105 MediaExpectations media_expectations;
3106 media_expectations.ExpectBidirectionalAudioAndVideo();
3107 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003108}
3109
deadbeef1dcb1642017-03-29 21:08:16 -07003110// This test sets up a call between two parties with audio, video and an RTP
3111// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003112TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003113 PeerConnectionInterface::RTCConfiguration rtc_config;
3114 rtc_config.enable_rtp_data_channel = true;
3115 rtc_config.enable_dtls_srtp = false;
3116 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003117 ConnectFakeSignaling();
3118 // Expect that data channel created on caller side will show up for callee as
3119 // well.
3120 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003121 caller()->AddAudioVideoTracks();
3122 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003123 caller()->CreateAndSetAndSignalOffer();
3124 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3125 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003126 MediaExpectations media_expectations;
3127 media_expectations.ExpectBidirectionalAudioAndVideo();
3128 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003129 ASSERT_NE(nullptr, caller()->data_channel());
3130 ASSERT_NE(nullptr, callee()->data_channel());
3131 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3132 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3133
3134 // Ensure data can be sent in both directions.
3135 std::string data = "hello world";
3136 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3137 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3138 kDefaultTimeout);
3139 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3140 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3141 kDefaultTimeout);
3142}
3143
3144// Ensure that an RTP data channel is signaled as closed for the caller when
3145// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003146TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003147 RtpDataChannelSignaledClosedInCalleeOffer) {
3148 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003149 PeerConnectionInterface::RTCConfiguration rtc_config;
3150 rtc_config.enable_rtp_data_channel = true;
3151 rtc_config.enable_dtls_srtp = false;
3152 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003153 ConnectFakeSignaling();
3154 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003155 caller()->AddAudioVideoTracks();
3156 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003157 caller()->CreateAndSetAndSignalOffer();
3158 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3159 ASSERT_NE(nullptr, caller()->data_channel());
3160 ASSERT_NE(nullptr, callee()->data_channel());
3161 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3162 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3163
3164 // Close the data channel on the callee, and do an updated offer/answer.
3165 callee()->data_channel()->Close();
3166 callee()->CreateAndSetAndSignalOffer();
3167 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3168 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3169 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3170}
3171
3172// Tests that data is buffered in an RTP data channel until an observer is
3173// registered for it.
3174//
3175// NOTE: RTP data channels can receive data before the underlying
3176// transport has detected that a channel is writable and thus data can be
3177// received before the data channel state changes to open. That is hard to test
3178// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003179TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003180 DataBufferedUntilRtpDataChannelObserverRegistered) {
3181 // Use fake clock and simulated network delay so that we predictably can wait
3182 // until an SCTP message has been delivered without "sleep()"ing.
3183 rtc::ScopedFakeClock fake_clock;
3184 // Some things use a time of "0" as a special value, so we need to start out
3185 // the fake clock at a nonzero time.
3186 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003187 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003188 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3189 virtual_socket_server()->UpdateDelayDistribution();
3190
Niels Möllerf06f9232018-08-07 12:32:18 +02003191 PeerConnectionInterface::RTCConfiguration rtc_config;
3192 rtc_config.enable_rtp_data_channel = true;
3193 rtc_config.enable_dtls_srtp = false;
3194 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003195 ConnectFakeSignaling();
3196 caller()->CreateDataChannel();
3197 caller()->CreateAndSetAndSignalOffer();
3198 ASSERT_TRUE(caller()->data_channel() != nullptr);
3199 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3200 kDefaultTimeout, fake_clock);
3201 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3202 kDefaultTimeout, fake_clock);
3203 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3204 callee()->data_channel()->state(), kDefaultTimeout,
3205 fake_clock);
3206
3207 // Unregister the observer which is normally automatically registered.
3208 callee()->data_channel()->UnregisterObserver();
3209 // Send data and advance fake clock until it should have been received.
3210 std::string data = "hello world";
3211 caller()->data_channel()->Send(DataBuffer(data));
3212 SIMULATED_WAIT(false, 50, fake_clock);
3213
3214 // Attach data channel and expect data to be received immediately. Note that
3215 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3216 // further, but data can be received even if the callback is asynchronous.
3217 MockDataChannelObserver new_observer(callee()->data_channel());
3218 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3219 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003220 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3221 // If this is not done a DCHECK can be hit in ports.cc, because a large
3222 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07003223 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07003224}
3225
3226// This test sets up a call between two parties with audio, video and but only
3227// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003228TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003229 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3230 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003231 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003232 rtc_config_1.enable_dtls_srtp = false;
3233 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3234 rtc_config_2.enable_dtls_srtp = false;
3235 rtc_config_2.enable_dtls_srtp = false;
3236 ASSERT_TRUE(
3237 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003238 ConnectFakeSignaling();
3239 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003240 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003241 caller()->AddAudioVideoTracks();
3242 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003243 caller()->CreateAndSetAndSignalOffer();
3244 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3245 // The caller should still have a data channel, but it should be closed, and
3246 // one should ever have been created for the callee.
3247 EXPECT_TRUE(caller()->data_channel() != nullptr);
3248 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3249 EXPECT_EQ(nullptr, callee()->data_channel());
3250}
3251
3252// This test sets up a call between two parties with audio, and video. When
3253// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003254TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003255 PeerConnectionInterface::RTCConfiguration rtc_config;
3256 rtc_config.enable_rtp_data_channel = true;
3257 rtc_config.enable_dtls_srtp = false;
3258 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003259 ConnectFakeSignaling();
3260 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003261 caller()->AddAudioVideoTracks();
3262 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003263 caller()->CreateAndSetAndSignalOffer();
3264 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3265 // Create data channel and do new offer and answer.
3266 caller()->CreateDataChannel();
3267 caller()->CreateAndSetAndSignalOffer();
3268 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3269 ASSERT_NE(nullptr, caller()->data_channel());
3270 ASSERT_NE(nullptr, callee()->data_channel());
3271 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3272 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3273 // Ensure data can be sent in both directions.
3274 std::string data = "hello world";
3275 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3276 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3277 kDefaultTimeout);
3278 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3279 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3280 kDefaultTimeout);
3281}
3282
3283#ifdef HAVE_SCTP
3284
3285// This test sets up a call between two parties with audio, video and an SCTP
3286// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003287TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003288 ASSERT_TRUE(CreatePeerConnectionWrappers());
3289 ConnectFakeSignaling();
3290 // Expect that data channel created on caller side will show up for callee as
3291 // well.
3292 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003293 caller()->AddAudioVideoTracks();
3294 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003295 caller()->CreateAndSetAndSignalOffer();
3296 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3297 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003298 MediaExpectations media_expectations;
3299 media_expectations.ExpectBidirectionalAudioAndVideo();
3300 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003301 // Caller data channel should already exist (it created one). Callee data
3302 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3303 ASSERT_NE(nullptr, caller()->data_channel());
3304 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3305 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3306 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3307
3308 // Ensure data can be sent in both directions.
3309 std::string data = "hello world";
3310 caller()->data_channel()->Send(DataBuffer(data));
3311 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3312 kDefaultTimeout);
3313 callee()->data_channel()->Send(DataBuffer(data));
3314 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3315 kDefaultTimeout);
3316}
3317
3318// Ensure that when the callee closes an SCTP data channel, the closing
3319// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003320TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003321 // Same procedure as above test.
3322 ASSERT_TRUE(CreatePeerConnectionWrappers());
3323 ConnectFakeSignaling();
3324 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003325 caller()->AddAudioVideoTracks();
3326 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003327 caller()->CreateAndSetAndSignalOffer();
3328 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3329 ASSERT_NE(nullptr, caller()->data_channel());
3330 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3331 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3332 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3333
3334 // Close the data channel on the callee side, and wait for it to reach the
3335 // "closed" state on both sides.
3336 callee()->data_channel()->Close();
3337 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3338 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3339}
3340
Seth Hampson2f0d7022018-02-20 11:54:42 -08003341TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003342 ASSERT_TRUE(CreatePeerConnectionWrappers());
3343 ConnectFakeSignaling();
3344 webrtc::DataChannelInit init;
3345 init.id = 53;
3346 init.maxRetransmits = 52;
3347 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003348 caller()->AddAudioVideoTracks();
3349 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003350 caller()->CreateAndSetAndSignalOffer();
3351 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003352 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3353 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003354 // Since "negotiated" is false, the "id" parameter should be ignored.
3355 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003356 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3357 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3358 EXPECT_FALSE(callee()->data_channel()->negotiated());
3359}
3360
deadbeef1dcb1642017-03-29 21:08:16 -07003361// Test usrsctp's ability to process unordered data stream, where data actually
3362// arrives out of order using simulated delays. Previously there have been some
3363// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003364TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003365 // Introduce random network delays.
3366 // Otherwise it's not a true "unordered" test.
3367 virtual_socket_server()->set_delay_mean(20);
3368 virtual_socket_server()->set_delay_stddev(5);
3369 virtual_socket_server()->UpdateDelayDistribution();
3370 // Normal procedure, but with unordered data channel config.
3371 ASSERT_TRUE(CreatePeerConnectionWrappers());
3372 ConnectFakeSignaling();
3373 webrtc::DataChannelInit init;
3374 init.ordered = false;
3375 caller()->CreateDataChannel(&init);
3376 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 static constexpr int kNumMessages = 100;
3384 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3385 static constexpr size_t kMaxMessageSize = 4096;
3386 // Create and send random messages.
3387 std::vector<std::string> sent_messages;
3388 for (int i = 0; i < kNumMessages; ++i) {
3389 size_t length =
3390 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3391 std::string message;
3392 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3393 caller()->data_channel()->Send(DataBuffer(message));
3394 callee()->data_channel()->Send(DataBuffer(message));
3395 sent_messages.push_back(message);
3396 }
3397
3398 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003399 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003400 caller()->data_observer()->received_message_count(),
3401 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003402 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003403 callee()->data_observer()->received_message_count(),
3404 kDefaultTimeout);
3405
3406 // Sort and compare to make sure none of the messages were corrupted.
3407 std::vector<std::string> caller_received_messages =
3408 caller()->data_observer()->messages();
3409 std::vector<std::string> callee_received_messages =
3410 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003411 absl::c_sort(sent_messages);
3412 absl::c_sort(caller_received_messages);
3413 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003414 EXPECT_EQ(sent_messages, caller_received_messages);
3415 EXPECT_EQ(sent_messages, callee_received_messages);
3416}
3417
3418// This test sets up a call between two parties with audio, and video. When
3419// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003420TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003421 ASSERT_TRUE(CreatePeerConnectionWrappers());
3422 ConnectFakeSignaling();
3423 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003424 caller()->AddAudioVideoTracks();
3425 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003426 caller()->CreateAndSetAndSignalOffer();
3427 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3428 // Create data channel and do new offer and answer.
3429 caller()->CreateDataChannel();
3430 caller()->CreateAndSetAndSignalOffer();
3431 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3432 // Caller data channel should already exist (it created one). Callee data
3433 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3434 ASSERT_NE(nullptr, caller()->data_channel());
3435 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3436 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3437 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3438 // Ensure data can be sent in both directions.
3439 std::string data = "hello world";
3440 caller()->data_channel()->Send(DataBuffer(data));
3441 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3442 kDefaultTimeout);
3443 callee()->data_channel()->Send(DataBuffer(data));
3444 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3445 kDefaultTimeout);
3446}
3447
deadbeef7914b8c2017-04-21 03:23:33 -07003448// Set up a connection initially just using SCTP data channels, later upgrading
3449// to audio/video, ensuring frames are received end-to-end. Effectively the
3450// inverse of the test above.
3451// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003452TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003453 ASSERT_TRUE(CreatePeerConnectionWrappers());
3454 ConnectFakeSignaling();
3455 // Do initial offer/answer with just data channel.
3456 caller()->CreateDataChannel();
3457 caller()->CreateAndSetAndSignalOffer();
3458 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3459 // Wait until data can be sent over the data channel.
3460 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3461 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3462 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3463
3464 // Do subsequent offer/answer with two-way audio and video. Audio and video
3465 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003466 caller()->AddAudioVideoTracks();
3467 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003468 caller()->CreateAndSetAndSignalOffer();
3469 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003470 MediaExpectations media_expectations;
3471 media_expectations.ExpectBidirectionalAudioAndVideo();
3472 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003473}
3474
deadbeef8b7e9ad2017-05-25 09:38:55 -07003475static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003476 cricket::SctpDataContentDescription* dcd_offer =
3477 GetFirstSctpDataContentDescription(desc);
Steve Antonb1c1de12017-12-21 15:14:30 -08003478 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003479 dcd_offer->set_use_sctpmap(false);
3480 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3481}
3482
3483// Test that the data channel works when a spec-compliant SCTP m= section is
3484// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3485// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003486TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003487 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3488 ASSERT_TRUE(CreatePeerConnectionWrappers());
3489 ConnectFakeSignaling();
3490 caller()->CreateDataChannel();
3491 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3492 caller()->CreateAndSetAndSignalOffer();
3493 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3494 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3495 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3496 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3497
3498 // Ensure data can be sent in both directions.
3499 std::string data = "hello world";
3500 caller()->data_channel()->Send(DataBuffer(data));
3501 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3502 kDefaultTimeout);
3503 callee()->data_channel()->Send(DataBuffer(data));
3504 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3505 kDefaultTimeout);
3506}
3507
deadbeef1dcb1642017-03-29 21:08:16 -07003508#endif // HAVE_SCTP
3509
Bjorn Mellema2eb0a72018-11-09 10:13:51 -08003510// This test sets up a call between two parties with a media transport data
3511// channel.
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003512TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelEndToEnd) {
3513 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003514 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3515 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003516 rtc_config.use_media_transport_for_data_channels = true;
3517 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3518 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3519 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3520 loopback_media_transports()->second_factory()));
3521 ConnectFakeSignaling();
3522
3523 // Expect that data channel created on caller side will show up for callee as
3524 // well.
3525 caller()->CreateDataChannel();
3526 caller()->CreateAndSetAndSignalOffer();
3527 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3528
3529 // Ensure that the media transport is ready.
3530 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3531 loopback_media_transports()->FlushAsyncInvokes();
3532
3533 // Caller data channel should already exist (it created one). Callee data
3534 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3535 ASSERT_NE(nullptr, caller()->data_channel());
3536 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3537 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3538 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3539
3540 // Ensure data can be sent in both directions.
3541 std::string data = "hello world";
3542 caller()->data_channel()->Send(DataBuffer(data));
3543 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3544 kDefaultTimeout);
3545 callee()->data_channel()->Send(DataBuffer(data));
3546 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3547 kDefaultTimeout);
3548}
3549
3550// Ensure that when the callee closes a media transport data channel, the
3551// closing procedure results in the data channel being closed for the caller
3552// as well.
3553TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelCalleeCloses) {
3554 PeerConnectionInterface::RTCConfiguration rtc_config;
3555 rtc_config.use_media_transport_for_data_channels = true;
3556 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3557 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3558 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3559 loopback_media_transports()->second_factory()));
3560 ConnectFakeSignaling();
3561
3562 // Create a data channel on the caller and signal it to the callee.
3563 caller()->CreateDataChannel();
3564 caller()->CreateAndSetAndSignalOffer();
3565 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3566
3567 // Ensure that the media transport is ready.
3568 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3569 loopback_media_transports()->FlushAsyncInvokes();
3570
3571 // Data channels exist and open on both ends of the connection.
3572 ASSERT_NE(nullptr, caller()->data_channel());
3573 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3574 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3575 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3576
3577 // Close the data channel on the callee side, and wait for it to reach the
3578 // "closed" state on both sides.
3579 callee()->data_channel()->Close();
3580 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3581 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3582}
3583
3584TEST_P(PeerConnectionIntegrationTest,
3585 MediaTransportDataChannelConfigSentToOtherSide) {
3586 PeerConnectionInterface::RTCConfiguration rtc_config;
3587 rtc_config.use_media_transport_for_data_channels = true;
3588 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3589 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3590 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3591 loopback_media_transports()->second_factory()));
3592 ConnectFakeSignaling();
3593
3594 // Create a data channel with a non-default configuration and signal it to the
3595 // callee.
3596 webrtc::DataChannelInit init;
3597 init.id = 53;
3598 init.maxRetransmits = 52;
3599 caller()->CreateDataChannel("data-channel", &init);
3600 caller()->CreateAndSetAndSignalOffer();
3601 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3602
3603 // Ensure that the media transport is ready.
3604 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3605 loopback_media_transports()->FlushAsyncInvokes();
3606
3607 // Ensure that the data channel exists on the callee with the correct
3608 // configuration.
3609 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3610 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003611 // Since "negotiate" is false, the "id" parameter is ignored.
3612 EXPECT_NE(init.id, callee()->data_channel()->id());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003613 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3614 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3615 EXPECT_FALSE(callee()->data_channel()->negotiated());
3616}
3617
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003618TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgrade) {
3619 PeerConnectionInterface::RTCConfiguration rtc_config;
3620 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3621 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3622 rtc_config.use_media_transport = true;
3623 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3624 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3625 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3626 loopback_media_transports()->second_factory()));
3627 ConnectFakeSignaling();
3628
3629 // Do initial offer/answer with just a video track.
3630 caller()->AddVideoTrack();
3631 callee()->AddVideoTrack();
3632 caller()->CreateAndSetAndSignalOffer();
3633 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3634
3635 // Ensure that the media transport is ready.
3636 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3637 loopback_media_transports()->FlushAsyncInvokes();
3638
3639 // Now add an audio track and do another offer/answer.
3640 caller()->AddAudioTrack();
3641 callee()->AddAudioTrack();
3642 caller()->CreateAndSetAndSignalOffer();
3643 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3644
3645 // Ensure both audio and video frames are received end-to-end.
3646 MediaExpectations media_expectations;
3647 media_expectations.ExpectBidirectionalAudioAndVideo();
3648 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3649
3650 // The second offer should not have generated another media transport.
3651 // Media transport was kept alive, and was not recreated.
3652 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3653 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3654}
3655
3656TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgradeOnTheCallee) {
3657 PeerConnectionInterface::RTCConfiguration rtc_config;
3658 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3659 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3660 rtc_config.use_media_transport = true;
3661 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3662 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3663 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3664 loopback_media_transports()->second_factory()));
3665 ConnectFakeSignaling();
3666
3667 // Do initial offer/answer with just a video track.
3668 caller()->AddVideoTrack();
3669 callee()->AddVideoTrack();
3670 caller()->CreateAndSetAndSignalOffer();
3671 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3672
3673 // Ensure that the media transport is ready.
3674 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3675 loopback_media_transports()->FlushAsyncInvokes();
3676
3677 // Now add an audio track and do another offer/answer.
3678 caller()->AddAudioTrack();
3679 callee()->AddAudioTrack();
3680 callee()->CreateAndSetAndSignalOffer();
3681 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3682
3683 // Ensure both audio and video frames are received end-to-end.
3684 MediaExpectations media_expectations;
3685 media_expectations.ExpectBidirectionalAudioAndVideo();
3686 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3687
3688 // The second offer should not have generated another media transport.
3689 // Media transport was kept alive, and was not recreated.
3690 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3691 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3692}
3693
Niels Möllerc68d2822018-11-20 14:52:05 +01003694TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalAudio) {
3695 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003696 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3697 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Niels Möllerc68d2822018-11-20 14:52:05 +01003698 rtc_config.use_media_transport = true;
3699 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3700 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3701 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3702 loopback_media_transports()->second_factory()));
3703 ConnectFakeSignaling();
3704
3705 caller()->AddAudioTrack();
3706 callee()->AddAudioTrack();
3707 // Start offer/answer exchange and wait for it to complete.
3708 caller()->CreateAndSetAndSignalOffer();
3709 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3710
3711 // Ensure that the media transport is ready.
3712 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3713 loopback_media_transports()->FlushAsyncInvokes();
3714
3715 MediaExpectations media_expectations;
3716 media_expectations.ExpectBidirectionalAudio();
3717 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3718
3719 webrtc::MediaTransportPair::Stats first_stats =
3720 loopback_media_transports()->FirstStats();
3721 webrtc::MediaTransportPair::Stats second_stats =
3722 loopback_media_transports()->SecondStats();
3723
3724 EXPECT_GT(first_stats.received_audio_frames, 0);
3725 EXPECT_GE(second_stats.sent_audio_frames, first_stats.received_audio_frames);
3726
3727 EXPECT_GT(second_stats.received_audio_frames, 0);
3728 EXPECT_GE(first_stats.sent_audio_frames, second_stats.received_audio_frames);
3729}
3730
Niels Möller46879152019-01-07 15:54:47 +01003731TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalVideo) {
3732 PeerConnectionInterface::RTCConfiguration rtc_config;
3733 rtc_config.use_media_transport = true;
3734 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3735 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3736 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3737 loopback_media_transports()->second_factory()));
3738 ConnectFakeSignaling();
3739
3740 caller()->AddVideoTrack();
3741 callee()->AddVideoTrack();
3742 // Start offer/answer exchange and wait for it to complete.
3743 caller()->CreateAndSetAndSignalOffer();
3744 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3745
3746 // Ensure that the media transport is ready.
3747 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3748 loopback_media_transports()->FlushAsyncInvokes();
3749
3750 MediaExpectations media_expectations;
3751 media_expectations.ExpectBidirectionalVideo();
3752 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3753
3754 webrtc::MediaTransportPair::Stats first_stats =
3755 loopback_media_transports()->FirstStats();
3756 webrtc::MediaTransportPair::Stats second_stats =
3757 loopback_media_transports()->SecondStats();
3758
3759 EXPECT_GT(first_stats.received_video_frames, 0);
3760 EXPECT_GE(second_stats.sent_video_frames, first_stats.received_video_frames);
3761
3762 EXPECT_GT(second_stats.received_video_frames, 0);
3763 EXPECT_GE(first_stats.sent_video_frames, second_stats.received_video_frames);
3764}
3765
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003766TEST_P(PeerConnectionIntegrationTest,
3767 MediaTransportDataChannelUsesRtpBidirectionalVideo) {
3768 PeerConnectionInterface::RTCConfiguration rtc_config;
3769 rtc_config.use_media_transport = false;
3770 rtc_config.use_media_transport_for_data_channels = true;
3771 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3772 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3773 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3774 loopback_media_transports()->second_factory()));
3775 ConnectFakeSignaling();
3776
3777 caller()->AddVideoTrack();
3778 callee()->AddVideoTrack();
3779 // Start offer/answer exchange and wait for it to complete.
3780 caller()->CreateAndSetAndSignalOffer();
3781 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3782
3783 MediaExpectations media_expectations;
3784 media_expectations.ExpectBidirectionalVideo();
3785 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3786}
3787
deadbeef1dcb1642017-03-29 21:08:16 -07003788// Test that the ICE connection and gathering states eventually reach
3789// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003790TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003791 ASSERT_TRUE(CreatePeerConnectionWrappers());
3792 ConnectFakeSignaling();
3793 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003794 caller()->AddAudioVideoTracks();
3795 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003796 caller()->CreateAndSetAndSignalOffer();
3797 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3798 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3799 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3800 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3801 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3802 // After the best candidate pair is selected and all candidates are signaled,
3803 // the ICE connection state should reach "complete".
3804 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3805 // answerer/"callee" by default) only reaches "connected". When this is
3806 // fixed, this test should be updated.
3807 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3808 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00003809 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3810 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003811}
3812
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003813constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
3814 cricket::PORTALLOCATOR_DISABLE_RELAY |
3815 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003816
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003817// Use a mock resolver to resolve the hostname back to the original IP on both
3818// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003819TEST_P(PeerConnectionIntegrationTest,
3820 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003821 auto caller_resolver_factory =
3822 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3823 auto callee_resolver_factory =
3824 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3825 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
3826 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003827
3828 // This also verifies that the injected AsyncResolverFactory is used by
3829 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003830 EXPECT_CALL(*caller_resolver_factory, Create())
3831 .WillOnce(Return(&caller_async_resolver));
3832 webrtc::PeerConnectionDependencies caller_deps(nullptr);
3833 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
3834
3835 EXPECT_CALL(*callee_resolver_factory, Create())
3836 .WillOnce(Return(&callee_async_resolver));
3837 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3838 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
3839
3840 PeerConnectionInterface::RTCConfiguration config;
3841 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3842 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3843
3844 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3845 config, std::move(caller_deps), config, std::move(callee_deps)));
3846
3847 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
3848 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
3849
3850 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07003851 caller()->SetMdnsResponder(
3852 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
3853 callee()->SetMdnsResponder(
3854 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003855
3856 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003857
3858 ConnectFakeSignaling();
3859 caller()->AddAudioVideoTracks();
3860 callee()->AddAudioVideoTracks();
3861 caller()->CreateAndSetAndSignalOffer();
3862 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3863 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3864 caller()->ice_connection_state(), kDefaultTimeout);
3865 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3866 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08003867
3868 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3869 "WebRTC.PeerConnection.CandidatePairType_UDP",
3870 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003871}
3872
Steve Antonede9ca52017-10-16 13:04:27 -07003873// Test that firewalling the ICE connection causes the clients to identify the
3874// disconnected state and then removing the firewall causes them to reconnect.
3875class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003876 : public PeerConnectionIntegrationBaseTest,
3877 public ::testing::WithParamInterface<
3878 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003879 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003880 PeerConnectionIntegrationIceStatesTest()
3881 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3882 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003883 }
3884
3885 void StartStunServer(const SocketAddress& server_address) {
3886 stun_server_.reset(
3887 cricket::TestStunServer::Create(network_thread(), server_address));
3888 }
3889
3890 bool TestIPv6() {
3891 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3892 }
3893
3894 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003895 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
3896 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07003897 }
3898
3899 std::vector<SocketAddress> CallerAddresses() {
3900 std::vector<SocketAddress> addresses;
3901 addresses.push_back(SocketAddress("1.1.1.1", 0));
3902 if (TestIPv6()) {
3903 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3904 }
3905 return addresses;
3906 }
3907
3908 std::vector<SocketAddress> CalleeAddresses() {
3909 std::vector<SocketAddress> addresses;
3910 addresses.push_back(SocketAddress("2.2.2.2", 0));
3911 if (TestIPv6()) {
3912 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3913 }
3914 return addresses;
3915 }
3916
3917 void SetUpNetworkInterfaces() {
3918 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07003919 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
3920 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07003921
3922 // Add network addresses for test.
3923 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003924 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003925 }
3926 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003927 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003928 }
3929 }
3930
3931 private:
3932 uint32_t port_allocator_flags_;
3933 std::unique_ptr<cricket::TestStunServer> stun_server_;
3934};
3935
3936// Tests that the PeerConnection goes through all the ICE gathering/connection
3937// states over the duration of the call. This includes Disconnected and Failed
3938// states, induced by putting a firewall between the peers and waiting for them
3939// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003940TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01003941 rtc::ScopedFakeClock fake_clock;
3942 // Some things use a time of "0" as a special value, so we need to start out
3943 // the fake clock at a nonzero time.
3944 fake_clock.AdvanceTime(TimeDelta::seconds(1));
Steve Antonede9ca52017-10-16 13:04:27 -07003945
3946 const SocketAddress kStunServerAddress =
3947 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3948 StartStunServer(kStunServerAddress);
3949
3950 PeerConnectionInterface::RTCConfiguration config;
3951 PeerConnectionInterface::IceServer ice_stun_server;
3952 ice_stun_server.urls.push_back(
3953 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
3954 kStunServerAddress.PortAsString());
3955 config.servers.push_back(ice_stun_server);
3956
3957 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3958 ConnectFakeSignaling();
3959 SetPortAllocatorFlags();
3960 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003961 caller()->AddAudioVideoTracks();
3962 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003963
3964 // Initial state before anything happens.
3965 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
3966 caller()->ice_gathering_state());
3967 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3968 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01003969 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3970 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07003971
3972 // Start the call by creating the offer, setting it as the local description,
3973 // then sending it to the peer who will respond with an answer. This happens
3974 // asynchronously so that we can watch the states as it runs in the
3975 // background.
3976 caller()->CreateAndSetAndSignalOffer();
3977
Jonas Olsson7a6739e2019-01-15 16:31:55 +01003978 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
3979 caller()->ice_connection_state());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01003980 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olsson7a6739e2019-01-15 16:31:55 +01003981 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07003982
3983 // Verify that the observer was notified of the intermediate transitions.
3984 EXPECT_THAT(caller()->ice_connection_state_history(),
3985 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3986 PeerConnectionInterface::kIceConnectionConnected,
3987 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01003988 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
3989 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3990 PeerConnectionInterface::kIceConnectionConnected,
3991 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02003992 EXPECT_THAT(
3993 caller()->peer_connection_state_history(),
3994 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02003995 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07003996 EXPECT_THAT(caller()->ice_gathering_state_history(),
3997 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
3998 PeerConnectionInterface::kIceGatheringComplete));
3999
4000 // Block connections to/from the caller and wait for ICE to become
4001 // disconnected.
4002 for (const auto& caller_address : CallerAddresses()) {
4003 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4004 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004005 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004006 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4007 caller()->ice_connection_state(), kDefaultTimeout,
4008 fake_clock);
4009 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4010 caller()->standardized_ice_connection_state(),
4011 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004012
4013 // Let ICE re-establish by removing the firewall rules.
4014 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004015 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004016 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4017 caller()->ice_connection_state(), kDefaultTimeout,
4018 fake_clock);
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004019 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004020 caller()->standardized_ice_connection_state(),
4021 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004022
4023 // According to RFC7675, if there is no response within 30 seconds then the
4024 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004025 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004026 constexpr int kConsentTimeout = 30000;
4027 for (const auto& caller_address : CallerAddresses()) {
4028 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4029 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004030 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004031 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4032 caller()->ice_connection_state(), kConsentTimeout,
4033 fake_clock);
4034 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4035 caller()->standardized_ice_connection_state(),
4036 kConsentTimeout, fake_clock);
4037
4038 // We need to manually close the peerconnections before the fake clock goes
4039 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4040 // return to using non-faked time.
4041 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4042 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
4043}
4044
4045// Tests that if the connection doesn't get set up properly we eventually reach
4046// the "failed" iceConnectionState.
4047TEST_P(PeerConnectionIntegrationIceStatesTest, IceStateSetupFailure) {
4048 rtc::ScopedFakeClock fake_clock;
4049 // Some things use a time of "0" as a special value, so we need to start out
4050 // the fake clock at a nonzero time.
4051 fake_clock.AdvanceTime(TimeDelta::seconds(1));
4052
4053 // Block connections to/from the caller and wait for ICE to become
4054 // disconnected.
4055 for (const auto& caller_address : CallerAddresses()) {
4056 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4057 }
4058
4059 ASSERT_TRUE(CreatePeerConnectionWrappers());
4060 ConnectFakeSignaling();
4061 SetPortAllocatorFlags();
4062 SetUpNetworkInterfaces();
4063 caller()->AddAudioVideoTracks();
4064 caller()->CreateAndSetAndSignalOffer();
4065
4066 // According to RFC7675, if there is no response within 30 seconds then the
4067 // peer should consider the other side to have rejected the connection. This
4068 // is signaled by the state transitioning to "failed".
4069 constexpr int kConsentTimeout = 30000;
4070 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4071 caller()->standardized_ice_connection_state(),
4072 kConsentTimeout, fake_clock);
4073
4074 // We need to manually close the peerconnections before the fake clock goes
4075 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4076 // return to using non-faked time.
4077 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4078 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
Steve Antonede9ca52017-10-16 13:04:27 -07004079}
4080
4081// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4082// and that the statistics in the metric observers are updated correctly.
4083TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4084 ASSERT_TRUE(CreatePeerConnectionWrappers());
4085 ConnectFakeSignaling();
4086 SetPortAllocatorFlags();
4087 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004088 caller()->AddAudioVideoTracks();
4089 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004090 caller()->CreateAndSetAndSignalOffer();
4091
4092 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4093
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004094 // TODO(bugs.webrtc.org/9456): Fix it.
4095 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4096 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4097 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4098 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004099 if (TestIPv6()) {
4100 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4101 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004102 EXPECT_EQ(0, num_best_ipv4);
4103 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004104 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004105 EXPECT_EQ(1, num_best_ipv4);
4106 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004107 }
4108
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004109 EXPECT_EQ(0, webrtc::metrics::NumEvents(
4110 "WebRTC.PeerConnection.CandidatePairType_UDP",
4111 webrtc::kIceCandidatePairHostHost));
4112 EXPECT_EQ(1, webrtc::metrics::NumEvents(
4113 "WebRTC.PeerConnection.CandidatePairType_UDP",
4114 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004115}
4116
4117constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4118 cricket::PORTALLOCATOR_DISABLE_STUN |
4119 cricket::PORTALLOCATOR_DISABLE_RELAY;
4120constexpr uint32_t kFlagsIPv6NoStun =
4121 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4122 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4123constexpr uint32_t kFlagsIPv4Stun =
4124 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4125
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004126INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004127 PeerConnectionIntegrationTest,
4128 PeerConnectionIntegrationIceStatesTest,
4129 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4130 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4131 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4132 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004133
deadbeef1dcb1642017-03-29 21:08:16 -07004134// This test sets up a call between two parties with audio and video.
4135// During the call, the caller restarts ICE and the test verifies that
4136// new ICE candidates are generated and audio and video still can flow, and the
4137// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004138TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004139 ASSERT_TRUE(CreatePeerConnectionWrappers());
4140 ConnectFakeSignaling();
4141 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004142 caller()->AddAudioVideoTracks();
4143 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004144 caller()->CreateAndSetAndSignalOffer();
4145 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4146 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4147 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004148 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4149 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004150
4151 // To verify that the ICE restart actually occurs, get
4152 // ufrag/password/candidates before and after restart.
4153 // Create an SDP string of the first audio candidate for both clients.
4154 const webrtc::IceCandidateCollection* audio_candidates_caller =
4155 caller()->pc()->local_description()->candidates(0);
4156 const webrtc::IceCandidateCollection* audio_candidates_callee =
4157 callee()->pc()->local_description()->candidates(0);
4158 ASSERT_GT(audio_candidates_caller->count(), 0u);
4159 ASSERT_GT(audio_candidates_callee->count(), 0u);
4160 std::string caller_candidate_pre_restart;
4161 ASSERT_TRUE(
4162 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4163 std::string callee_candidate_pre_restart;
4164 ASSERT_TRUE(
4165 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4166 const cricket::SessionDescription* desc =
4167 caller()->pc()->local_description()->description();
4168 std::string caller_ufrag_pre_restart =
4169 desc->transport_infos()[0].description.ice_ufrag;
4170 desc = callee()->pc()->local_description()->description();
4171 std::string callee_ufrag_pre_restart =
4172 desc->transport_infos()[0].description.ice_ufrag;
4173
4174 // Have the caller initiate an ICE restart.
4175 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4176 caller()->CreateAndSetAndSignalOffer();
4177 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4178 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4179 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004180 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004181 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4182
4183 // Grab the ufrags/candidates again.
4184 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4185 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4186 ASSERT_GT(audio_candidates_caller->count(), 0u);
4187 ASSERT_GT(audio_candidates_callee->count(), 0u);
4188 std::string caller_candidate_post_restart;
4189 ASSERT_TRUE(
4190 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4191 std::string callee_candidate_post_restart;
4192 ASSERT_TRUE(
4193 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4194 desc = caller()->pc()->local_description()->description();
4195 std::string caller_ufrag_post_restart =
4196 desc->transport_infos()[0].description.ice_ufrag;
4197 desc = callee()->pc()->local_description()->description();
4198 std::string callee_ufrag_post_restart =
4199 desc->transport_infos()[0].description.ice_ufrag;
4200 // Sanity check that an ICE restart was actually negotiated in SDP.
4201 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4202 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4203 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4204 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
4205
4206 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004207 MediaExpectations media_expectations;
4208 media_expectations.ExpectBidirectionalAudioAndVideo();
4209 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004210}
4211
4212// Verify that audio/video can be received end-to-end when ICE renomination is
4213// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004214TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004215 PeerConnectionInterface::RTCConfiguration config;
4216 config.enable_ice_renomination = true;
4217 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4218 ConnectFakeSignaling();
4219 // Do normal offer/answer and wait for some frames to be received in each
4220 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004221 caller()->AddAudioVideoTracks();
4222 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004223 caller()->CreateAndSetAndSignalOffer();
4224 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4225 // Sanity check that ICE renomination was actually negotiated.
4226 const cricket::SessionDescription* desc =
4227 caller()->pc()->local_description()->description();
4228 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004229 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004230 }
4231 desc = callee()->pc()->local_description()->description();
4232 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004233 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004234 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004235 MediaExpectations media_expectations;
4236 media_expectations.ExpectBidirectionalAudioAndVideo();
4237 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004238}
4239
Steve Anton6f25b092017-10-23 09:39:20 -07004240// With a max bundle policy and RTCP muxing, adding a new media description to
4241// the connection should not affect ICE at all because the new media will use
4242// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004243TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004244 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004245 PeerConnectionInterface::RTCConfiguration config;
4246 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4247 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4248 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4249 config, PeerConnectionInterface::RTCConfiguration()));
4250 ConnectFakeSignaling();
4251
Steve Anton15324772018-01-16 10:26:49 -08004252 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004253 caller()->CreateAndSetAndSignalOffer();
4254 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004255 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4256 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004257
4258 caller()->clear_ice_connection_state_history();
4259
Steve Anton15324772018-01-16 10:26:49 -08004260 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004261 caller()->CreateAndSetAndSignalOffer();
4262 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4263
4264 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4265}
4266
deadbeef1dcb1642017-03-29 21:08:16 -07004267// This test sets up a call between two parties with audio and video. It then
4268// renegotiates setting the video m-line to "port 0", then later renegotiates
4269// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004270TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004271 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4272 ASSERT_TRUE(CreatePeerConnectionWrappers());
4273 ConnectFakeSignaling();
4274
4275 // Do initial negotiation, only sending media from the caller. Will result in
4276 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004277 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004278 caller()->CreateAndSetAndSignalOffer();
4279 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4280
4281 // Negotiate again, disabling the video "m=" section (the callee will set the
4282 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004283 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4284 PeerConnectionInterface::RTCOfferAnswerOptions options;
4285 options.offer_to_receive_video = 0;
4286 callee()->SetOfferAnswerOptions(options);
4287 } else {
4288 callee()->SetRemoteOfferHandler([this] {
4289 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4290 });
4291 }
deadbeef1dcb1642017-03-29 21:08:16 -07004292 caller()->CreateAndSetAndSignalOffer();
4293 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4294 // Sanity check that video "m=" section was actually rejected.
4295 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4296 callee()->pc()->local_description()->description());
4297 ASSERT_NE(nullptr, answer_video_content);
4298 ASSERT_TRUE(answer_video_content->rejected);
4299
4300 // Enable video and do negotiation again, making sure video is received
4301 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004302 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4303 PeerConnectionInterface::RTCOfferAnswerOptions options;
4304 options.offer_to_receive_video = 1;
4305 callee()->SetOfferAnswerOptions(options);
4306 } else {
4307 // The caller's transceiver is stopped, so we need to add another track.
4308 auto caller_transceiver =
4309 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4310 EXPECT_TRUE(caller_transceiver->stopped());
4311 caller()->AddVideoTrack();
4312 }
4313 callee()->AddVideoTrack();
4314 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004315 caller()->CreateAndSetAndSignalOffer();
4316 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004317
deadbeef1dcb1642017-03-29 21:08:16 -07004318 // Verify the caller receives frames from the newly added stream, and the
4319 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004320 MediaExpectations media_expectations;
4321 media_expectations.CalleeExpectsSomeAudio();
4322 media_expectations.ExpectBidirectionalVideo();
4323 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004324}
4325
deadbeef1dcb1642017-03-29 21:08:16 -07004326// This tests that if we negotiate after calling CreateSender but before we
4327// have a track, then set a track later, frames from the newly-set track are
4328// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004329TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004330 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4331 ASSERT_TRUE(CreatePeerConnectionWrappers());
4332 ConnectFakeSignaling();
4333 auto caller_audio_sender =
4334 caller()->pc()->CreateSender("audio", "caller_stream");
4335 auto caller_video_sender =
4336 caller()->pc()->CreateSender("video", "caller_stream");
4337 auto callee_audio_sender =
4338 callee()->pc()->CreateSender("audio", "callee_stream");
4339 auto callee_video_sender =
4340 callee()->pc()->CreateSender("video", "callee_stream");
4341 caller()->CreateAndSetAndSignalOffer();
4342 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4343 // Wait for ICE to complete, without any tracks being set.
4344 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4345 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4346 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4347 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4348 // Now set the tracks, and expect frames to immediately start flowing.
4349 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4350 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4351 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4352 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004353 MediaExpectations media_expectations;
4354 media_expectations.ExpectBidirectionalAudioAndVideo();
4355 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4356}
4357
4358// This tests that if we negotiate after calling AddTransceiver but before we
4359// have a track, then set a track later, frames from the newly-set tracks are
4360// received end-to-end.
4361TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4362 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4363 ASSERT_TRUE(CreatePeerConnectionWrappers());
4364 ConnectFakeSignaling();
4365 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4366 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4367 auto caller_audio_sender = audio_result.MoveValue()->sender();
4368 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4369 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4370 auto caller_video_sender = video_result.MoveValue()->sender();
4371 callee()->SetRemoteOfferHandler([this] {
4372 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4373 callee()->pc()->GetTransceivers()[0]->SetDirection(
4374 RtpTransceiverDirection::kSendRecv);
4375 callee()->pc()->GetTransceivers()[1]->SetDirection(
4376 RtpTransceiverDirection::kSendRecv);
4377 });
4378 caller()->CreateAndSetAndSignalOffer();
4379 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4380 // Wait for ICE to complete, without any tracks being set.
4381 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4382 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4383 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4384 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4385 // Now set the tracks, and expect frames to immediately start flowing.
4386 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4387 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4388 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4389 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4390 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4391 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4392 MediaExpectations media_expectations;
4393 media_expectations.ExpectBidirectionalAudioAndVideo();
4394 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004395}
4396
4397// This test verifies that a remote video track can be added via AddStream,
4398// and sent end-to-end. For this particular test, it's simply echoed back
4399// from the caller to the callee, rather than being forwarded to a third
4400// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004401TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004402 ASSERT_TRUE(CreatePeerConnectionWrappers());
4403 ConnectFakeSignaling();
4404 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004405 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004406 caller()->CreateAndSetAndSignalOffer();
4407 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004408 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004409
4410 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4411 // time).
4412 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4413 callee()->CreateAndSetAndSignalOffer();
4414 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4415
Seth Hampson2f0d7022018-02-20 11:54:42 -08004416 MediaExpectations media_expectations;
4417 media_expectations.ExpectBidirectionalVideo();
4418 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004419}
4420
4421// Test that we achieve the expected end-to-end connection time, using a
4422// fake clock and simulated latency on the media and signaling paths.
4423// We use a TURN<->TURN connection because this is usually the quickest to
4424// set up initially, especially when we're confident the connection will work
4425// and can start sending media before we get a STUN response.
4426//
4427// With various optimizations enabled, here are the network delays we expect to
4428// be on the critical path:
4429// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4430// signaling answer (with DTLS fingerprint).
4431// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4432// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4433// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004434TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004435 rtc::ScopedFakeClock fake_clock;
4436 // Some things use a time of "0" as a special value, so we need to start out
4437 // the fake clock at a nonzero time.
4438 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02004439 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07004440
4441 static constexpr int media_hop_delay_ms = 50;
4442 static constexpr int signaling_trip_delay_ms = 500;
4443 // For explanation of these values, see comment above.
4444 static constexpr int required_media_hops = 9;
4445 static constexpr int required_signaling_trips = 2;
4446 // For internal delays (such as posting an event asychronously).
4447 static constexpr int allowed_internal_delay_ms = 20;
4448 static constexpr int total_connection_time_ms =
4449 media_hop_delay_ms * required_media_hops +
4450 signaling_trip_delay_ms * required_signaling_trips +
4451 allowed_internal_delay_ms;
4452
4453 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4454 3478};
4455 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4456 0};
4457 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4458 3478};
4459 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4460 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004461 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4462 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004463
Seth Hampsonaed71642018-06-11 07:41:32 -07004464 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4465 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004466 // Bypass permission check on received packets so media can be sent before
4467 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004468 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4469 turn_server_1->set_enable_permission_checks(false);
4470 });
4471 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4472 turn_server_2->set_enable_permission_checks(false);
4473 });
deadbeef1dcb1642017-03-29 21:08:16 -07004474
4475 PeerConnectionInterface::RTCConfiguration client_1_config;
4476 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4477 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4478 ice_server_1.username = "test";
4479 ice_server_1.password = "test";
4480 client_1_config.servers.push_back(ice_server_1);
4481 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4482 client_1_config.presume_writable_when_fully_relayed = true;
4483
4484 PeerConnectionInterface::RTCConfiguration client_2_config;
4485 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4486 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4487 ice_server_2.username = "test";
4488 ice_server_2.password = "test";
4489 client_2_config.servers.push_back(ice_server_2);
4490 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4491 client_2_config.presume_writable_when_fully_relayed = true;
4492
4493 ASSERT_TRUE(
4494 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4495 // Set up the simulated delays.
4496 SetSignalingDelayMs(signaling_trip_delay_ms);
4497 ConnectFakeSignaling();
4498 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4499 virtual_socket_server()->UpdateDelayDistribution();
4500
4501 // Set "offer to receive audio/video" without adding any tracks, so we just
4502 // set up ICE/DTLS with no media.
4503 PeerConnectionInterface::RTCOfferAnswerOptions options;
4504 options.offer_to_receive_audio = 1;
4505 options.offer_to_receive_video = 1;
4506 caller()->SetOfferAnswerOptions(options);
4507 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004508 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4509 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004510 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4511 // If this is not done a DCHECK can be hit in ports.cc, because a large
4512 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07004513 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07004514}
4515
Jonas Orelandbdcee282017-10-10 14:01:40 +02004516// Verify that a TurnCustomizer passed in through RTCConfiguration
4517// is actually used by the underlying TURN candidate pair.
4518// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004519TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004520 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4521 3478};
4522 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4523 0};
4524 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4525 3478};
4526 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4527 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004528 CreateTurnServer(turn_server_1_internal_address,
4529 turn_server_1_external_address);
4530 CreateTurnServer(turn_server_2_internal_address,
4531 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004532
4533 PeerConnectionInterface::RTCConfiguration client_1_config;
4534 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4535 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4536 ice_server_1.username = "test";
4537 ice_server_1.password = "test";
4538 client_1_config.servers.push_back(ice_server_1);
4539 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004540 auto* customizer1 = CreateTurnCustomizer();
4541 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004542
4543 PeerConnectionInterface::RTCConfiguration client_2_config;
4544 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4545 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4546 ice_server_2.username = "test";
4547 ice_server_2.password = "test";
4548 client_2_config.servers.push_back(ice_server_2);
4549 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004550 auto* customizer2 = CreateTurnCustomizer();
4551 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004552
4553 ASSERT_TRUE(
4554 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4555 ConnectFakeSignaling();
4556
4557 // Set "offer to receive audio/video" without adding any tracks, so we just
4558 // set up ICE/DTLS with no media.
4559 PeerConnectionInterface::RTCOfferAnswerOptions options;
4560 options.offer_to_receive_audio = 1;
4561 options.offer_to_receive_video = 1;
4562 caller()->SetOfferAnswerOptions(options);
4563 caller()->CreateAndSetAndSignalOffer();
4564 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4565
Seth Hampsonaed71642018-06-11 07:41:32 -07004566 ExpectTurnCustomizerCountersIncremented(customizer1);
4567 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004568}
4569
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004570// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4571// send media between the caller and the callee.
4572TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4573 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4574 3478};
4575 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4576
4577 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004578 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4579 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004580
4581 webrtc::PeerConnectionInterface::IceServer ice_server;
4582 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4583 ice_server.username = "test";
4584 ice_server.password = "test";
4585
4586 PeerConnectionInterface::RTCConfiguration client_1_config;
4587 client_1_config.servers.push_back(ice_server);
4588 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4589
4590 PeerConnectionInterface::RTCConfiguration client_2_config;
4591 client_2_config.servers.push_back(ice_server);
4592 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4593
4594 ASSERT_TRUE(
4595 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4596
4597 // Do normal offer/answer and wait for ICE to complete.
4598 ConnectFakeSignaling();
4599 caller()->AddAudioVideoTracks();
4600 callee()->AddAudioVideoTracks();
4601 caller()->CreateAndSetAndSignalOffer();
4602 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4603 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4604 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4605
4606 MediaExpectations media_expectations;
4607 media_expectations.ExpectBidirectionalAudioAndVideo();
4608 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4609}
4610
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004611// Verify that a SSLCertificateVerifier passed in through
4612// PeerConnectionDependencies is actually used by the underlying SSL
4613// implementation to determine whether a certificate presented by the TURN
4614// server is accepted by the client. Note that openssladapter_unittest.cc
4615// contains more detailed, lower-level tests.
4616TEST_P(PeerConnectionIntegrationTest,
4617 SSLCertificateVerifierUsedForTurnConnections) {
4618 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4619 3478};
4620 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4621
4622 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4623 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004624 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4625 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004626
4627 webrtc::PeerConnectionInterface::IceServer ice_server;
4628 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4629 ice_server.username = "test";
4630 ice_server.password = "test";
4631
4632 PeerConnectionInterface::RTCConfiguration client_1_config;
4633 client_1_config.servers.push_back(ice_server);
4634 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4635
4636 PeerConnectionInterface::RTCConfiguration client_2_config;
4637 client_2_config.servers.push_back(ice_server);
4638 // Setting the type to kRelay forces the connection to go through a TURN
4639 // server.
4640 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4641
4642 // Get a copy to the pointer so we can verify calls later.
4643 rtc::TestCertificateVerifier* client_1_cert_verifier =
4644 new rtc::TestCertificateVerifier();
4645 client_1_cert_verifier->verify_certificate_ = true;
4646 rtc::TestCertificateVerifier* client_2_cert_verifier =
4647 new rtc::TestCertificateVerifier();
4648 client_2_cert_verifier->verify_certificate_ = true;
4649
4650 // Create the dependencies with the test certificate verifier.
4651 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4652 client_1_deps.tls_cert_verifier =
4653 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4654 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4655 client_2_deps.tls_cert_verifier =
4656 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4657
4658 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4659 client_1_config, std::move(client_1_deps), client_2_config,
4660 std::move(client_2_deps)));
4661 ConnectFakeSignaling();
4662
4663 // Set "offer to receive audio/video" without adding any tracks, so we just
4664 // set up ICE/DTLS with no media.
4665 PeerConnectionInterface::RTCOfferAnswerOptions options;
4666 options.offer_to_receive_audio = 1;
4667 options.offer_to_receive_video = 1;
4668 caller()->SetOfferAnswerOptions(options);
4669 caller()->CreateAndSetAndSignalOffer();
4670 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4671
4672 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4673 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004674}
4675
4676TEST_P(PeerConnectionIntegrationTest,
4677 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4678 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4679 3478};
4680 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4681
4682 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4683 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004684 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4685 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004686
4687 webrtc::PeerConnectionInterface::IceServer ice_server;
4688 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4689 ice_server.username = "test";
4690 ice_server.password = "test";
4691
4692 PeerConnectionInterface::RTCConfiguration client_1_config;
4693 client_1_config.servers.push_back(ice_server);
4694 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4695
4696 PeerConnectionInterface::RTCConfiguration client_2_config;
4697 client_2_config.servers.push_back(ice_server);
4698 // Setting the type to kRelay forces the connection to go through a TURN
4699 // server.
4700 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4701
4702 // Get a copy to the pointer so we can verify calls later.
4703 rtc::TestCertificateVerifier* client_1_cert_verifier =
4704 new rtc::TestCertificateVerifier();
4705 client_1_cert_verifier->verify_certificate_ = false;
4706 rtc::TestCertificateVerifier* client_2_cert_verifier =
4707 new rtc::TestCertificateVerifier();
4708 client_2_cert_verifier->verify_certificate_ = false;
4709
4710 // Create the dependencies with the test certificate verifier.
4711 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4712 client_1_deps.tls_cert_verifier =
4713 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4714 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4715 client_2_deps.tls_cert_verifier =
4716 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4717
4718 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4719 client_1_config, std::move(client_1_deps), client_2_config,
4720 std::move(client_2_deps)));
4721 ConnectFakeSignaling();
4722
4723 // Set "offer to receive audio/video" without adding any tracks, so we just
4724 // set up ICE/DTLS with no media.
4725 PeerConnectionInterface::RTCOfferAnswerOptions options;
4726 options.offer_to_receive_audio = 1;
4727 options.offer_to_receive_video = 1;
4728 caller()->SetOfferAnswerOptions(options);
4729 caller()->CreateAndSetAndSignalOffer();
4730 bool wait_res = true;
4731 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4732 // properly, should be able to just wait for a state of "failed" instead of
4733 // waiting a fixed 10 seconds.
4734 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4735 ASSERT_FALSE(wait_res);
4736
4737 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4738 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004739}
4740
deadbeefc964d0b2017-04-03 10:03:35 -07004741// Test that audio and video flow end-to-end when codec names don't use the
4742// expected casing, given that they're supposed to be case insensitive. To test
4743// this, all but one codec is removed from each media description, and its
4744// casing is changed.
4745//
4746// In the past, this has regressed and caused crashes/black video, due to the
4747// fact that code at some layers was doing case-insensitive comparisons and
4748// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004749TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004750 ASSERT_TRUE(CreatePeerConnectionWrappers());
4751 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004752 caller()->AddAudioVideoTracks();
4753 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004754
4755 // Remove all but one audio/video codec (opus and VP8), and change the
4756 // casing of the caller's generated offer.
4757 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4758 cricket::AudioContentDescription* audio =
4759 GetFirstAudioContentDescription(description);
4760 ASSERT_NE(nullptr, audio);
4761 auto audio_codecs = audio->codecs();
4762 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4763 [](const cricket::AudioCodec& codec) {
4764 return codec.name != "opus";
4765 }),
4766 audio_codecs.end());
4767 ASSERT_EQ(1u, audio_codecs.size());
4768 audio_codecs[0].name = "OpUs";
4769 audio->set_codecs(audio_codecs);
4770
4771 cricket::VideoContentDescription* video =
4772 GetFirstVideoContentDescription(description);
4773 ASSERT_NE(nullptr, video);
4774 auto video_codecs = video->codecs();
4775 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4776 [](const cricket::VideoCodec& codec) {
4777 return codec.name != "VP8";
4778 }),
4779 video_codecs.end());
4780 ASSERT_EQ(1u, video_codecs.size());
4781 video_codecs[0].name = "vP8";
4782 video->set_codecs(video_codecs);
4783 });
4784
4785 caller()->CreateAndSetAndSignalOffer();
4786 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4787
4788 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004789 MediaExpectations media_expectations;
4790 media_expectations.ExpectBidirectionalAudioAndVideo();
4791 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004792}
4793
Jonas Oreland49ac5952018-09-26 16:04:32 +02004794TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004795 ASSERT_TRUE(CreatePeerConnectionWrappers());
4796 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004797 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004798 caller()->CreateAndSetAndSignalOffer();
4799 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004800 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004801 MediaExpectations media_expectations;
4802 media_expectations.CalleeExpectsSomeAudio(1);
4803 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004804 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004805 auto receiver = callee()->pc()->GetReceivers()[0];
4806 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004807 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004808 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4809 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004810 sources[0].source_id());
4811 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4812}
4813
4814TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4815 ASSERT_TRUE(CreatePeerConnectionWrappers());
4816 ConnectFakeSignaling();
4817 caller()->AddVideoTrack();
4818 caller()->CreateAndSetAndSignalOffer();
4819 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4820 // Wait for one video frame to be received by the callee.
4821 MediaExpectations media_expectations;
4822 media_expectations.CalleeExpectsSomeVideo(1);
4823 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4824 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4825 auto receiver = callee()->pc()->GetReceivers()[0];
4826 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4827 auto sources = receiver->GetSources();
4828 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4829 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4830 sources[0].source_id());
4831 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004832}
4833
deadbeef2f425aa2017-04-14 10:41:32 -07004834// Test that if a track is removed and added again with a different stream ID,
4835// the new stream ID is successfully communicated in SDP and media continues to
4836// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004837// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4838// it will not reuse a transceiver that has already been sending. After creating
4839// a new transceiver it tries to create an offer with two senders of the same
4840// track ids and it fails.
4841TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004842 ASSERT_TRUE(CreatePeerConnectionWrappers());
4843 ConnectFakeSignaling();
4844
deadbeef2f425aa2017-04-14 10:41:32 -07004845 // Add track using stream 1, do offer/answer.
4846 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4847 caller()->CreateLocalAudioTrack();
4848 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004849 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004850 caller()->CreateAndSetAndSignalOffer();
4851 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004852 {
4853 MediaExpectations media_expectations;
4854 media_expectations.CalleeExpectsSomeAudio(1);
4855 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4856 }
deadbeef2f425aa2017-04-14 10:41:32 -07004857 // Remove the sender, and create a new one with the new stream.
4858 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004859 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004860 caller()->CreateAndSetAndSignalOffer();
4861 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4862 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004863 {
4864 MediaExpectations media_expectations;
4865 media_expectations.CalleeExpectsSomeAudio();
4866 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4867 }
deadbeef2f425aa2017-04-14 10:41:32 -07004868}
4869
Seth Hampson2f0d7022018-02-20 11:54:42 -08004870TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004871 ASSERT_TRUE(CreatePeerConnectionWrappers());
4872 ConnectFakeSignaling();
4873
Karl Wiberg918f50c2018-07-05 11:40:33 +02004874 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02004875 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
4876 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02004877 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004878 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4879 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004880
Steve Anton15324772018-01-16 10:26:49 -08004881 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004882 caller()->CreateAndSetAndSignalOffer();
4883 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4884}
4885
Steve Antonede9ca52017-10-16 13:04:27 -07004886// Test that if candidates are only signaled by applying full session
4887// descriptions (instead of using AddIceCandidate), the peers can connect to
4888// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004889TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004890 ASSERT_TRUE(CreatePeerConnectionWrappers());
4891 // Each side will signal the session descriptions but not candidates.
4892 ConnectFakeSignalingForSdpOnly();
4893
4894 // Add audio video track and exchange the initial offer/answer with media
4895 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004896 caller()->AddAudioVideoTracks();
4897 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004898 caller()->CreateAndSetAndSignalOffer();
4899
4900 // Wait for all candidates to be gathered on both the caller and callee.
4901 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4902 caller()->ice_gathering_state(), kDefaultTimeout);
4903 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4904 callee()->ice_gathering_state(), kDefaultTimeout);
4905
4906 // The candidates will now be included in the session description, so
4907 // signaling them will start the ICE connection.
4908 caller()->CreateAndSetAndSignalOffer();
4909 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4910
4911 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004912 MediaExpectations media_expectations;
4913 media_expectations.ExpectBidirectionalAudioAndVideo();
4914 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004915}
4916
henrika5f6bf242017-11-01 11:06:56 +01004917// Test that SetAudioPlayout can be used to disable audio playout from the
4918// start, then later enable it. This may be useful, for example, if the caller
4919// needs to play a local ringtone until some event occurs, after which it
4920// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004921TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004922 ASSERT_TRUE(CreatePeerConnectionWrappers());
4923 ConnectFakeSignaling();
4924
4925 // Set up audio-only call where audio playout is disabled on caller's side.
4926 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004927 caller()->AddAudioTrack();
4928 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004929 caller()->CreateAndSetAndSignalOffer();
4930 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4931
4932 // Pump messages for a second.
4933 WAIT(false, 1000);
4934 // Since audio playout is disabled, the caller shouldn't have received
4935 // anything (at the playout level, at least).
4936 EXPECT_EQ(0, caller()->audio_frames_received());
4937 // As a sanity check, make sure the callee (for which playout isn't disabled)
4938 // did still see frames on its audio level.
4939 ASSERT_GT(callee()->audio_frames_received(), 0);
4940
4941 // Enable playout again, and ensure audio starts flowing.
4942 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004943 MediaExpectations media_expectations;
4944 media_expectations.ExpectBidirectionalAudio();
4945 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004946}
4947
4948double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
4949 auto report = pc->NewGetStats();
4950 auto track_stats_list =
4951 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
4952 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
4953 for (const auto* track_stats : track_stats_list) {
4954 if (track_stats->remote_source.is_defined() &&
4955 *track_stats->remote_source) {
4956 remote_track_stats = track_stats;
4957 break;
4958 }
4959 }
4960
4961 if (!remote_track_stats->total_audio_energy.is_defined()) {
4962 return 0.0;
4963 }
4964 return *remote_track_stats->total_audio_energy;
4965}
4966
4967// Test that if audio playout is disabled via the SetAudioPlayout() method, then
4968// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004969TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01004970 DisableAudioPlayoutStillGeneratesAudioStats) {
4971 ASSERT_TRUE(CreatePeerConnectionWrappers());
4972 ConnectFakeSignaling();
4973
4974 // Set up audio-only call where playout is disabled but audio-processing is
4975 // still active.
Steve Anton15324772018-01-16 10:26:49 -08004976 caller()->AddAudioTrack();
4977 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004978 caller()->pc()->SetAudioPlayout(false);
4979
4980 caller()->CreateAndSetAndSignalOffer();
4981 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4982
4983 // Wait for the callee to receive audio stats.
4984 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
4985}
4986
henrika4f167df2017-11-01 14:45:55 +01004987// Test that SetAudioRecording can be used to disable audio recording from the
4988// start, then later enable it. This may be useful, for example, if the caller
4989// wants to ensure that no audio resources are active before a certain state
4990// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004991TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01004992 ASSERT_TRUE(CreatePeerConnectionWrappers());
4993 ConnectFakeSignaling();
4994
4995 // Set up audio-only call where audio recording is disabled on caller's side.
4996 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08004997 caller()->AddAudioTrack();
4998 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01004999 caller()->CreateAndSetAndSignalOffer();
5000 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5001
5002 // Pump messages for a second.
5003 WAIT(false, 1000);
5004 // Since caller has disabled audio recording, the callee shouldn't have
5005 // received anything.
5006 EXPECT_EQ(0, callee()->audio_frames_received());
5007 // As a sanity check, make sure the caller did still see frames on its
5008 // audio level since audio recording is enabled on the calle side.
5009 ASSERT_GT(caller()->audio_frames_received(), 0);
5010
5011 // Enable audio recording again, and ensure audio starts flowing.
5012 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005013 MediaExpectations media_expectations;
5014 media_expectations.ExpectBidirectionalAudio();
5015 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005016}
5017
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005018// Test that after closing PeerConnections, they stop sending any packets (ICE,
5019// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005020TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005021 // Set up audio/video/data, wait for some frames to be received.
5022 ASSERT_TRUE(CreatePeerConnectionWrappers());
5023 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005024 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005025#ifdef HAVE_SCTP
5026 caller()->CreateDataChannel();
5027#endif
5028 caller()->CreateAndSetAndSignalOffer();
5029 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005030 MediaExpectations media_expectations;
5031 media_expectations.CalleeExpectsSomeAudioAndVideo();
5032 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005033 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005034 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005035 // Pump messages for a second, and ensure no new packets end up sent.
5036 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5037 WAIT(false, 1000);
5038 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5039 EXPECT_EQ(sent_packets_a, sent_packets_b);
5040}
5041
Steve Anton7eca0932018-03-30 15:18:41 -07005042// Test that transport stats are generated by the RTCStatsCollector for a
5043// connection that only involves data channels. This is a regression test for
5044// crbug.com/826972.
5045#ifdef HAVE_SCTP
5046TEST_P(PeerConnectionIntegrationTest,
5047 TransportStatsReportedForDataChannelOnlyConnection) {
5048 ASSERT_TRUE(CreatePeerConnectionWrappers());
5049 ConnectFakeSignaling();
5050 caller()->CreateDataChannel();
5051
5052 caller()->CreateAndSetAndSignalOffer();
5053 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5054 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5055
5056 auto caller_report = caller()->NewGetStats();
5057 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5058 auto callee_report = callee()->NewGetStats();
5059 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5060}
5061#endif // HAVE_SCTP
5062
Qingsi Wang7685e862018-06-11 20:15:46 -07005063TEST_P(PeerConnectionIntegrationTest,
5064 IceEventsGeneratedAndLoggedInRtcEventLog) {
5065 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5066 ConnectFakeSignaling();
5067 PeerConnectionInterface::RTCOfferAnswerOptions options;
5068 options.offer_to_receive_audio = 1;
5069 caller()->SetOfferAnswerOptions(options);
5070 caller()->CreateAndSetAndSignalOffer();
5071 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5072 ASSERT_NE(nullptr, caller()->event_log_factory());
5073 ASSERT_NE(nullptr, callee()->event_log_factory());
5074 webrtc::FakeRtcEventLog* caller_event_log =
5075 static_cast<webrtc::FakeRtcEventLog*>(
5076 caller()->event_log_factory()->last_log_created());
5077 webrtc::FakeRtcEventLog* callee_event_log =
5078 static_cast<webrtc::FakeRtcEventLog*>(
5079 callee()->event_log_factory()->last_log_created());
5080 ASSERT_NE(nullptr, caller_event_log);
5081 ASSERT_NE(nullptr, callee_event_log);
5082 int caller_ice_config_count = caller_event_log->GetEventCount(
5083 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5084 int caller_ice_event_count = caller_event_log->GetEventCount(
5085 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5086 int callee_ice_config_count = callee_event_log->GetEventCount(
5087 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5088 int callee_ice_event_count = callee_event_log->GetEventCount(
5089 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5090 EXPECT_LT(0, caller_ice_config_count);
5091 EXPECT_LT(0, caller_ice_event_count);
5092 EXPECT_LT(0, callee_ice_config_count);
5093 EXPECT_LT(0, callee_ice_event_count);
5094}
5095
Qingsi Wangc129c352019-04-18 10:41:58 -07005096TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005097 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5098 3478};
5099 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5100
5101 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5102
5103 webrtc::PeerConnectionInterface::IceServer ice_server;
5104 ice_server.urls.push_back("turn:88.88.88.0:3478");
5105 ice_server.username = "test";
5106 ice_server.password = "test";
5107
5108 PeerConnectionInterface::RTCConfiguration caller_config;
5109 caller_config.servers.push_back(ice_server);
5110 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5111 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005112 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005113
5114 PeerConnectionInterface::RTCConfiguration callee_config;
5115 callee_config.servers.push_back(ice_server);
5116 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5117 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005118 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005119
5120 ASSERT_TRUE(
5121 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5122
5123 // Do normal offer/answer and wait for ICE to complete.
5124 ConnectFakeSignaling();
5125 caller()->AddAudioVideoTracks();
5126 callee()->AddAudioVideoTracks();
5127 caller()->CreateAndSetAndSignalOffer();
5128 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5129 // Since we are doing continual gathering, the ICE transport does not reach
5130 // kIceGatheringComplete (see
5131 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5132 // kIceConnectionComplete.
5133 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5134 caller()->ice_connection_state(), kDefaultTimeout);
5135 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5136 callee()->ice_connection_state(), kDefaultTimeout);
5137 // Note that we cannot use the metric
5138 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5139 // metric is only populated when we reach kIceConnectionComplete in the
5140 // current implementation.
5141 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5142 caller()->last_candidate_gathered().type());
5143 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5144 callee()->last_candidate_gathered().type());
5145
5146 // Loosen the caller's candidate filter.
5147 caller_config = caller()->pc()->GetConfiguration();
5148 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5149 caller()->pc()->SetConfiguration(caller_config);
5150 // We should have gathered a new host candidate.
5151 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5152 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5153
5154 // Loosen the callee's candidate filter.
5155 callee_config = callee()->pc()->GetConfiguration();
5156 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5157 callee()->pc()->SetConfiguration(callee_config);
5158 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5159 callee()->last_candidate_gathered().type(), kDefaultTimeout);
5160}
5161
Eldar Relloda13ea22019-06-01 12:23:43 +03005162TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
Eldar Relloda13ea22019-06-01 12:23:43 +03005163 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5164 3478};
5165 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5166
5167 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5168
5169 webrtc::PeerConnectionInterface::IceServer ice_server;
5170 ice_server.urls.push_back("turn:88.88.88.0:3478");
5171 ice_server.username = "test";
5172 ice_server.password = "123";
5173
5174 PeerConnectionInterface::RTCConfiguration caller_config;
5175 caller_config.servers.push_back(ice_server);
5176 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5177 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5178
5179 PeerConnectionInterface::RTCConfiguration callee_config;
5180 callee_config.servers.push_back(ice_server);
5181 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5182 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5183
5184 ASSERT_TRUE(
5185 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5186
5187 // Do normal offer/answer and wait for ICE to complete.
5188 ConnectFakeSignaling();
5189 caller()->AddAudioVideoTracks();
5190 callee()->AddAudioVideoTracks();
5191 caller()->CreateAndSetAndSignalOffer();
5192 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5193 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5194 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5195 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
5196 EXPECT_NE(std::string::npos,
5197 caller()->error_event().host_candidate.find(":"));
5198}
5199
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005200INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5201 PeerConnectionIntegrationTest,
5202 Values(SdpSemantics::kPlanB,
5203 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005204
Steve Anton74255ff2018-01-24 18:32:57 -08005205// Tests that verify interoperability between Plan B and Unified Plan
5206// PeerConnections.
5207class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08005208 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08005209 public ::testing::WithParamInterface<
5210 std::tuple<SdpSemantics, SdpSemantics>> {
5211 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08005212 // Setting the SdpSemantics for the base test to kDefault does not matter
5213 // because we specify not to use the test semantics when creating
5214 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08005215 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07005216 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08005217 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08005218 callee_semantics_(std::get<1>(GetParam())) {}
5219
5220 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07005221 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5222 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08005223 }
5224
5225 const SdpSemantics caller_semantics_;
5226 const SdpSemantics callee_semantics_;
5227};
5228
5229TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5230 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5231 ConnectFakeSignaling();
5232
5233 caller()->CreateAndSetAndSignalOffer();
5234 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5235}
5236
5237TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
5238 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5239 ConnectFakeSignaling();
5240 auto audio_sender = caller()->AddAudioTrack();
5241
5242 caller()->CreateAndSetAndSignalOffer();
5243 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5244
5245 // Verify that one audio receiver has been created on the remote and that it
5246 // has the same track ID as the sending track.
5247 auto receivers = callee()->pc()->GetReceivers();
5248 ASSERT_EQ(1u, receivers.size());
5249 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
5250 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
5251
Seth Hampson2f0d7022018-02-20 11:54:42 -08005252 MediaExpectations media_expectations;
5253 media_expectations.CalleeExpectsSomeAudio();
5254 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005255}
5256
5257TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
5258 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5259 ConnectFakeSignaling();
5260 auto video_sender = caller()->AddVideoTrack();
5261 auto audio_sender = caller()->AddAudioTrack();
5262
5263 caller()->CreateAndSetAndSignalOffer();
5264 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5265
5266 // Verify that one audio and one video receiver have been created on the
5267 // remote and that they have the same track IDs as the sending tracks.
5268 auto audio_receivers =
5269 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5270 ASSERT_EQ(1u, audio_receivers.size());
5271 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5272 auto video_receivers =
5273 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5274 ASSERT_EQ(1u, video_receivers.size());
5275 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5276
Seth Hampson2f0d7022018-02-20 11:54:42 -08005277 MediaExpectations media_expectations;
5278 media_expectations.CalleeExpectsSomeAudioAndVideo();
5279 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005280}
5281
5282TEST_P(PeerConnectionIntegrationInteropTest,
5283 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5284 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5285 ConnectFakeSignaling();
5286 caller()->AddAudioVideoTracks();
5287 callee()->AddAudioVideoTracks();
5288
5289 caller()->CreateAndSetAndSignalOffer();
5290 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5291
Seth Hampson2f0d7022018-02-20 11:54:42 -08005292 MediaExpectations media_expectations;
5293 media_expectations.ExpectBidirectionalAudioAndVideo();
5294 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005295}
5296
5297TEST_P(PeerConnectionIntegrationInteropTest,
5298 ReverseRolesOneAudioLocalToOneVideoRemote) {
5299 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5300 ConnectFakeSignaling();
5301 caller()->AddAudioTrack();
5302 callee()->AddVideoTrack();
5303
5304 caller()->CreateAndSetAndSignalOffer();
5305 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5306
5307 // Verify that only the audio track has been negotiated.
5308 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5309 // Might also check that the callee's NegotiationNeeded flag is set.
5310
5311 // Reverse roles.
5312 callee()->CreateAndSetAndSignalOffer();
5313 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5314
Seth Hampson2f0d7022018-02-20 11:54:42 -08005315 MediaExpectations media_expectations;
5316 media_expectations.CallerExpectsSomeVideo();
5317 media_expectations.CalleeExpectsSomeAudio();
5318 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005319}
5320
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005321INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07005322 PeerConnectionIntegrationTest,
5323 PeerConnectionIntegrationInteropTest,
5324 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5325 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5326
5327// Test that if the Unified Plan side offers two video tracks then the Plan B
5328// side will only see the first one and ignore the second.
5329TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005330 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5331 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005332 ConnectFakeSignaling();
5333 auto first_sender = caller()->AddVideoTrack();
5334 caller()->AddVideoTrack();
5335
5336 caller()->CreateAndSetAndSignalOffer();
5337 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5338
5339 // Verify that there is only one receiver and it corresponds to the first
5340 // added track.
5341 auto receivers = callee()->pc()->GetReceivers();
5342 ASSERT_EQ(1u, receivers.size());
5343 EXPECT_TRUE(receivers[0]->track()->enabled());
5344 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5345
Seth Hampson2f0d7022018-02-20 11:54:42 -08005346 MediaExpectations media_expectations;
5347 media_expectations.CalleeExpectsSomeVideo();
5348 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005349}
5350
Steve Anton2bed3972019-01-04 17:04:30 -08005351// Test that if the initial offer tagged BUNDLE section is rejected due to its
5352// associated RtpTransceiver being stopped and another transceiver is added,
5353// then renegotiation causes the callee to receive the new video track without
5354// error.
5355// This is a regression test for bugs.webrtc.org/9954
5356TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5357 ReOfferWithStoppedBundleTaggedTransceiver) {
5358 RTCConfiguration config;
5359 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5360 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5361 ConnectFakeSignaling();
5362 auto audio_transceiver_or_error =
5363 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5364 ASSERT_TRUE(audio_transceiver_or_error.ok());
5365 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5366
5367 caller()->CreateAndSetAndSignalOffer();
5368 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5369 {
5370 MediaExpectations media_expectations;
5371 media_expectations.CalleeExpectsSomeAudio();
5372 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5373 }
5374
5375 audio_transceiver->Stop();
5376 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5377
5378 caller()->CreateAndSetAndSignalOffer();
5379 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5380 {
5381 MediaExpectations media_expectations;
5382 media_expectations.CalleeExpectsSomeVideo();
5383 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5384 }
5385}
5386
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005387#ifdef HAVE_SCTP
5388
5389TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5390 EndToEndCallWithBundledSctpDataChannel) {
5391 ASSERT_TRUE(CreatePeerConnectionWrappers());
5392 ConnectFakeSignaling();
5393 caller()->CreateDataChannel();
5394 caller()->AddAudioVideoTracks();
5395 callee()->AddAudioVideoTracks();
5396 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
5397 caller()->CreateAndSetAndSignalOffer();
5398 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5399 // Ensure that media and data are multiplexed on the same DTLS transport.
5400 // This only works on Unified Plan, because transports are not exposed in plan
5401 // B.
5402 auto sctp_info = caller()->pc()->GetSctpTransport()->Information();
5403 EXPECT_EQ(sctp_info.dtls_transport(),
5404 caller()->pc()->GetSenders()[0]->dtls_transport());
5405}
5406
5407#endif // HAVE_SCTP
5408
deadbeef1dcb1642017-03-29 21:08:16 -07005409} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01005410} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07005411
5412#endif // if !defined(THREAD_SANITIZER)