blob: 3eeeeb8647ba47304076e9af0c29a55a640d3ff9 [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"
Karl Wiberg1b0eae32017-10-17 14:48:54 +020026#include "api/audio_codecs/builtin_audio_decoder_factory.h"
27#include "api/audio_codecs/builtin_audio_encoder_factory.h"
Steve Anton10542f22019-01-11 09:11:00 -080028#include "api/media_stream_interface.h"
29#include "api/peer_connection_interface.h"
30#include "api/peer_connection_proxy.h"
31#include "api/rtp_receiver_interface.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/builtin_video_decoder_factory.h"
35#include "api/video_codecs/builtin_video_encoder_factory.h"
36#include "api/video_codecs/sdp_video_format.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070037#include "call/call.h"
38#include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
Bjorn Tereliusb8b3c992019-01-09 11:15:34 +010039#include "logging/rtc_event_log/rtc_event_log_factory.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070040#include "logging/rtc_event_log/rtc_event_log_factory_interface.h"
Steve Anton10542f22019-01-11 09:11:00 -080041#include "media/engine/fake_webrtc_video_engine.h"
42#include "media/engine/webrtc_media_engine.h"
Qingsi Wang7685e862018-06-11 20:15:46 -070043#include "modules/audio_processing/include/audio_processing.h"
Steve Anton10542f22019-01-11 09:11:00 -080044#include "p2p/base/mock_async_resolver.h"
45#include "p2p/base/p2p_constants.h"
46#include "p2p/base/port_interface.h"
47#include "p2p/base/test_stun_server.h"
48#include "p2p/base/test_turn_customizer.h"
49#include "p2p/base/test_turn_server.h"
50#include "p2p/client/basic_port_allocator.h"
51#include "pc/dtmf_sender.h"
52#include "pc/local_audio_source.h"
53#include "pc/media_session.h"
54#include "pc/peer_connection.h"
55#include "pc/peer_connection_factory.h"
56#include "pc/rtp_media_utils.h"
57#include "pc/session_description.h"
58#include "pc/test/fake_audio_capture_module.h"
59#include "pc/test/fake_periodic_video_track_source.h"
60#include "pc/test/fake_rtc_certificate_generator.h"
61#include "pc/test/fake_video_track_renderer.h"
62#include "pc/test/mock_peer_connection_observers.h"
Jonas Olssonb75d9e92019-02-22 10:33:29 +010063#include "rtc_base/fake_clock.h"
Qingsi Wangecd30542019-05-22 14:34:56 -070064#include "rtc_base/fake_mdns_responder.h"
Steve Anton10542f22019-01-11 09:11:00 -080065#include "rtc_base/fake_network.h"
66#include "rtc_base/firewall_socket_server.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020067#include "rtc_base/gunit.h"
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +020068#include "rtc_base/numerics/safe_conversions.h"
Steve Anton10542f22019-01-11 09:11:00 -080069#include "rtc_base/test_certificate_verifier.h"
70#include "rtc_base/time_utils.h"
71#include "rtc_base/virtual_socket_server.h"
Mirko Bonadei17f48782018-09-28 08:51:10 +020072#include "system_wrappers/include/metrics.h"
Qingsi Wangc129c352019-04-18 10:41:58 -070073#include "test/field_trial.h"
Elad Alon99c3fe52017-10-13 16:29:40 +020074#include "test/gmock.h"
deadbeef1dcb1642017-03-29 21:08:16 -070075
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010076namespace webrtc {
77namespace {
78
79using ::cricket::ContentInfo;
80using ::cricket::StreamParams;
81using ::rtc::SocketAddress;
82using ::testing::_;
Seth Hampson2f0d7022018-02-20 11:54:42 -080083using ::testing::Combine;
Steve Anton64b626b2019-01-28 17:25:26 -080084using ::testing::Contains;
Mirko Bonadeie46f5db2019-03-26 20:14:46 +010085using ::testing::DoAll;
Steve Antonede9ca52017-10-16 13:04:27 -070086using ::testing::ElementsAre;
Qingsi Wang1dac6d82018-12-12 15:28:47 -080087using ::testing::NiceMock;
Steve Anton64b626b2019-01-28 17:25:26 -080088using ::testing::Return;
Zach Stein6fcdc2f2018-08-23 16:25:55 -070089using ::testing::SetArgPointee;
Steve Antonffa6ce42018-11-30 09:26:08 -080090using ::testing::UnorderedElementsAreArray;
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +010091using ::testing::Values;
Steve Anton74255ff2018-01-24 18:32:57 -080092using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
deadbeef1dcb1642017-03-29 21:08:16 -070093
94static const int kDefaultTimeout = 10000;
95static const int kMaxWaitForStatsMs = 3000;
96static const int kMaxWaitForActivationMs = 5000;
97static const int kMaxWaitForFramesMs = 10000;
98// Default number of audio/video frames to wait for before considering a test
99// successful.
100static const int kDefaultExpectedAudioFrameCount = 3;
101static const int kDefaultExpectedVideoFrameCount = 3;
102
deadbeef1dcb1642017-03-29 21:08:16 -0700103static const char kDataChannelLabel[] = "data_channel";
104
105// SRTP cipher name negotiated by the tests. This must be updated if the
106// default changes.
Taylor Brandstetterfd350d72018-04-03 16:29:26 -0700107static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
deadbeef1dcb1642017-03-29 21:08:16 -0700108static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
109
Steve Antonede9ca52017-10-16 13:04:27 -0700110static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
111
deadbeef1dcb1642017-03-29 21:08:16 -0700112// Helper function for constructing offer/answer options to initiate an ICE
113// restart.
114PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
115 PeerConnectionInterface::RTCOfferAnswerOptions options;
116 options.ice_restart = true;
117 return options;
118}
119
deadbeefd8ad7882017-04-18 16:01:17 -0700120// Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
121// attribute from received SDP, simulating a legacy endpoint.
122void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
123 for (ContentInfo& content : desc->contents()) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800124 content.media_description()->mutable_streams().clear();
deadbeefd8ad7882017-04-18 16:01:17 -0700125 }
126 desc->set_msid_supported(false);
Henrik Boström5b147782018-12-04 11:25:05 +0100127 desc->set_msid_signaling(0);
deadbeefd8ad7882017-04-18 16:01:17 -0700128}
129
Seth Hampson5897a6e2018-04-03 11:16:33 -0700130// Removes all stream information besides the stream ids, simulating an
131// endpoint that only signals a=msid lines to convey stream_ids.
132void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
133 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700134 std::string track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700135 std::vector<std::string> stream_ids;
136 if (!content.media_description()->streams().empty()) {
Steve Antondf527fd2018-04-27 15:52:03 -0700137 const StreamParams& first_stream =
138 content.media_description()->streams()[0];
139 track_id = first_stream.id;
140 stream_ids = first_stream.stream_ids();
Seth Hampson5897a6e2018-04-03 11:16:33 -0700141 }
142 content.media_description()->mutable_streams().clear();
Steve Antondf527fd2018-04-27 15:52:03 -0700143 StreamParams new_stream;
144 new_stream.id = track_id;
Seth Hampson5897a6e2018-04-03 11:16:33 -0700145 new_stream.set_stream_ids(stream_ids);
146 content.media_description()->AddStream(new_stream);
147 }
148}
149
zhihuangf8164932017-05-19 13:09:47 -0700150int FindFirstMediaStatsIndexByKind(
151 const std::string& kind,
152 const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
153 media_stats_vec) {
154 for (size_t i = 0; i < media_stats_vec.size(); i++) {
155 if (media_stats_vec[i]->kind.ValueToString() == kind) {
156 return i;
157 }
158 }
159 return -1;
160}
161
deadbeef1dcb1642017-03-29 21:08:16 -0700162class SignalingMessageReceiver {
163 public:
Steve Antona3a92c22017-12-07 10:27:41 -0800164 virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700165 virtual void ReceiveIceMessage(const std::string& sdp_mid,
166 int sdp_mline_index,
167 const std::string& msg) = 0;
168
169 protected:
170 SignalingMessageReceiver() {}
171 virtual ~SignalingMessageReceiver() {}
172};
173
174class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
175 public:
176 explicit MockRtpReceiverObserver(cricket::MediaType media_type)
177 : expected_media_type_(media_type) {}
178
179 void OnFirstPacketReceived(cricket::MediaType media_type) override {
180 ASSERT_EQ(expected_media_type_, media_type);
181 first_packet_received_ = true;
182 }
183
184 bool first_packet_received() const { return first_packet_received_; }
185
186 virtual ~MockRtpReceiverObserver() {}
187
188 private:
189 bool first_packet_received_ = false;
190 cricket::MediaType expected_media_type_;
191};
192
193// Helper class that wraps a peer connection, observes it, and can accept
194// signaling messages from another wrapper.
195//
196// Uses a fake network, fake A/V capture, and optionally fake
197// encoders/decoders, though they aren't used by default since they don't
198// advertise support of any codecs.
Steve Anton94286cb2017-09-26 16:20:19 -0700199// TODO(steveanton): See how this could become a subclass of
Seth Hampson2f0d7022018-02-20 11:54:42 -0800200// PeerConnectionWrapper defined in peerconnectionwrapper.h.
deadbeef1dcb1642017-03-29 21:08:16 -0700201class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
Steve Anton15324772018-01-16 10:26:49 -0800202 public SignalingMessageReceiver {
deadbeef1dcb1642017-03-29 21:08:16 -0700203 public:
204 // Different factory methods for convenience.
205 // TODO(deadbeef): Could use the pattern of:
206 //
207 // PeerConnectionWrapper =
208 // WrapperBuilder.WithConfig(...).WithOptions(...).build();
209 //
210 // To reduce some code duplication.
211 static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
212 const std::string& debug_name,
213 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
214 rtc::Thread* network_thread,
215 rtc::Thread* worker_thread) {
216 PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700217 webrtc::PeerConnectionDependencies dependencies(nullptr);
218 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200219 if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800220 worker_thread, nullptr,
221 /*media_transport_factory=*/nullptr)) {
deadbeef1dcb1642017-03-29 21:08:16 -0700222 delete client;
223 return nullptr;
224 }
225 return client;
226 }
227
deadbeef2f425aa2017-04-14 10:41:32 -0700228 webrtc::PeerConnectionFactoryInterface* pc_factory() const {
229 return peer_connection_factory_.get();
230 }
231
deadbeef1dcb1642017-03-29 21:08:16 -0700232 webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
233
234 // If a signaling message receiver is set (via ConnectFakeSignaling), this
235 // will set the whole offer/answer exchange in motion. Just need to wait for
236 // the signaling state to reach "stable".
237 void CreateAndSetAndSignalOffer() {
238 auto offer = CreateOffer();
239 ASSERT_NE(nullptr, offer);
240 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
241 }
242
243 // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
244 // when a remote offer is received (via fake signaling) and an answer is
245 // generated. By default, uses default options.
246 void SetOfferAnswerOptions(
247 const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
248 offer_answer_options_ = options;
249 }
250
251 // Set a callback to be invoked when SDP is received via the fake signaling
252 // channel, which provides an opportunity to munge (modify) the SDP. This is
253 // used to test SDP being applied that a PeerConnection would normally not
254 // generate, but a non-JSEP endpoint might.
255 void SetReceivedSdpMunger(
256 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100257 received_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700258 }
259
deadbeefc964d0b2017-04-03 10:03:35 -0700260 // Similar to the above, but this is run on SDP immediately after it's
deadbeef1dcb1642017-03-29 21:08:16 -0700261 // generated.
262 void SetGeneratedSdpMunger(
263 std::function<void(cricket::SessionDescription*)> munger) {
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100264 generated_sdp_munger_ = std::move(munger);
deadbeef1dcb1642017-03-29 21:08:16 -0700265 }
266
Seth Hampson2f0d7022018-02-20 11:54:42 -0800267 // Set a callback to be invoked when a remote offer is received via the fake
268 // signaling channel. This provides an opportunity to change the
269 // PeerConnection state before an answer is created and sent to the caller.
270 void SetRemoteOfferHandler(std::function<void()> handler) {
271 remote_offer_handler_ = std::move(handler);
272 }
273
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800274 void SetRemoteAsyncResolver(rtc::MockAsyncResolver* resolver) {
275 remote_async_resolver_ = resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700276 }
277
Steve Antonede9ca52017-10-16 13:04:27 -0700278 // Every ICE connection state in order that has been seen by the observer.
279 std::vector<PeerConnectionInterface::IceConnectionState>
280 ice_connection_state_history() const {
281 return ice_connection_state_history_;
282 }
Steve Anton6f25b092017-10-23 09:39:20 -0700283 void clear_ice_connection_state_history() {
284 ice_connection_state_history_.clear();
285 }
Steve Antonede9ca52017-10-16 13:04:27 -0700286
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100287 // Every standardized ICE connection state in order that has been seen by the
288 // observer.
289 std::vector<PeerConnectionInterface::IceConnectionState>
290 standardized_ice_connection_state_history() const {
291 return standardized_ice_connection_state_history_;
292 }
293
Jonas Olsson635474e2018-10-18 15:58:17 +0200294 // Every PeerConnection state in order that has been seen by the observer.
295 std::vector<PeerConnectionInterface::PeerConnectionState>
296 peer_connection_state_history() const {
297 return peer_connection_state_history_;
298 }
299
Steve Antonede9ca52017-10-16 13:04:27 -0700300 // Every ICE gathering state in order that has been seen by the observer.
301 std::vector<PeerConnectionInterface::IceGatheringState>
302 ice_gathering_state_history() const {
303 return ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -0700304 }
305
Steve Anton15324772018-01-16 10:26:49 -0800306 void AddAudioVideoTracks() {
307 AddAudioTrack();
308 AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -0700309 }
310
Steve Anton74255ff2018-01-24 18:32:57 -0800311 rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
312 return AddTrack(CreateLocalAudioTrack());
313 }
deadbeef1dcb1642017-03-29 21:08:16 -0700314
Steve Anton74255ff2018-01-24 18:32:57 -0800315 rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
316 return AddTrack(CreateLocalVideoTrack());
317 }
deadbeef1dcb1642017-03-29 21:08:16 -0700318
319 rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
Niels Möller2d02e082018-05-21 11:23:35 +0200320 cricket::AudioOptions options;
deadbeef1dcb1642017-03-29 21:08:16 -0700321 // Disable highpass filter so that we can get all the test audio frames.
Niels Möller2d02e082018-05-21 11:23:35 +0200322 options.highpass_filter = false;
deadbeef1dcb1642017-03-29 21:08:16 -0700323 rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
Niels Möller2d02e082018-05-21 11:23:35 +0200324 peer_connection_factory_->CreateAudioSource(options);
deadbeef1dcb1642017-03-29 21:08:16 -0700325 // TODO(perkj): Test audio source when it is implemented. Currently audio
326 // always use the default input.
deadbeefb1a15d72017-09-07 14:12:05 -0700327 return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
deadbeef1dcb1642017-03-29 21:08:16 -0700328 source);
329 }
330
331 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
Johannes Kron965e7942018-09-13 15:36:20 +0200332 webrtc::FakePeriodicVideoSource::Config config;
333 config.timestamp_offset_ms = rtc::TimeMillis();
334 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700335 }
336
337 rtc::scoped_refptr<webrtc::VideoTrackInterface>
Niels Möller5c7efe72018-05-11 10:34:46 +0200338 CreateLocalVideoTrackWithConfig(
339 webrtc::FakePeriodicVideoSource::Config config) {
340 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700341 }
342
343 rtc::scoped_refptr<webrtc::VideoTrackInterface>
344 CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
Niels Möller5c7efe72018-05-11 10:34:46 +0200345 webrtc::FakePeriodicVideoSource::Config config;
346 config.rotation = rotation;
Johannes Kron965e7942018-09-13 15:36:20 +0200347 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +0200348 return CreateLocalVideoTrackInternal(config);
deadbeef1dcb1642017-03-29 21:08:16 -0700349 }
350
Steve Anton74255ff2018-01-24 18:32:57 -0800351 rtc::scoped_refptr<RtpSenderInterface> AddTrack(
352 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -0800353 const std::vector<std::string>& stream_ids = {}) {
354 auto result = pc()->AddTrack(track, stream_ids);
Steve Anton15324772018-01-16 10:26:49 -0800355 EXPECT_EQ(RTCErrorType::NONE, result.error().type());
Steve Anton74255ff2018-01-24 18:32:57 -0800356 return result.MoveValue();
357 }
358
359 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
360 cricket::MediaType media_type) {
361 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
Mirko Bonadei739baf02019-01-27 17:29:42 +0100362 for (const auto& receiver : pc()->GetReceivers()) {
Steve Anton74255ff2018-01-24 18:32:57 -0800363 if (receiver->media_type() == media_type) {
364 receivers.push_back(receiver);
365 }
366 }
367 return receivers;
deadbeef1dcb1642017-03-29 21:08:16 -0700368 }
369
Seth Hampson2f0d7022018-02-20 11:54:42 -0800370 rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
371 cricket::MediaType media_type) {
372 for (auto transceiver : pc()->GetTransceivers()) {
373 if (transceiver->receiver()->media_type() == media_type) {
374 return transceiver;
375 }
376 }
377 return nullptr;
378 }
379
deadbeef1dcb1642017-03-29 21:08:16 -0700380 bool SignalingStateStable() {
381 return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
382 }
383
384 void CreateDataChannel() { CreateDataChannel(nullptr); }
385
386 void CreateDataChannel(const webrtc::DataChannelInit* init) {
Steve Antonda6c0952017-10-23 11:41:54 -0700387 CreateDataChannel(kDataChannelLabel, init);
388 }
389
390 void CreateDataChannel(const std::string& label,
391 const webrtc::DataChannelInit* init) {
392 data_channel_ = pc()->CreateDataChannel(label, init);
deadbeef1dcb1642017-03-29 21:08:16 -0700393 ASSERT_TRUE(data_channel_.get() != nullptr);
394 data_observer_.reset(new MockDataChannelObserver(data_channel_));
395 }
396
397 DataChannelInterface* data_channel() { return data_channel_; }
398 const MockDataChannelObserver* data_observer() const {
399 return data_observer_.get();
400 }
401
402 int audio_frames_received() const {
403 return fake_audio_capture_module_->frames_received();
404 }
405
406 // Takes minimum of video frames received for each track.
407 //
408 // Can be used like:
409 // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
410 //
411 // To ensure that all video tracks received at least a certain number of
412 // frames.
413 int min_video_frames_received_per_track() const {
414 int min_frames = INT_MAX;
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200415 if (fake_video_renderers_.empty()) {
416 return 0;
deadbeef1dcb1642017-03-29 21:08:16 -0700417 }
deadbeef1dcb1642017-03-29 21:08:16 -0700418
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200419 for (const auto& pair : fake_video_renderers_) {
420 min_frames = std::min(min_frames, pair.second->num_rendered_frames());
deadbeef1dcb1642017-03-29 21:08:16 -0700421 }
Anders Carlsson5f2bb622018-05-14 09:48:06 +0200422 return min_frames;
deadbeef1dcb1642017-03-29 21:08:16 -0700423 }
424
425 // Returns a MockStatsObserver in a state after stats gathering finished,
426 // which can be used to access the gathered stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700427 rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
deadbeef1dcb1642017-03-29 21:08:16 -0700428 webrtc::MediaStreamTrackInterface* track) {
429 rtc::scoped_refptr<MockStatsObserver> observer(
430 new rtc::RefCountedObject<MockStatsObserver>());
431 EXPECT_TRUE(peer_connection_->GetStats(
432 observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
433 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
434 return observer;
435 }
436
437 // Version that doesn't take a track "filter", and gathers all stats.
deadbeefd8ad7882017-04-18 16:01:17 -0700438 rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
439 return OldGetStatsForTrack(nullptr);
440 }
441
442 // Synchronously gets stats and returns them. If it times out, fails the test
443 // and returns null.
444 rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
445 rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
446 new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
447 peer_connection_->GetStats(callback);
448 EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
449 return callback->report();
deadbeef1dcb1642017-03-29 21:08:16 -0700450 }
451
452 int rendered_width() {
453 EXPECT_FALSE(fake_video_renderers_.empty());
454 return fake_video_renderers_.empty()
455 ? 0
456 : fake_video_renderers_.begin()->second->width();
457 }
458
459 int rendered_height() {
460 EXPECT_FALSE(fake_video_renderers_.empty());
461 return fake_video_renderers_.empty()
462 ? 0
463 : fake_video_renderers_.begin()->second->height();
464 }
465
466 double rendered_aspect_ratio() {
467 if (rendered_height() == 0) {
468 return 0.0;
469 }
470 return static_cast<double>(rendered_width()) / rendered_height();
471 }
472
473 webrtc::VideoRotation rendered_rotation() {
474 EXPECT_FALSE(fake_video_renderers_.empty());
475 return fake_video_renderers_.empty()
476 ? webrtc::kVideoRotation_0
477 : fake_video_renderers_.begin()->second->rotation();
478 }
479
480 int local_rendered_width() {
481 return local_video_renderer_ ? local_video_renderer_->width() : 0;
482 }
483
484 int local_rendered_height() {
485 return local_video_renderer_ ? local_video_renderer_->height() : 0;
486 }
487
488 double local_rendered_aspect_ratio() {
489 if (local_rendered_height() == 0) {
490 return 0.0;
491 }
492 return static_cast<double>(local_rendered_width()) /
493 local_rendered_height();
494 }
495
496 size_t number_of_remote_streams() {
497 if (!pc()) {
498 return 0;
499 }
500 return pc()->remote_streams()->count();
501 }
502
503 StreamCollectionInterface* remote_streams() const {
504 if (!pc()) {
505 ADD_FAILURE();
506 return nullptr;
507 }
508 return pc()->remote_streams();
509 }
510
511 StreamCollectionInterface* local_streams() {
512 if (!pc()) {
513 ADD_FAILURE();
514 return nullptr;
515 }
516 return pc()->local_streams();
517 }
518
519 webrtc::PeerConnectionInterface::SignalingState signaling_state() {
520 return pc()->signaling_state();
521 }
522
523 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
524 return pc()->ice_connection_state();
525 }
526
Jonas Olsson7a6739e2019-01-15 16:31:55 +0100527 webrtc::PeerConnectionInterface::IceConnectionState
528 standardized_ice_connection_state() {
529 return pc()->standardized_ice_connection_state();
530 }
531
deadbeef1dcb1642017-03-29 21:08:16 -0700532 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
533 return pc()->ice_gathering_state();
534 }
535
536 // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
537 // GetReceivers. They're updated automatically when a remote offer/answer
538 // from the fake signaling channel is applied, or when
539 // ResetRtpReceiverObservers below is called.
540 const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
541 rtp_receiver_observers() {
542 return rtp_receiver_observers_;
543 }
544
545 void ResetRtpReceiverObservers() {
546 rtp_receiver_observers_.clear();
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100547 for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
548 pc()->GetReceivers()) {
deadbeef1dcb1642017-03-29 21:08:16 -0700549 std::unique_ptr<MockRtpReceiverObserver> observer(
550 new MockRtpReceiverObserver(receiver->media_type()));
551 receiver->SetObserver(observer.get());
552 rtp_receiver_observers_.push_back(std::move(observer));
553 }
554 }
555
Qingsi Wangecd30542019-05-22 14:34:56 -0700556 rtc::FakeNetworkManager* network_manager() const {
Steve Antonede9ca52017-10-16 13:04:27 -0700557 return fake_network_manager_.get();
558 }
559 cricket::PortAllocator* port_allocator() const { return port_allocator_; }
560
Qingsi Wang7685e862018-06-11 20:15:46 -0700561 webrtc::FakeRtcEventLogFactory* event_log_factory() const {
562 return event_log_factory_;
563 }
564
Qingsi Wangc129c352019-04-18 10:41:58 -0700565 const cricket::Candidate& last_candidate_gathered() const {
566 return last_candidate_gathered_;
567 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300568 const cricket::IceCandidateErrorEvent& error_event() const {
569 return error_event_;
570 }
Qingsi Wangc129c352019-04-18 10:41:58 -0700571
Qingsi Wangecd30542019-05-22 14:34:56 -0700572 // Sets the mDNS responder for the owned fake network manager and keeps a
573 // reference to the responder.
574 void SetMdnsResponder(
575 std::unique_ptr<webrtc::FakeMdnsResponder> mdns_responder) {
576 RTC_DCHECK(mdns_responder != nullptr);
577 mdns_responder_ = mdns_responder.get();
578 network_manager()->set_mdns_responder(std::move(mdns_responder));
579 }
580
deadbeef1dcb1642017-03-29 21:08:16 -0700581 private:
582 explicit PeerConnectionWrapper(const std::string& debug_name)
583 : debug_name_(debug_name) {}
584
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800585 bool Init(
586 const PeerConnectionFactory::Options* options,
587 const PeerConnectionInterface::RTCConfiguration* config,
588 webrtc::PeerConnectionDependencies dependencies,
589 rtc::Thread* network_thread,
590 rtc::Thread* worker_thread,
591 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
592 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
deadbeef1dcb1642017-03-29 21:08:16 -0700593 // There's an error in this test code if Init ends up being called twice.
594 RTC_DCHECK(!peer_connection_);
595 RTC_DCHECK(!peer_connection_factory_);
596
597 fake_network_manager_.reset(new rtc::FakeNetworkManager());
Steve Antonede9ca52017-10-16 13:04:27 -0700598 fake_network_manager_->AddInterface(kDefaultLocalAddress);
deadbeef1dcb1642017-03-29 21:08:16 -0700599
600 std::unique_ptr<cricket::PortAllocator> port_allocator(
601 new cricket::BasicPortAllocator(fake_network_manager_.get()));
Steve Antonede9ca52017-10-16 13:04:27 -0700602 port_allocator_ = port_allocator.get();
deadbeef1dcb1642017-03-29 21:08:16 -0700603 fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
604 if (!fake_audio_capture_module_) {
605 return false;
606 }
deadbeef1dcb1642017-03-29 21:08:16 -0700607 rtc::Thread* const signaling_thread = rtc::Thread::Current();
Qingsi Wang7685e862018-06-11 20:15:46 -0700608
609 webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
610 pc_factory_dependencies.network_thread = network_thread;
611 pc_factory_dependencies.worker_thread = worker_thread;
612 pc_factory_dependencies.signaling_thread = signaling_thread;
613 pc_factory_dependencies.media_engine =
614 cricket::WebRtcMediaEngineFactory::Create(
615 rtc::scoped_refptr<webrtc::AudioDeviceModule>(
616 fake_audio_capture_module_),
617 webrtc::CreateBuiltinAudioEncoderFactory(),
618 webrtc::CreateBuiltinAudioDecoderFactory(),
619 webrtc::CreateBuiltinVideoEncoderFactory(),
Qingsi Wang59844ce2018-11-01 04:45:53 +0000620 webrtc::CreateBuiltinVideoDecoderFactory(), nullptr,
Qingsi Wang7685e862018-06-11 20:15:46 -0700621 webrtc::AudioProcessingBuilder().Create());
622 pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
623 if (event_log_factory) {
624 event_log_factory_ = event_log_factory.get();
625 pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
626 } else {
627 pc_factory_dependencies.event_log_factory =
628 webrtc::CreateRtcEventLogFactory();
629 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800630 if (media_transport_factory) {
631 pc_factory_dependencies.media_transport_factory =
632 std::move(media_transport_factory);
633 }
Qingsi Wang7685e862018-06-11 20:15:46 -0700634 peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
635 std::move(pc_factory_dependencies));
636
deadbeef1dcb1642017-03-29 21:08:16 -0700637 if (!peer_connection_factory_) {
638 return false;
639 }
640 if (options) {
641 peer_connection_factory_->SetOptions(*options);
642 }
Seth Hampson2f0d7022018-02-20 11:54:42 -0800643 if (config) {
644 sdp_semantics_ = config->sdp_semantics;
645 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700646
647 dependencies.allocator = std::move(port_allocator);
Niels Möllerf06f9232018-08-07 12:32:18 +0200648 peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700649 return peer_connection_.get() != nullptr;
650 }
651
652 rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
deadbeef1dcb1642017-03-29 21:08:16 -0700653 const PeerConnectionInterface::RTCConfiguration* config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700654 webrtc::PeerConnectionDependencies dependencies) {
deadbeef1dcb1642017-03-29 21:08:16 -0700655 PeerConnectionInterface::RTCConfiguration modified_config;
656 // If |config| is null, this will result in a default configuration being
657 // used.
658 if (config) {
659 modified_config = *config;
660 }
661 // Disable resolution adaptation; we don't want it interfering with the
662 // test results.
663 // TODO(deadbeef): Do something more robust. Since we're testing for aspect
664 // ratios and not specific resolutions, is this even necessary?
665 modified_config.set_cpu_adaptation(false);
666
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700667 dependencies.observer = this;
deadbeef1dcb1642017-03-29 21:08:16 -0700668 return peer_connection_factory_->CreatePeerConnection(
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700669 modified_config, std::move(dependencies));
deadbeef1dcb1642017-03-29 21:08:16 -0700670 }
671
672 void set_signaling_message_receiver(
673 SignalingMessageReceiver* signaling_message_receiver) {
674 signaling_message_receiver_ = signaling_message_receiver;
675 }
676
677 void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
678
Steve Antonede9ca52017-10-16 13:04:27 -0700679 void set_signal_ice_candidates(bool signal) {
680 signal_ice_candidates_ = signal;
681 }
682
deadbeef1dcb1642017-03-29 21:08:16 -0700683 rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
Niels Möller5c7efe72018-05-11 10:34:46 +0200684 webrtc::FakePeriodicVideoSource::Config config) {
deadbeef1dcb1642017-03-29 21:08:16 -0700685 // Set max frame rate to 10fps to reduce the risk of test flakiness.
686 // TODO(deadbeef): Do something more robust.
Niels Möller5c7efe72018-05-11 10:34:46 +0200687 config.frame_interval_ms = 100;
deadbeef1dcb1642017-03-29 21:08:16 -0700688
Niels Möller5c7efe72018-05-11 10:34:46 +0200689 video_track_sources_.emplace_back(
Niels Möller0f405822018-05-17 09:16:41 +0200690 new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
691 config, false /* remote */));
deadbeef1dcb1642017-03-29 21:08:16 -0700692 rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
Niels Möller5c7efe72018-05-11 10:34:46 +0200693 peer_connection_factory_->CreateVideoTrack(
694 rtc::CreateRandomUuid(), video_track_sources_.back()));
deadbeef1dcb1642017-03-29 21:08:16 -0700695 if (!local_video_renderer_) {
696 local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
697 }
698 return track;
699 }
700
701 void HandleIncomingOffer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100702 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
Steve Antona3a92c22017-12-07 10:27:41 -0800703 std::unique_ptr<SessionDescriptionInterface> desc =
704 webrtc::CreateSessionDescription(SdpType::kOffer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700705 if (received_sdp_munger_) {
706 received_sdp_munger_(desc->description());
707 }
708
709 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
710 // Setting a remote description may have changed the number of receivers,
711 // so reset the receiver observers.
712 ResetRtpReceiverObservers();
Seth Hampson2f0d7022018-02-20 11:54:42 -0800713 if (remote_offer_handler_) {
714 remote_offer_handler_();
715 }
deadbeef1dcb1642017-03-29 21:08:16 -0700716 auto answer = CreateAnswer();
717 ASSERT_NE(nullptr, answer);
718 EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
719 }
720
721 void HandleIncomingAnswer(const std::string& msg) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100722 RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
Steve Antona3a92c22017-12-07 10:27:41 -0800723 std::unique_ptr<SessionDescriptionInterface> desc =
724 webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
deadbeef1dcb1642017-03-29 21:08:16 -0700725 if (received_sdp_munger_) {
726 received_sdp_munger_(desc->description());
727 }
728
729 EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
730 // Set the RtpReceiverObserver after receivers are created.
731 ResetRtpReceiverObservers();
732 }
733
734 // Returns null on failure.
735 std::unique_ptr<SessionDescriptionInterface> CreateOffer() {
736 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
737 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
738 pc()->CreateOffer(observer, offer_answer_options_);
739 return WaitForDescriptionFromObserver(observer);
740 }
741
742 // Returns null on failure.
743 std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
744 rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
745 new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
746 pc()->CreateAnswer(observer, offer_answer_options_);
747 return WaitForDescriptionFromObserver(observer);
748 }
749
750 std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
Mirko Bonadeic61ce0d2017-11-21 17:04:20 +0100751 MockCreateSessionDescriptionObserver* observer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700752 EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
753 if (!observer->result()) {
754 return nullptr;
755 }
756 auto description = observer->MoveDescription();
757 if (generated_sdp_munger_) {
758 generated_sdp_munger_(description->description());
759 }
760 return description;
761 }
762
763 // Setting the local description and sending the SDP message over the fake
764 // signaling channel are combined into the same method because the SDP
765 // message needs to be sent as soon as SetLocalDescription finishes, without
766 // waiting for the observer to be called. This ensures that ICE candidates
767 // don't outrace the description.
768 bool SetLocalDescriptionAndSendSdpMessage(
769 std::unique_ptr<SessionDescriptionInterface> desc) {
770 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
771 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100772 RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
Steve Antona3a92c22017-12-07 10:27:41 -0800773 SdpType type = desc->GetType();
deadbeef1dcb1642017-03-29 21:08:16 -0700774 std::string sdp;
775 EXPECT_TRUE(desc->ToString(&sdp));
776 pc()->SetLocalDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800777 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
778 RemoveUnusedVideoRenderers();
779 }
deadbeef1dcb1642017-03-29 21:08:16 -0700780 // As mentioned above, we need to send the message immediately after
781 // SetLocalDescription.
782 SendSdpMessage(type, sdp);
783 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
784 return true;
785 }
786
787 bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
788 rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
789 new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
Mirko Bonadei675513b2017-11-09 11:09:25 +0100790 RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
deadbeef1dcb1642017-03-29 21:08:16 -0700791 pc()->SetRemoteDescription(observer, desc.release());
Seth Hampson2f0d7022018-02-20 11:54:42 -0800792 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
793 RemoveUnusedVideoRenderers();
794 }
deadbeef1dcb1642017-03-29 21:08:16 -0700795 EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
796 return observer->result();
797 }
798
Seth Hampson2f0d7022018-02-20 11:54:42 -0800799 // This is a work around to remove unused fake_video_renderers from
800 // transceivers that have either stopped or are no longer receiving.
801 void RemoveUnusedVideoRenderers() {
802 auto transceivers = pc()->GetTransceivers();
803 for (auto& transceiver : transceivers) {
804 if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
805 continue;
806 }
807 // Remove fake video renderers from any stopped transceivers.
808 if (transceiver->stopped()) {
809 auto it =
810 fake_video_renderers_.find(transceiver->receiver()->track()->id());
811 if (it != fake_video_renderers_.end()) {
812 fake_video_renderers_.erase(it);
813 }
814 }
815 // Remove fake video renderers from any transceivers that are no longer
816 // receiving.
817 if ((transceiver->current_direction() &&
818 !webrtc::RtpTransceiverDirectionHasRecv(
819 *transceiver->current_direction()))) {
820 auto it =
821 fake_video_renderers_.find(transceiver->receiver()->track()->id());
822 if (it != fake_video_renderers_.end()) {
823 fake_video_renderers_.erase(it);
824 }
825 }
826 }
827 }
828
deadbeef1dcb1642017-03-29 21:08:16 -0700829 // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
830 // default).
Steve Antona3a92c22017-12-07 10:27:41 -0800831 void SendSdpMessage(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700832 if (signaling_delay_ms_ == 0) {
833 RelaySdpMessageIfReceiverExists(type, msg);
834 } else {
835 invoker_.AsyncInvokeDelayed<void>(
836 RTC_FROM_HERE, rtc::Thread::Current(),
837 rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
838 this, type, msg),
839 signaling_delay_ms_);
840 }
841 }
842
Steve Antona3a92c22017-12-07 10:27:41 -0800843 void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
deadbeef1dcb1642017-03-29 21:08:16 -0700844 if (signaling_message_receiver_) {
845 signaling_message_receiver_->ReceiveSdpMessage(type, msg);
846 }
847 }
848
849 // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
850 // default).
851 void SendIceMessage(const std::string& sdp_mid,
852 int sdp_mline_index,
853 const std::string& msg) {
854 if (signaling_delay_ms_ == 0) {
855 RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
856 } else {
857 invoker_.AsyncInvokeDelayed<void>(
858 RTC_FROM_HERE, rtc::Thread::Current(),
859 rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
860 this, sdp_mid, sdp_mline_index, msg),
861 signaling_delay_ms_);
862 }
863 }
864
865 void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
866 int sdp_mline_index,
867 const std::string& msg) {
868 if (signaling_message_receiver_) {
869 signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
870 msg);
871 }
872 }
873
874 // SignalingMessageReceiver callbacks.
Steve Antona3a92c22017-12-07 10:27:41 -0800875 void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
876 if (type == SdpType::kOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -0700877 HandleIncomingOffer(msg);
878 } else {
879 HandleIncomingAnswer(msg);
880 }
881 }
882
883 void ReceiveIceMessage(const std::string& sdp_mid,
884 int sdp_mline_index,
885 const std::string& msg) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100886 RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
deadbeef1dcb1642017-03-29 21:08:16 -0700887 std::unique_ptr<webrtc::IceCandidateInterface> candidate(
888 webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
889 EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
890 }
891
892 // PeerConnectionObserver callbacks.
893 void OnSignalingChange(
894 webrtc::PeerConnectionInterface::SignalingState new_state) override {
895 EXPECT_EQ(pc()->signaling_state(), new_state);
896 }
Steve Anton15324772018-01-16 10:26:49 -0800897 void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
898 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
899 streams) override {
900 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
901 rtc::scoped_refptr<VideoTrackInterface> video_track(
902 static_cast<VideoTrackInterface*>(receiver->track().get()));
903 ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
deadbeef1dcb1642017-03-29 21:08:16 -0700904 fake_video_renderers_.end());
Steve Anton15324772018-01-16 10:26:49 -0800905 fake_video_renderers_[video_track->id()] =
Karl Wiberg918f50c2018-07-05 11:40:33 +0200906 absl::make_unique<FakeVideoTrackRenderer>(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -0700907 }
908 }
Steve Anton15324772018-01-16 10:26:49 -0800909 void OnRemoveTrack(
910 rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
911 if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
912 auto it = fake_video_renderers_.find(receiver->track()->id());
913 RTC_DCHECK(it != fake_video_renderers_.end());
914 fake_video_renderers_.erase(it);
915 }
916 }
deadbeef1dcb1642017-03-29 21:08:16 -0700917 void OnRenegotiationNeeded() override {}
918 void OnIceConnectionChange(
919 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
920 EXPECT_EQ(pc()->ice_connection_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700921 ice_connection_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700922 }
Jonas Olssonacd8ae72019-02-25 15:26:24 +0100923 void OnStandardizedIceConnectionChange(
924 webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
925 standardized_ice_connection_state_history_.push_back(new_state);
926 }
Jonas Olsson635474e2018-10-18 15:58:17 +0200927 void OnConnectionChange(
928 webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
929 peer_connection_state_history_.push_back(new_state);
930 }
931
deadbeef1dcb1642017-03-29 21:08:16 -0700932 void OnIceGatheringChange(
933 webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
deadbeef1dcb1642017-03-29 21:08:16 -0700934 EXPECT_EQ(pc()->ice_gathering_state(), new_state);
Steve Antonede9ca52017-10-16 13:04:27 -0700935 ice_gathering_state_history_.push_back(new_state);
deadbeef1dcb1642017-03-29 21:08:16 -0700936 }
937 void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100938 RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
deadbeef1dcb1642017-03-29 21:08:16 -0700939
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800940 if (remote_async_resolver_) {
941 const auto& local_candidate = candidate->candidate();
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800942 if (local_candidate.address().IsUnresolvedIP()) {
943 RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
944 rtc::SocketAddress resolved_addr(local_candidate.address());
Qingsi Wangecd30542019-05-22 14:34:56 -0700945 const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800946 local_candidate.address().hostname());
947 RTC_DCHECK(!resolved_ip.IsNil());
948 resolved_addr.SetResolvedIP(resolved_ip);
949 EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
950 .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
951 EXPECT_CALL(*remote_async_resolver_, Destroy(_));
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700952 }
Zach Stein6fcdc2f2018-08-23 16:25:55 -0700953 }
954
deadbeef1dcb1642017-03-29 21:08:16 -0700955 std::string ice_sdp;
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800956 EXPECT_TRUE(candidate->ToString(&ice_sdp));
Steve Antonede9ca52017-10-16 13:04:27 -0700957 if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
deadbeef1dcb1642017-03-29 21:08:16 -0700958 // Remote party may be deleted.
959 return;
960 }
Qingsi Wang1dac6d82018-12-12 15:28:47 -0800961 SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
Qingsi Wangc129c352019-04-18 10:41:58 -0700962 last_candidate_gathered_ = candidate->candidate();
deadbeef1dcb1642017-03-29 21:08:16 -0700963 }
Eldar Relloda13ea22019-06-01 12:23:43 +0300964 void OnIceCandidateError(const std::string& host_candidate,
965 const std::string& url,
966 int error_code,
967 const std::string& error_text) override {
968 error_event_ = cricket::IceCandidateErrorEvent(host_candidate, url,
969 error_code, error_text);
970 }
deadbeef1dcb1642017-03-29 21:08:16 -0700971 void OnDataChannel(
972 rtc::scoped_refptr<DataChannelInterface> data_channel) override {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100973 RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
deadbeef1dcb1642017-03-29 21:08:16 -0700974 data_channel_ = data_channel;
975 data_observer_.reset(new MockDataChannelObserver(data_channel));
976 }
977
deadbeef1dcb1642017-03-29 21:08:16 -0700978 std::string debug_name_;
979
980 std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
Qingsi Wangecd30542019-05-22 14:34:56 -0700981 // Reference to the mDNS responder owned by |fake_network_manager_| after set.
982 webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -0700983
984 rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
985 rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
986 peer_connection_factory_;
987
Steve Antonede9ca52017-10-16 13:04:27 -0700988 cricket::PortAllocator* port_allocator_;
deadbeef1dcb1642017-03-29 21:08:16 -0700989 // Needed to keep track of number of frames sent.
990 rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
991 // Needed to keep track of number of frames received.
992 std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
993 fake_video_renderers_;
994 // Needed to ensure frames aren't received for removed tracks.
995 std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
996 removed_fake_video_renderers_;
deadbeef1dcb1642017-03-29 21:08:16 -0700997
998 // For remote peer communication.
999 SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
1000 int signaling_delay_ms_ = 0;
Steve Antonede9ca52017-10-16 13:04:27 -07001001 bool signal_ice_candidates_ = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07001002 cricket::Candidate last_candidate_gathered_;
Eldar Relloda13ea22019-06-01 12:23:43 +03001003 cricket::IceCandidateErrorEvent error_event_;
deadbeef1dcb1642017-03-29 21:08:16 -07001004
Niels Möller5c7efe72018-05-11 10:34:46 +02001005 // Store references to the video sources we've created, so that we can stop
deadbeef1dcb1642017-03-29 21:08:16 -07001006 // them, if required.
Niels Möller5c7efe72018-05-11 10:34:46 +02001007 std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
1008 video_track_sources_;
deadbeef1dcb1642017-03-29 21:08:16 -07001009 // |local_video_renderer_| attached to the first created local video track.
1010 std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
1011
Seth Hampson2f0d7022018-02-20 11:54:42 -08001012 SdpSemantics sdp_semantics_;
deadbeef1dcb1642017-03-29 21:08:16 -07001013 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
1014 std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
1015 std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001016 std::function<void()> remote_offer_handler_;
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001017 rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
deadbeef1dcb1642017-03-29 21:08:16 -07001018 rtc::scoped_refptr<DataChannelInterface> data_channel_;
1019 std::unique_ptr<MockDataChannelObserver> data_observer_;
1020
1021 std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
1022
Steve Antonede9ca52017-10-16 13:04:27 -07001023 std::vector<PeerConnectionInterface::IceConnectionState>
1024 ice_connection_state_history_;
Jonas Olssonacd8ae72019-02-25 15:26:24 +01001025 std::vector<PeerConnectionInterface::IceConnectionState>
1026 standardized_ice_connection_state_history_;
Jonas Olsson635474e2018-10-18 15:58:17 +02001027 std::vector<PeerConnectionInterface::PeerConnectionState>
1028 peer_connection_state_history_;
Steve Antonede9ca52017-10-16 13:04:27 -07001029 std::vector<PeerConnectionInterface::IceGatheringState>
1030 ice_gathering_state_history_;
deadbeef1dcb1642017-03-29 21:08:16 -07001031
Qingsi Wang7685e862018-06-11 20:15:46 -07001032 webrtc::FakeRtcEventLogFactory* event_log_factory_;
1033
deadbeef1dcb1642017-03-29 21:08:16 -07001034 rtc::AsyncInvoker invoker_;
1035
Seth Hampson2f0d7022018-02-20 11:54:42 -08001036 friend class PeerConnectionIntegrationBaseTest;
deadbeef1dcb1642017-03-29 21:08:16 -07001037};
1038
Elad Alon99c3fe52017-10-13 16:29:40 +02001039class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
1040 public:
1041 virtual ~MockRtcEventLogOutput() = default;
1042 MOCK_CONST_METHOD0(IsActive, bool());
1043 MOCK_METHOD1(Write, bool(const std::string&));
1044};
1045
Seth Hampson2f0d7022018-02-20 11:54:42 -08001046// This helper object is used for both specifying how many audio/video frames
1047// are expected to be received for a caller/callee. It provides helper functions
1048// to specify these expectations. The object initially starts in a state of no
1049// expectations.
1050class MediaExpectations {
1051 public:
1052 enum ExpectFrames {
1053 kExpectSomeFrames,
1054 kExpectNoFrames,
1055 kNoExpectation,
1056 };
1057
1058 void ExpectBidirectionalAudioAndVideo() {
1059 ExpectBidirectionalAudio();
1060 ExpectBidirectionalVideo();
1061 }
1062
1063 void ExpectBidirectionalAudio() {
1064 CallerExpectsSomeAudio();
1065 CalleeExpectsSomeAudio();
1066 }
1067
1068 void ExpectNoAudio() {
1069 CallerExpectsNoAudio();
1070 CalleeExpectsNoAudio();
1071 }
1072
1073 void ExpectBidirectionalVideo() {
1074 CallerExpectsSomeVideo();
1075 CalleeExpectsSomeVideo();
1076 }
1077
1078 void ExpectNoVideo() {
1079 CallerExpectsNoVideo();
1080 CalleeExpectsNoVideo();
1081 }
1082
1083 void CallerExpectsSomeAudioAndVideo() {
1084 CallerExpectsSomeAudio();
1085 CallerExpectsSomeVideo();
1086 }
1087
1088 void CalleeExpectsSomeAudioAndVideo() {
1089 CalleeExpectsSomeAudio();
1090 CalleeExpectsSomeVideo();
1091 }
1092
1093 // Caller's audio functions.
1094 void CallerExpectsSomeAudio(
1095 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1096 caller_audio_expectation_ = kExpectSomeFrames;
1097 caller_audio_frames_expected_ = expected_audio_frames;
1098 }
1099
1100 void CallerExpectsNoAudio() {
1101 caller_audio_expectation_ = kExpectNoFrames;
1102 caller_audio_frames_expected_ = 0;
1103 }
1104
1105 // Caller's video functions.
1106 void CallerExpectsSomeVideo(
1107 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1108 caller_video_expectation_ = kExpectSomeFrames;
1109 caller_video_frames_expected_ = expected_video_frames;
1110 }
1111
1112 void CallerExpectsNoVideo() {
1113 caller_video_expectation_ = kExpectNoFrames;
1114 caller_video_frames_expected_ = 0;
1115 }
1116
1117 // Callee's audio functions.
1118 void CalleeExpectsSomeAudio(
1119 int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
1120 callee_audio_expectation_ = kExpectSomeFrames;
1121 callee_audio_frames_expected_ = expected_audio_frames;
1122 }
1123
1124 void CalleeExpectsNoAudio() {
1125 callee_audio_expectation_ = kExpectNoFrames;
1126 callee_audio_frames_expected_ = 0;
1127 }
1128
1129 // Callee's video functions.
1130 void CalleeExpectsSomeVideo(
1131 int expected_video_frames = kDefaultExpectedVideoFrameCount) {
1132 callee_video_expectation_ = kExpectSomeFrames;
1133 callee_video_frames_expected_ = expected_video_frames;
1134 }
1135
1136 void CalleeExpectsNoVideo() {
1137 callee_video_expectation_ = kExpectNoFrames;
1138 callee_video_frames_expected_ = 0;
1139 }
1140
1141 ExpectFrames caller_audio_expectation_ = kNoExpectation;
1142 ExpectFrames caller_video_expectation_ = kNoExpectation;
1143 ExpectFrames callee_audio_expectation_ = kNoExpectation;
1144 ExpectFrames callee_video_expectation_ = kNoExpectation;
1145 int caller_audio_frames_expected_ = 0;
1146 int caller_video_frames_expected_ = 0;
1147 int callee_audio_frames_expected_ = 0;
1148 int callee_video_frames_expected_ = 0;
1149};
1150
deadbeef1dcb1642017-03-29 21:08:16 -07001151// Tests two PeerConnections connecting to each other end-to-end, using a
1152// virtual network, fake A/V capture and fake encoder/decoders. The
1153// PeerConnections share the threads/socket servers, but use separate versions
1154// of everything else (including "PeerConnectionFactory"s).
Mirko Bonadei6a489f22019-04-09 15:11:12 +02001155class PeerConnectionIntegrationBaseTest : public ::testing::Test {
deadbeef1dcb1642017-03-29 21:08:16 -07001156 public:
Seth Hampson2f0d7022018-02-20 11:54:42 -08001157 explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
1158 : sdp_semantics_(sdp_semantics),
1159 ss_(new rtc::VirtualSocketServer()),
Steve Antonede9ca52017-10-16 13:04:27 -07001160 fss_(new rtc::FirewallSocketServer(ss_.get())),
1161 network_thread_(new rtc::Thread(fss_.get())),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001162 worker_thread_(rtc::Thread::Create()),
1163 loopback_media_transports_(network_thread_.get()) {
Sebastian Jansson8a793a02018-03-13 15:21:48 +01001164 network_thread_->SetName("PCNetworkThread", this);
1165 worker_thread_->SetName("PCWorkerThread", this);
deadbeef1dcb1642017-03-29 21:08:16 -07001166 RTC_CHECK(network_thread_->Start());
1167 RTC_CHECK(worker_thread_->Start());
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001168 webrtc::metrics::Reset();
deadbeef1dcb1642017-03-29 21:08:16 -07001169 }
1170
Seth Hampson2f0d7022018-02-20 11:54:42 -08001171 ~PeerConnectionIntegrationBaseTest() {
Seth Hampsonaed71642018-06-11 07:41:32 -07001172 // The PeerConnections should deleted before the TurnCustomizers.
1173 // A TurnPort is created with a raw pointer to a TurnCustomizer. The
1174 // TurnPort has the same lifetime as the PeerConnection, so it's expected
1175 // that the TurnCustomizer outlives the life of the PeerConnection or else
1176 // when Send() is called it will hit a seg fault.
deadbeef1dcb1642017-03-29 21:08:16 -07001177 if (caller_) {
1178 caller_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001179 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001180 }
1181 if (callee_) {
1182 callee_->set_signaling_message_receiver(nullptr);
Seth Hampsonaed71642018-06-11 07:41:32 -07001183 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001184 }
Seth Hampsonaed71642018-06-11 07:41:32 -07001185
1186 // If turn servers were created for the test they need to be destroyed on
1187 // the network thread.
1188 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1189 turn_servers_.clear();
1190 turn_customizers_.clear();
1191 });
deadbeef1dcb1642017-03-29 21:08:16 -07001192 }
1193
1194 bool SignalingStateStable() {
1195 return caller_->SignalingStateStable() && callee_->SignalingStateStable();
1196 }
1197
deadbeef71452802017-05-07 17:21:01 -07001198 bool DtlsConnected() {
Alex Loiko9289eda2018-11-23 16:18:59 +00001199 // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
1200 // are connected. This is an important distinction. Once we have separate
1201 // ICE and DTLS state, this check needs to use the DTLS state.
1202 return (callee()->ice_connection_state() ==
1203 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1204 callee()->ice_connection_state() ==
1205 webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
1206 (caller()->ice_connection_state() ==
1207 webrtc::PeerConnectionInterface::kIceConnectionConnected ||
1208 caller()->ice_connection_state() ==
1209 webrtc::PeerConnectionInterface::kIceConnectionCompleted);
deadbeef71452802017-05-07 17:21:01 -07001210 }
1211
Qingsi Wang7685e862018-06-11 20:15:46 -07001212 // When |event_log_factory| is null, the default implementation of the event
1213 // log factory will be used.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001214 std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
1215 const std::string& debug_name,
Seth Hampson2f0d7022018-02-20 11:54:42 -08001216 const PeerConnectionFactory::Options* options,
1217 const RTCConfiguration* config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001218 webrtc::PeerConnectionDependencies dependencies,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001219 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
1220 std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001221 RTCConfiguration modified_config;
1222 if (config) {
1223 modified_config = *config;
1224 }
Steve Anton3acffc32018-04-12 17:21:03 -07001225 modified_config.sdp_semantics = sdp_semantics_;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001226 if (!dependencies.cert_generator) {
1227 dependencies.cert_generator =
Karl Wiberg918f50c2018-07-05 11:40:33 +02001228 absl::make_unique<FakeRTCCertificateGenerator>();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001229 }
1230 std::unique_ptr<PeerConnectionWrapper> client(
1231 new PeerConnectionWrapper(debug_name));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001232
Niels Möllerf06f9232018-08-07 12:32:18 +02001233 if (!client->Init(options, &modified_config, std::move(dependencies),
1234 network_thread_.get(), worker_thread_.get(),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001235 std::move(event_log_factory),
1236 std::move(media_transport_factory))) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08001237 return nullptr;
1238 }
1239 return client;
1240 }
1241
Qingsi Wang7685e862018-06-11 20:15:46 -07001242 std::unique_ptr<PeerConnectionWrapper>
1243 CreatePeerConnectionWrapperWithFakeRtcEventLog(
1244 const std::string& debug_name,
Qingsi Wang7685e862018-06-11 20:15:46 -07001245 const PeerConnectionFactory::Options* options,
1246 const RTCConfiguration* config,
1247 webrtc::PeerConnectionDependencies dependencies) {
1248 std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
1249 new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
Niels Möllerf06f9232018-08-07 12:32:18 +02001250 return CreatePeerConnectionWrapper(debug_name, options, config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001251 std::move(dependencies),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001252 std::move(event_log_factory),
1253 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001254 }
1255
deadbeef1dcb1642017-03-29 21:08:16 -07001256 bool CreatePeerConnectionWrappers() {
1257 return CreatePeerConnectionWrappersWithConfig(
1258 PeerConnectionInterface::RTCConfiguration(),
1259 PeerConnectionInterface::RTCConfiguration());
1260 }
1261
Steve Anton3acffc32018-04-12 17:21:03 -07001262 bool CreatePeerConnectionWrappersWithSdpSemantics(
1263 SdpSemantics caller_semantics,
1264 SdpSemantics callee_semantics) {
1265 // Can't specify the sdp_semantics in the passed-in configuration since it
1266 // will be overwritten by CreatePeerConnectionWrapper with whatever is
1267 // stored in sdp_semantics_. So get around this by modifying the instance
1268 // variable before calling CreatePeerConnectionWrapper for the caller and
1269 // callee PeerConnections.
1270 SdpSemantics original_semantics = sdp_semantics_;
1271 sdp_semantics_ = caller_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001272 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001273 "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001274 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001275 sdp_semantics_ = callee_semantics;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001276 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001277 "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001278 nullptr, /*media_transport_factory=*/nullptr);
Steve Anton3acffc32018-04-12 17:21:03 -07001279 sdp_semantics_ = original_semantics;
1280 return caller_ && callee_;
1281 }
1282
deadbeef1dcb1642017-03-29 21:08:16 -07001283 bool CreatePeerConnectionWrappersWithConfig(
1284 const PeerConnectionInterface::RTCConfiguration& caller_config,
1285 const PeerConnectionInterface::RTCConfiguration& callee_config) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001286 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001287 "Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001288 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1289 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001290 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001291 "Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001292 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1293 /*media_transport_factory=*/nullptr);
1294 return caller_ && callee_;
1295 }
1296
1297 bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
1298 const PeerConnectionInterface::RTCConfiguration& caller_config,
1299 const PeerConnectionInterface::RTCConfiguration& callee_config,
1300 std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
1301 std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
1302 caller_ =
1303 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
1304 webrtc::PeerConnectionDependencies(nullptr),
1305 nullptr, std::move(caller_factory));
1306 callee_ =
1307 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
1308 webrtc::PeerConnectionDependencies(nullptr),
1309 nullptr, std::move(callee_factory));
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001310 return caller_ && callee_;
1311 }
1312
1313 bool CreatePeerConnectionWrappersWithConfigAndDeps(
1314 const PeerConnectionInterface::RTCConfiguration& caller_config,
1315 webrtc::PeerConnectionDependencies caller_dependencies,
1316 const PeerConnectionInterface::RTCConfiguration& callee_config,
1317 webrtc::PeerConnectionDependencies callee_dependencies) {
1318 caller_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001319 CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001320 std::move(caller_dependencies), nullptr,
1321 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001322 callee_ =
Niels Möllerf06f9232018-08-07 12:32:18 +02001323 CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001324 std::move(callee_dependencies), nullptr,
1325 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001326 return caller_ && callee_;
1327 }
1328
1329 bool CreatePeerConnectionWrappersWithOptions(
1330 const PeerConnectionFactory::Options& caller_options,
1331 const PeerConnectionFactory::Options& callee_options) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001332 caller_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001333 "Caller", &caller_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001334 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1335 /*media_transport_factory=*/nullptr);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001336 callee_ = CreatePeerConnectionWrapper(
Niels Möllerf06f9232018-08-07 12:32:18 +02001337 "Callee", &callee_options, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001338 webrtc::PeerConnectionDependencies(nullptr), nullptr,
1339 /*media_transport_factory=*/nullptr);
Qingsi Wang7685e862018-06-11 20:15:46 -07001340 return caller_ && callee_;
1341 }
1342
1343 bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
1344 PeerConnectionInterface::RTCConfiguration default_config;
1345 caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001346 "Caller", nullptr, &default_config,
Qingsi Wang7685e862018-06-11 20:15:46 -07001347 webrtc::PeerConnectionDependencies(nullptr));
1348 callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
Niels Möllerf06f9232018-08-07 12:32:18 +02001349 "Callee", nullptr, &default_config,
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001350 webrtc::PeerConnectionDependencies(nullptr));
deadbeef1dcb1642017-03-29 21:08:16 -07001351 return caller_ && callee_;
1352 }
1353
Seth Hampson2f0d7022018-02-20 11:54:42 -08001354 std::unique_ptr<PeerConnectionWrapper>
1355 CreatePeerConnectionWrapperWithAlternateKey() {
deadbeef1dcb1642017-03-29 21:08:16 -07001356 std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
1357 new FakeRTCCertificateGenerator());
1358 cert_generator->use_alternate_key();
1359
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07001360 webrtc::PeerConnectionDependencies dependencies(nullptr);
1361 dependencies.cert_generator = std::move(cert_generator);
Niels Möllerf06f9232018-08-07 12:32:18 +02001362 return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001363 std::move(dependencies), nullptr,
1364 /*media_transport_factory=*/nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07001365 }
1366
Seth Hampsonaed71642018-06-11 07:41:32 -07001367 cricket::TestTurnServer* CreateTurnServer(
1368 rtc::SocketAddress internal_address,
1369 rtc::SocketAddress external_address,
1370 cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
1371 const std::string& common_name = "test turn server") {
1372 rtc::Thread* thread = network_thread();
1373 std::unique_ptr<cricket::TestTurnServer> turn_server =
1374 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
1375 RTC_FROM_HERE,
1376 [thread, internal_address, external_address, type, common_name] {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001377 return absl::make_unique<cricket::TestTurnServer>(
Seth Hampsonaed71642018-06-11 07:41:32 -07001378 thread, internal_address, external_address, type,
1379 /*ignore_bad_certs=*/true, common_name);
1380 });
1381 turn_servers_.push_back(std::move(turn_server));
1382 // Interactions with the turn server should be done on the network thread.
1383 return turn_servers_.back().get();
1384 }
1385
1386 cricket::TestTurnCustomizer* CreateTurnCustomizer() {
1387 std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
1388 network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
1389 RTC_FROM_HERE,
Karl Wiberg918f50c2018-07-05 11:40:33 +02001390 [] { return absl::make_unique<cricket::TestTurnCustomizer>(); });
Seth Hampsonaed71642018-06-11 07:41:32 -07001391 turn_customizers_.push_back(std::move(turn_customizer));
1392 // Interactions with the turn customizer should be done on the network
1393 // thread.
1394 return turn_customizers_.back().get();
1395 }
1396
1397 // Checks that the function counters for a TestTurnCustomizer are greater than
1398 // 0.
1399 void ExpectTurnCustomizerCountersIncremented(
1400 cricket::TestTurnCustomizer* turn_customizer) {
1401 unsigned int allow_channel_data_counter =
1402 network_thread()->Invoke<unsigned int>(
1403 RTC_FROM_HERE, [turn_customizer] {
1404 return turn_customizer->allow_channel_data_cnt_;
1405 });
1406 EXPECT_GT(allow_channel_data_counter, 0u);
1407 unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
1408 RTC_FROM_HERE,
1409 [turn_customizer] { return turn_customizer->modify_cnt_; });
1410 EXPECT_GT(modify_counter, 0u);
1411 }
1412
deadbeef1dcb1642017-03-29 21:08:16 -07001413 // Once called, SDP blobs and ICE candidates will be automatically signaled
1414 // between PeerConnections.
1415 void ConnectFakeSignaling() {
1416 caller_->set_signaling_message_receiver(callee_.get());
1417 callee_->set_signaling_message_receiver(caller_.get());
1418 }
1419
Steve Antonede9ca52017-10-16 13:04:27 -07001420 // Once called, SDP blobs will be automatically signaled between
1421 // PeerConnections. Note that ICE candidates will not be signaled unless they
1422 // are in the exchanged SDP blobs.
1423 void ConnectFakeSignalingForSdpOnly() {
1424 ConnectFakeSignaling();
1425 SetSignalIceCandidates(false);
1426 }
1427
deadbeef1dcb1642017-03-29 21:08:16 -07001428 void SetSignalingDelayMs(int delay_ms) {
1429 caller_->set_signaling_delay_ms(delay_ms);
1430 callee_->set_signaling_delay_ms(delay_ms);
1431 }
1432
Steve Antonede9ca52017-10-16 13:04:27 -07001433 void SetSignalIceCandidates(bool signal) {
1434 caller_->set_signal_ice_candidates(signal);
1435 callee_->set_signal_ice_candidates(signal);
1436 }
1437
deadbeef1dcb1642017-03-29 21:08:16 -07001438 // Messages may get lost on the unreliable DataChannel, so we send multiple
1439 // times to avoid test flakiness.
1440 void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
1441 const std::string& data,
1442 int retries) {
1443 for (int i = 0; i < retries; ++i) {
1444 dc->Send(DataBuffer(data));
1445 }
1446 }
1447
1448 rtc::Thread* network_thread() { return network_thread_.get(); }
1449
1450 rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
1451
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001452 webrtc::MediaTransportPair* loopback_media_transports() {
1453 return &loopback_media_transports_;
1454 }
1455
deadbeef1dcb1642017-03-29 21:08:16 -07001456 PeerConnectionWrapper* caller() { return caller_.get(); }
1457
1458 // Set the |caller_| to the |wrapper| passed in and return the
1459 // original |caller_|.
1460 PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
1461 PeerConnectionWrapper* wrapper) {
1462 PeerConnectionWrapper* old = caller_.release();
1463 caller_.reset(wrapper);
1464 return old;
1465 }
1466
1467 PeerConnectionWrapper* callee() { return callee_.get(); }
1468
1469 // Set the |callee_| to the |wrapper| passed in and return the
1470 // original |callee_|.
1471 PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
1472 PeerConnectionWrapper* wrapper) {
1473 PeerConnectionWrapper* old = callee_.release();
1474 callee_.reset(wrapper);
1475 return old;
1476 }
1477
Qingsi Wang1dac6d82018-12-12 15:28:47 -08001478 void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
1479 network_thread()->Invoke<void>(
1480 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1481 caller()->port_allocator(), caller_flags));
1482 network_thread()->Invoke<void>(
1483 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
1484 callee()->port_allocator(), callee_flags));
1485 }
1486
Steve Antonede9ca52017-10-16 13:04:27 -07001487 rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
1488
Seth Hampson2f0d7022018-02-20 11:54:42 -08001489 // Expects the provided number of new frames to be received within
1490 // kMaxWaitForFramesMs. The new expected frames are specified in
1491 // |media_expectations|. Returns false if any of the expectations were
1492 // not met.
1493 bool ExpectNewFrames(const MediaExpectations& media_expectations) {
1494 // First initialize the expected frame counts based upon the current
1495 // frame count.
1496 int total_caller_audio_frames_expected = caller()->audio_frames_received();
1497 if (media_expectations.caller_audio_expectation_ ==
1498 MediaExpectations::kExpectSomeFrames) {
1499 total_caller_audio_frames_expected +=
1500 media_expectations.caller_audio_frames_expected_;
1501 }
1502 int total_caller_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001503 caller()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001504 if (media_expectations.caller_video_expectation_ ==
1505 MediaExpectations::kExpectSomeFrames) {
1506 total_caller_video_frames_expected +=
1507 media_expectations.caller_video_frames_expected_;
1508 }
1509 int total_callee_audio_frames_expected = callee()->audio_frames_received();
1510 if (media_expectations.callee_audio_expectation_ ==
1511 MediaExpectations::kExpectSomeFrames) {
1512 total_callee_audio_frames_expected +=
1513 media_expectations.callee_audio_frames_expected_;
1514 }
1515 int total_callee_video_frames_expected =
deadbeef1dcb1642017-03-29 21:08:16 -07001516 callee()->min_video_frames_received_per_track();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001517 if (media_expectations.callee_video_expectation_ ==
1518 MediaExpectations::kExpectSomeFrames) {
1519 total_callee_video_frames_expected +=
1520 media_expectations.callee_video_frames_expected_;
1521 }
deadbeef1dcb1642017-03-29 21:08:16 -07001522
Seth Hampson2f0d7022018-02-20 11:54:42 -08001523 // Wait for the expected frames.
deadbeef1dcb1642017-03-29 21:08:16 -07001524 EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001525 total_caller_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001526 caller()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001527 total_caller_video_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001528 callee()->audio_frames_received() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001529 total_callee_audio_frames_expected &&
deadbeef1dcb1642017-03-29 21:08:16 -07001530 callee()->min_video_frames_received_per_track() >=
Seth Hampson2f0d7022018-02-20 11:54:42 -08001531 total_callee_video_frames_expected,
1532 kMaxWaitForFramesMs);
1533 bool expectations_correct =
1534 caller()->audio_frames_received() >=
1535 total_caller_audio_frames_expected &&
1536 caller()->min_video_frames_received_per_track() >=
1537 total_caller_video_frames_expected &&
1538 callee()->audio_frames_received() >=
1539 total_callee_audio_frames_expected &&
1540 callee()->min_video_frames_received_per_track() >=
1541 total_callee_video_frames_expected;
deadbeef1dcb1642017-03-29 21:08:16 -07001542
Seth Hampson2f0d7022018-02-20 11:54:42 -08001543 // After the combined wait, print out a more detailed message upon
1544 // failure.
deadbeef1dcb1642017-03-29 21:08:16 -07001545 EXPECT_GE(caller()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001546 total_caller_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001547 EXPECT_GE(caller()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001548 total_caller_video_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001549 EXPECT_GE(callee()->audio_frames_received(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001550 total_callee_audio_frames_expected);
deadbeef1dcb1642017-03-29 21:08:16 -07001551 EXPECT_GE(callee()->min_video_frames_received_per_track(),
Seth Hampson2f0d7022018-02-20 11:54:42 -08001552 total_callee_video_frames_expected);
1553
1554 // We want to make sure nothing unexpected was received.
1555 if (media_expectations.caller_audio_expectation_ ==
1556 MediaExpectations::kExpectNoFrames) {
1557 EXPECT_EQ(caller()->audio_frames_received(),
1558 total_caller_audio_frames_expected);
1559 if (caller()->audio_frames_received() !=
1560 total_caller_audio_frames_expected) {
1561 expectations_correct = false;
1562 }
1563 }
1564 if (media_expectations.caller_video_expectation_ ==
1565 MediaExpectations::kExpectNoFrames) {
1566 EXPECT_EQ(caller()->min_video_frames_received_per_track(),
1567 total_caller_video_frames_expected);
1568 if (caller()->min_video_frames_received_per_track() !=
1569 total_caller_video_frames_expected) {
1570 expectations_correct = false;
1571 }
1572 }
1573 if (media_expectations.callee_audio_expectation_ ==
1574 MediaExpectations::kExpectNoFrames) {
1575 EXPECT_EQ(callee()->audio_frames_received(),
1576 total_callee_audio_frames_expected);
1577 if (callee()->audio_frames_received() !=
1578 total_callee_audio_frames_expected) {
1579 expectations_correct = false;
1580 }
1581 }
1582 if (media_expectations.callee_video_expectation_ ==
1583 MediaExpectations::kExpectNoFrames) {
1584 EXPECT_EQ(callee()->min_video_frames_received_per_track(),
1585 total_callee_video_frames_expected);
1586 if (callee()->min_video_frames_received_per_track() !=
1587 total_callee_video_frames_expected) {
1588 expectations_correct = false;
1589 }
1590 }
1591 return expectations_correct;
deadbeef1dcb1642017-03-29 21:08:16 -07001592 }
1593
Steve Antond91969e2019-05-30 12:27:03 -07001594 void ClosePeerConnections() {
1595 caller()->pc()->Close();
1596 callee()->pc()->Close();
1597 }
1598
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001599 void TestNegotiatedCipherSuite(
1600 const PeerConnectionFactory::Options& caller_options,
1601 const PeerConnectionFactory::Options& callee_options,
1602 int expected_cipher_suite) {
deadbeef1dcb1642017-03-29 21:08:16 -07001603 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
1604 callee_options));
deadbeef1dcb1642017-03-29 21:08:16 -07001605 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001606 caller()->AddAudioVideoTracks();
1607 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001608 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001609 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001610 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
deadbeefd8ad7882017-04-18 16:01:17 -07001611 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001612 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00001613 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001614 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
1615 expected_cipher_suite));
deadbeef1dcb1642017-03-29 21:08:16 -07001616 }
1617
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001618 void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
1619 bool remote_gcm_enabled,
1620 int expected_cipher_suite) {
1621 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001622 caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
1623 local_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001624 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001625 callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
1626 remote_gcm_enabled;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07001627 TestNegotiatedCipherSuite(caller_options, callee_options,
1628 expected_cipher_suite);
1629 }
1630
Seth Hampson2f0d7022018-02-20 11:54:42 -08001631 protected:
Steve Anton3acffc32018-04-12 17:21:03 -07001632 SdpSemantics sdp_semantics_;
Seth Hampson2f0d7022018-02-20 11:54:42 -08001633
deadbeef1dcb1642017-03-29 21:08:16 -07001634 private:
1635 // |ss_| is used by |network_thread_| so it must be destroyed later.
deadbeef1dcb1642017-03-29 21:08:16 -07001636 std::unique_ptr<rtc::VirtualSocketServer> ss_;
Steve Antonede9ca52017-10-16 13:04:27 -07001637 std::unique_ptr<rtc::FirewallSocketServer> fss_;
deadbeef1dcb1642017-03-29 21:08:16 -07001638 // |network_thread_| and |worker_thread_| are used by both
1639 // |caller_| and |callee_| so they must be destroyed
1640 // later.
1641 std::unique_ptr<rtc::Thread> network_thread_;
1642 std::unique_ptr<rtc::Thread> worker_thread_;
Seth Hampsonaed71642018-06-11 07:41:32 -07001643 // The turn servers and turn customizers should be accessed & deleted on the
1644 // network thread to avoid a race with the socket read/write that occurs
1645 // on the network thread.
1646 std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
1647 std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001648 webrtc::MediaTransportPair loopback_media_transports_;
deadbeef1dcb1642017-03-29 21:08:16 -07001649 std::unique_ptr<PeerConnectionWrapper> caller_;
1650 std::unique_ptr<PeerConnectionWrapper> callee_;
1651};
1652
Seth Hampson2f0d7022018-02-20 11:54:42 -08001653class PeerConnectionIntegrationTest
1654 : public PeerConnectionIntegrationBaseTest,
1655 public ::testing::WithParamInterface<SdpSemantics> {
1656 protected:
1657 PeerConnectionIntegrationTest()
1658 : PeerConnectionIntegrationBaseTest(GetParam()) {}
1659};
1660
1661class PeerConnectionIntegrationTestPlanB
1662 : public PeerConnectionIntegrationBaseTest {
1663 protected:
1664 PeerConnectionIntegrationTestPlanB()
1665 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
1666};
1667
1668class PeerConnectionIntegrationTestUnifiedPlan
1669 : public PeerConnectionIntegrationBaseTest {
1670 protected:
1671 PeerConnectionIntegrationTestUnifiedPlan()
1672 : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
1673};
1674
deadbeef1dcb1642017-03-29 21:08:16 -07001675// Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
1676// includes testing that the callback is invoked if an observer is connected
1677// after the first packet has already been received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001678TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001679 RtpReceiverObserverOnFirstPacketReceived) {
1680 ASSERT_TRUE(CreatePeerConnectionWrappers());
1681 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001682 caller()->AddAudioVideoTracks();
1683 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001684 // Start offer/answer exchange and wait for it to complete.
1685 caller()->CreateAndSetAndSignalOffer();
1686 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1687 // Should be one receiver each for audio/video.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001688 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1689 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001690 // Wait for all "first packet received" callbacks to be fired.
1691 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001692 absl::c_all_of(caller()->rtp_receiver_observers(),
1693 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1694 return o->first_packet_received();
1695 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001696 kMaxWaitForFramesMs);
1697 EXPECT_TRUE_WAIT(
Steve Anton64b626b2019-01-28 17:25:26 -08001698 absl::c_all_of(callee()->rtp_receiver_observers(),
1699 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1700 return o->first_packet_received();
1701 }),
deadbeef1dcb1642017-03-29 21:08:16 -07001702 kMaxWaitForFramesMs);
1703 // If new observers are set after the first packet was already received, the
1704 // callback should still be invoked.
1705 caller()->ResetRtpReceiverObservers();
1706 callee()->ResetRtpReceiverObservers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001707 EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
1708 EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
deadbeef1dcb1642017-03-29 21:08:16 -07001709 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001710 absl::c_all_of(caller()->rtp_receiver_observers(),
1711 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1712 return o->first_packet_received();
1713 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001714 EXPECT_TRUE(
Steve Anton64b626b2019-01-28 17:25:26 -08001715 absl::c_all_of(callee()->rtp_receiver_observers(),
1716 [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
1717 return o->first_packet_received();
1718 }));
deadbeef1dcb1642017-03-29 21:08:16 -07001719}
1720
1721class DummyDtmfObserver : public DtmfSenderObserverInterface {
1722 public:
1723 DummyDtmfObserver() : completed_(false) {}
1724
1725 // Implements DtmfSenderObserverInterface.
1726 void OnToneChange(const std::string& tone) override {
1727 tones_.push_back(tone);
1728 if (tone.empty()) {
1729 completed_ = true;
1730 }
1731 }
1732
1733 const std::vector<std::string>& tones() const { return tones_; }
1734 bool completed() const { return completed_; }
1735
1736 private:
1737 bool completed_;
1738 std::vector<std::string> tones_;
1739};
1740
1741// Assumes |sender| already has an audio track added and the offer/answer
1742// exchange is done.
1743void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
1744 PeerConnectionWrapper* receiver) {
Steve Anton15324772018-01-16 10:26:49 -08001745 // We should be able to get a DTMF sender from the local sender.
1746 rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
1747 sender->pc()->GetSenders().at(0)->GetDtmfSender();
1748 ASSERT_TRUE(dtmf_sender);
deadbeef1dcb1642017-03-29 21:08:16 -07001749 DummyDtmfObserver observer;
deadbeef1dcb1642017-03-29 21:08:16 -07001750 dtmf_sender->RegisterObserver(&observer);
1751
1752 // Test the DtmfSender object just created.
1753 EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
1754 EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
1755
1756 EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
1757 std::vector<std::string> tones = {"1", "a", ""};
1758 EXPECT_EQ(tones, observer.tones());
1759 dtmf_sender->UnregisterObserver();
1760 // TODO(deadbeef): Verify the tones were actually received end-to-end.
1761}
1762
1763// Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
1764// direction).
Seth Hampson2f0d7022018-02-20 11:54:42 -08001765TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
deadbeef1dcb1642017-03-29 21:08:16 -07001766 ASSERT_TRUE(CreatePeerConnectionWrappers());
1767 ConnectFakeSignaling();
1768 // Only need audio for DTMF.
Steve Anton15324772018-01-16 10:26:49 -08001769 caller()->AddAudioTrack();
1770 callee()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07001771 caller()->CreateAndSetAndSignalOffer();
1772 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeef71452802017-05-07 17:21:01 -07001773 // DTLS must finish before the DTMF sender can be used reliably.
1774 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07001775 TestDtmfFromSenderToReceiver(caller(), callee());
1776 TestDtmfFromSenderToReceiver(callee(), caller());
1777}
1778
1779// Basic end-to-end test, verifying media can be encoded/transmitted/decoded
1780// between two connections, using DTLS-SRTP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001781TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
deadbeef1dcb1642017-03-29 21:08:16 -07001782 ASSERT_TRUE(CreatePeerConnectionWrappers());
1783 ConnectFakeSignaling();
Harald Alvestrand194939b2018-01-24 16:04:13 +01001784
deadbeef1dcb1642017-03-29 21:08:16 -07001785 // Do normal offer/answer and wait for some frames to be received in each
1786 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001787 caller()->AddAudioVideoTracks();
1788 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001789 caller()->CreateAndSetAndSignalOffer();
1790 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001791 MediaExpectations media_expectations;
1792 media_expectations.ExpectBidirectionalAudioAndVideo();
1793 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001794 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1795 webrtc::kEnumCounterKeyProtocolDtls));
1796 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1797 webrtc::kEnumCounterKeyProtocolSdes));
deadbeef1dcb1642017-03-29 21:08:16 -07001798}
1799
1800// Uses SDES instead of DTLS for key agreement.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001801TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
deadbeef1dcb1642017-03-29 21:08:16 -07001802 PeerConnectionInterface::RTCConfiguration sdes_config;
1803 sdes_config.enable_dtls_srtp.emplace(false);
1804 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
1805 ConnectFakeSignaling();
1806
1807 // Do normal offer/answer and wait for some frames to be received in each
1808 // direction.
Steve Anton15324772018-01-16 10:26:49 -08001809 caller()->AddAudioVideoTracks();
1810 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001811 caller()->CreateAndSetAndSignalOffer();
1812 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001813 MediaExpectations media_expectations;
1814 media_expectations.ExpectBidirectionalAudioAndVideo();
1815 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Qingsi Wang7fc821d2018-07-12 12:54:53 -07001816 EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1817 webrtc::kEnumCounterKeyProtocolSdes));
1818 EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
1819 webrtc::kEnumCounterKeyProtocolDtls));
deadbeef1dcb1642017-03-29 21:08:16 -07001820}
1821
Steve Anton8c0f7a72017-10-03 10:03:10 -07001822// Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
1823// certificate once the DTLS handshake has finished.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001824TEST_P(PeerConnectionIntegrationTest,
Steve Anton8c0f7a72017-10-03 10:03:10 -07001825 GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
1826 auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
1827 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1828 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1829 return pc->GetRemoteAudioSSLCertificate();
1830 };
Zhi Huang70b820f2018-01-27 14:16:15 -08001831 auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
1832 auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
1833 auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
1834 return pc->GetRemoteAudioSSLCertChain();
1835 };
Steve Anton8c0f7a72017-10-03 10:03:10 -07001836
1837 auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
1838 auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
1839
1840 // Configure each side with a known certificate so they can be compared later.
1841 PeerConnectionInterface::RTCConfiguration caller_config;
1842 caller_config.enable_dtls_srtp.emplace(true);
1843 caller_config.certificates.push_back(caller_cert);
1844 PeerConnectionInterface::RTCConfiguration callee_config;
1845 callee_config.enable_dtls_srtp.emplace(true);
1846 callee_config.certificates.push_back(callee_cert);
1847 ASSERT_TRUE(
1848 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
1849 ConnectFakeSignaling();
1850
1851 // When first initialized, there should not be a remote SSL certificate (and
1852 // calling this method should not crash).
1853 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
1854 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
Zhi Huang70b820f2018-01-27 14:16:15 -08001855 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
1856 EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
Steve Anton8c0f7a72017-10-03 10:03:10 -07001857
Steve Anton15324772018-01-16 10:26:49 -08001858 caller()->AddAudioTrack();
1859 callee()->AddAudioTrack();
Steve Anton8c0f7a72017-10-03 10:03:10 -07001860 caller()->CreateAndSetAndSignalOffer();
1861 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
1862 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
1863
1864 // Once DTLS has been connected, each side should return the other's SSL
1865 // certificate when calling GetRemoteAudioSSLCertificate.
1866
1867 auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
1868 ASSERT_TRUE(caller_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001869 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001870 caller_remote_cert->ToPEMString());
1871
1872 auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
1873 ASSERT_TRUE(callee_remote_cert);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001874 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Steve Anton8c0f7a72017-10-03 10:03:10 -07001875 callee_remote_cert->ToPEMString());
Zhi Huang70b820f2018-01-27 14:16:15 -08001876
1877 auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
1878 ASSERT_TRUE(caller_remote_cert_chain);
1879 ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
1880 auto remote_cert = &caller_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001881 EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001882 remote_cert->ToPEMString());
1883
1884 auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
1885 ASSERT_TRUE(callee_remote_cert_chain);
1886 ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
1887 remote_cert = &callee_remote_cert_chain->Get(0);
Benjamin Wright6c6c9df2018-10-25 01:16:26 -07001888 EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
Zhi Huang70b820f2018-01-27 14:16:15 -08001889 remote_cert->ToPEMString());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001890}
1891
deadbeef1dcb1642017-03-29 21:08:16 -07001892// This test sets up a call between two parties with a source resolution of
1893// 1280x720 and verifies that a 16:9 aspect ratio is received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001894TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07001895 Send1280By720ResolutionAndReceive16To9AspectRatio) {
1896 ASSERT_TRUE(CreatePeerConnectionWrappers());
1897 ConnectFakeSignaling();
1898
Niels Möller5c7efe72018-05-11 10:34:46 +02001899 // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
1900 webrtc::FakePeriodicVideoSource::Config config;
1901 config.width = 1280;
1902 config.height = 720;
Johannes Kron965e7942018-09-13 15:36:20 +02001903 config.timestamp_offset_ms = rtc::TimeMillis();
Niels Möller5c7efe72018-05-11 10:34:46 +02001904 caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
1905 callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
deadbeef1dcb1642017-03-29 21:08:16 -07001906
1907 // Do normal offer/answer and wait for at least one frame to be received in
1908 // each direction.
1909 caller()->CreateAndSetAndSignalOffer();
1910 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
1911 callee()->min_video_frames_received_per_track() > 0,
1912 kMaxWaitForFramesMs);
1913
1914 // Check rendered aspect ratio.
1915 EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
1916 EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
1917 EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
1918 EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
1919}
1920
1921// This test sets up an one-way call, with media only from caller to
1922// callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001923TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
deadbeef1dcb1642017-03-29 21:08:16 -07001924 ASSERT_TRUE(CreatePeerConnectionWrappers());
1925 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08001926 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07001927 caller()->CreateAndSetAndSignalOffer();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001928 MediaExpectations media_expectations;
1929 media_expectations.CalleeExpectsSomeAudioAndVideo();
1930 media_expectations.CallerExpectsNoAudio();
1931 media_expectations.CallerExpectsNoVideo();
1932 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07001933}
1934
1935// This test sets up a audio call initially, with the callee rejecting video
1936// initially. Then later the callee decides to upgrade to audio/video, and
1937// initiates a new offer/answer exchange.
Seth Hampson2f0d7022018-02-20 11:54:42 -08001938TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
deadbeef1dcb1642017-03-29 21:08:16 -07001939 ASSERT_TRUE(CreatePeerConnectionWrappers());
1940 ConnectFakeSignaling();
1941 // Initially, offer an audio/video stream from the caller, but refuse to
1942 // send/receive video on the callee side.
Steve Anton15324772018-01-16 10:26:49 -08001943 caller()->AddAudioVideoTracks();
1944 callee()->AddAudioTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001945 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1946 PeerConnectionInterface::RTCOfferAnswerOptions options;
1947 options.offer_to_receive_video = 0;
1948 callee()->SetOfferAnswerOptions(options);
1949 } else {
1950 callee()->SetRemoteOfferHandler([this] {
1951 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
1952 });
1953 }
deadbeef1dcb1642017-03-29 21:08:16 -07001954 // Do offer/answer and make sure audio is still received end-to-end.
1955 caller()->CreateAndSetAndSignalOffer();
1956 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001957 {
1958 MediaExpectations media_expectations;
1959 media_expectations.ExpectBidirectionalAudio();
1960 media_expectations.ExpectNoVideo();
1961 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1962 }
deadbeef1dcb1642017-03-29 21:08:16 -07001963 // Sanity check that the callee's description has a rejected video section.
1964 ASSERT_NE(nullptr, callee()->pc()->local_description());
1965 const ContentInfo* callee_video_content =
1966 GetFirstVideoContent(callee()->pc()->local_description()->description());
1967 ASSERT_NE(nullptr, callee_video_content);
1968 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001969
deadbeef1dcb1642017-03-29 21:08:16 -07001970 // Now negotiate with video and ensure negotiation succeeds, with video
1971 // frames and additional audio frames being received.
Steve Anton15324772018-01-16 10:26:49 -08001972 callee()->AddVideoTrack();
Seth Hampson2f0d7022018-02-20 11:54:42 -08001973 if (sdp_semantics_ == SdpSemantics::kPlanB) {
1974 PeerConnectionInterface::RTCOfferAnswerOptions options;
1975 options.offer_to_receive_video = 1;
1976 callee()->SetOfferAnswerOptions(options);
1977 } else {
1978 callee()->SetRemoteOfferHandler(nullptr);
1979 caller()->SetRemoteOfferHandler([this] {
1980 // The caller creates a new transceiver to receive video on when receiving
1981 // the offer, but by default it is send only.
1982 auto transceivers = caller()->pc()->GetTransceivers();
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02001983 ASSERT_EQ(3U, transceivers.size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08001984 ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
1985 transceivers[2]->receiver()->media_type());
1986 transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
1987 transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
1988 });
1989 }
deadbeef1dcb1642017-03-29 21:08:16 -07001990 callee()->CreateAndSetAndSignalOffer();
1991 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08001992 {
1993 // Expect additional audio frames to be received after the upgrade.
1994 MediaExpectations media_expectations;
1995 media_expectations.ExpectBidirectionalAudioAndVideo();
1996 ASSERT_TRUE(ExpectNewFrames(media_expectations));
1997 }
deadbeef1dcb1642017-03-29 21:08:16 -07001998}
1999
deadbeef4389b4d2017-09-07 09:07:36 -07002000// Simpler than the above test; just add an audio track to an established
2001// video-only connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002002TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
deadbeef4389b4d2017-09-07 09:07:36 -07002003 ASSERT_TRUE(CreatePeerConnectionWrappers());
2004 ConnectFakeSignaling();
2005 // Do initial offer/answer with just a video track.
Steve Anton15324772018-01-16 10:26:49 -08002006 caller()->AddVideoTrack();
2007 callee()->AddVideoTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002008 caller()->CreateAndSetAndSignalOffer();
2009 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2010 // Now add an audio track and do another offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08002011 caller()->AddAudioTrack();
2012 callee()->AddAudioTrack();
deadbeef4389b4d2017-09-07 09:07:36 -07002013 caller()->CreateAndSetAndSignalOffer();
2014 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2015 // Ensure both audio and video frames are received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002016 MediaExpectations media_expectations;
2017 media_expectations.ExpectBidirectionalAudioAndVideo();
2018 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef4389b4d2017-09-07 09:07:36 -07002019}
2020
deadbeef1dcb1642017-03-29 21:08:16 -07002021// This test sets up a call that's transferred to a new caller with a different
2022// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002023TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
deadbeef1dcb1642017-03-29 21:08:16 -07002024 ASSERT_TRUE(CreatePeerConnectionWrappers());
2025 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002026 caller()->AddAudioVideoTracks();
2027 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002028 caller()->CreateAndSetAndSignalOffer();
2029 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2030
2031 // Keep the original peer around which will still send packets to the
2032 // receiving client. These SRTP packets will be dropped.
2033 std::unique_ptr<PeerConnectionWrapper> original_peer(
2034 SetCallerPcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002035 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002036 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2037 // directly above.
2038 original_peer->pc()->Close();
2039
2040 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002041 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002042 caller()->CreateAndSetAndSignalOffer();
2043 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2044 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002045 MediaExpectations media_expectations;
2046 media_expectations.ExpectBidirectionalAudioAndVideo();
2047 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002048}
2049
2050// This test sets up a call that's transferred to a new callee with a different
2051// DTLS fingerprint.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002052TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
deadbeef1dcb1642017-03-29 21:08:16 -07002053 ASSERT_TRUE(CreatePeerConnectionWrappers());
2054 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002055 caller()->AddAudioVideoTracks();
2056 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002057 caller()->CreateAndSetAndSignalOffer();
2058 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2059
2060 // Keep the original peer around which will still send packets to the
2061 // receiving client. These SRTP packets will be dropped.
2062 std::unique_ptr<PeerConnectionWrapper> original_peer(
2063 SetCalleePcWrapperAndReturnCurrent(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002064 CreatePeerConnectionWrapperWithAlternateKey().release()));
deadbeef1dcb1642017-03-29 21:08:16 -07002065 // TODO(deadbeef): Why do we call Close here? That goes against the comment
2066 // directly above.
2067 original_peer->pc()->Close();
2068
2069 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002070 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002071 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2072 caller()->CreateAndSetAndSignalOffer();
2073 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2074 // Wait for some additional frames to be transmitted end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002075 MediaExpectations media_expectations;
2076 media_expectations.ExpectBidirectionalAudioAndVideo();
2077 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002078}
2079
2080// This test sets up a non-bundled call and negotiates bundling at the same
2081// time as starting an ICE restart. When bundling is in effect in the restart,
2082// the DTLS-SRTP context should be successfully reset.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002083TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
deadbeef1dcb1642017-03-29 21:08:16 -07002084 ASSERT_TRUE(CreatePeerConnectionWrappers());
2085 ConnectFakeSignaling();
2086
Steve Anton15324772018-01-16 10:26:49 -08002087 caller()->AddAudioVideoTracks();
2088 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002089 // Remove the bundle group from the SDP received by the callee.
2090 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2091 desc->RemoveGroupByName("BUNDLE");
2092 });
2093 caller()->CreateAndSetAndSignalOffer();
2094 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002095 {
2096 MediaExpectations media_expectations;
2097 media_expectations.ExpectBidirectionalAudioAndVideo();
2098 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2099 }
deadbeef1dcb1642017-03-29 21:08:16 -07002100 // Now stop removing the BUNDLE group, and trigger an ICE restart.
2101 callee()->SetReceivedSdpMunger(nullptr);
2102 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
2103 caller()->CreateAndSetAndSignalOffer();
2104 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2105
2106 // Expect additional frames to be received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002107 {
2108 MediaExpectations media_expectations;
2109 media_expectations.ExpectBidirectionalAudioAndVideo();
2110 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2111 }
deadbeef1dcb1642017-03-29 21:08:16 -07002112}
2113
2114// Test CVO (Coordination of Video Orientation). If a video source is rotated
2115// and both peers support the CVO RTP header extension, the actual video frames
2116// don't need to be encoded in different resolutions, since the rotation is
2117// communicated through the RTP header extension.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002118TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002119 ASSERT_TRUE(CreatePeerConnectionWrappers());
2120 ConnectFakeSignaling();
2121 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002122 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002123 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002124 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002125 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2126
2127 // Wait for video frames to be received by both sides.
2128 caller()->CreateAndSetAndSignalOffer();
2129 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2130 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2131 callee()->min_video_frames_received_per_track() > 0,
2132 kMaxWaitForFramesMs);
2133
2134 // Ensure that the aspect ratio is unmodified.
2135 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2136 // not just assumed.
2137 EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
2138 EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
2139 EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
2140 EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
2141 // Ensure that the CVO bits were surfaced to the renderer.
2142 EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
2143 EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
2144}
2145
2146// Test that when the CVO extension isn't supported, video is rotated the
2147// old-fashioned way, by encoding rotated frames.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002148TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
deadbeef1dcb1642017-03-29 21:08:16 -07002149 ASSERT_TRUE(CreatePeerConnectionWrappers());
2150 ConnectFakeSignaling();
2151 // Add rotated video tracks.
Steve Anton15324772018-01-16 10:26:49 -08002152 caller()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002153 caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
Steve Anton15324772018-01-16 10:26:49 -08002154 callee()->AddTrack(
deadbeef1dcb1642017-03-29 21:08:16 -07002155 callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
2156
2157 // Remove the CVO extension from the offered SDP.
2158 callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
2159 cricket::VideoContentDescription* video =
2160 GetFirstVideoContentDescription(desc);
2161 video->ClearRtpHeaderExtensions();
2162 });
2163 // Wait for video frames to be received by both sides.
2164 caller()->CreateAndSetAndSignalOffer();
2165 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2166 ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
2167 callee()->min_video_frames_received_per_track() > 0,
2168 kMaxWaitForFramesMs);
2169
2170 // Expect that the aspect ratio is inversed to account for the 90/270 degree
2171 // rotation.
2172 // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
2173 // not just assumed.
2174 EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
2175 EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
2176 EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
2177 EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
2178 // Expect that each endpoint is unaware of the rotation of the other endpoint.
2179 EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
2180 EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
2181}
2182
deadbeef1dcb1642017-03-29 21:08:16 -07002183// Test that if the answerer rejects the audio m= section, no audio is sent or
2184// received, but video still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002185TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002186 ASSERT_TRUE(CreatePeerConnectionWrappers());
2187 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002188 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002189 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2190 // Only add video track for callee, and set offer_to_receive_audio to 0, so
2191 // it will reject the audio m= section completely.
2192 PeerConnectionInterface::RTCOfferAnswerOptions options;
2193 options.offer_to_receive_audio = 0;
2194 callee()->SetOfferAnswerOptions(options);
2195 } else {
2196 // Stopping the audio RtpTransceiver will cause the media section to be
2197 // rejected in the answer.
2198 callee()->SetRemoteOfferHandler([this] {
2199 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
2200 });
2201 }
Steve Anton15324772018-01-16 10:26:49 -08002202 callee()->AddTrack(callee()->CreateLocalVideoTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002203 // Do offer/answer and wait for successful end-to-end video frames.
2204 caller()->CreateAndSetAndSignalOffer();
2205 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002206 MediaExpectations media_expectations;
2207 media_expectations.ExpectBidirectionalVideo();
2208 media_expectations.ExpectNoAudio();
2209 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2210
deadbeef1dcb1642017-03-29 21:08:16 -07002211 // Sanity check that the callee's description has a rejected audio section.
2212 ASSERT_NE(nullptr, callee()->pc()->local_description());
2213 const ContentInfo* callee_audio_content =
2214 GetFirstAudioContent(callee()->pc()->local_description()->description());
2215 ASSERT_NE(nullptr, callee_audio_content);
2216 EXPECT_TRUE(callee_audio_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002217 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2218 // The caller's transceiver should have stopped after receiving the answer.
2219 EXPECT_TRUE(caller()
2220 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
2221 ->stopped());
2222 }
deadbeef1dcb1642017-03-29 21:08:16 -07002223}
2224
2225// Test that if the answerer rejects the video m= section, no video is sent or
2226// received, but audio still can be.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002227TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
deadbeef1dcb1642017-03-29 21:08:16 -07002228 ASSERT_TRUE(CreatePeerConnectionWrappers());
2229 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002230 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002231 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2232 // Only add audio track for callee, and set offer_to_receive_video to 0, so
2233 // it will reject the video m= section completely.
2234 PeerConnectionInterface::RTCOfferAnswerOptions options;
2235 options.offer_to_receive_video = 0;
2236 callee()->SetOfferAnswerOptions(options);
2237 } else {
2238 // Stopping the video RtpTransceiver will cause the media section to be
2239 // rejected in the answer.
2240 callee()->SetRemoteOfferHandler([this] {
2241 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2242 });
2243 }
Steve Anton15324772018-01-16 10:26:49 -08002244 callee()->AddTrack(callee()->CreateLocalAudioTrack());
deadbeef1dcb1642017-03-29 21:08:16 -07002245 // Do offer/answer and wait for successful end-to-end audio frames.
2246 caller()->CreateAndSetAndSignalOffer();
2247 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002248 MediaExpectations media_expectations;
2249 media_expectations.ExpectBidirectionalAudio();
2250 media_expectations.ExpectNoVideo();
2251 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2252
deadbeef1dcb1642017-03-29 21:08:16 -07002253 // Sanity check that the callee's description has a rejected video section.
2254 ASSERT_NE(nullptr, callee()->pc()->local_description());
2255 const ContentInfo* callee_video_content =
2256 GetFirstVideoContent(callee()->pc()->local_description()->description());
2257 ASSERT_NE(nullptr, callee_video_content);
2258 EXPECT_TRUE(callee_video_content->rejected);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002259 if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
2260 // The caller's transceiver should have stopped after receiving the answer.
2261 EXPECT_TRUE(caller()
2262 ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
2263 ->stopped());
2264 }
deadbeef1dcb1642017-03-29 21:08:16 -07002265}
2266
2267// Test that if the answerer rejects both audio and video m= sections, nothing
2268// bad happens.
2269// TODO(deadbeef): Test that a data channel still works. Currently this doesn't
2270// test anything but the fact that negotiation succeeds, which doesn't mean
2271// much.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002272TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
deadbeef1dcb1642017-03-29 21:08:16 -07002273 ASSERT_TRUE(CreatePeerConnectionWrappers());
2274 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002275 caller()->AddAudioVideoTracks();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002276 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2277 // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
2278 // will reject both audio and video m= sections.
2279 PeerConnectionInterface::RTCOfferAnswerOptions options;
2280 options.offer_to_receive_audio = 0;
2281 options.offer_to_receive_video = 0;
2282 callee()->SetOfferAnswerOptions(options);
2283 } else {
2284 callee()->SetRemoteOfferHandler([this] {
2285 // Stopping all transceivers will cause all media sections to be rejected.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002286 for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002287 transceiver->Stop();
2288 }
2289 });
2290 }
deadbeef1dcb1642017-03-29 21:08:16 -07002291 // Do offer/answer and wait for stable signaling state.
2292 caller()->CreateAndSetAndSignalOffer();
2293 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002294
deadbeef1dcb1642017-03-29 21:08:16 -07002295 // Sanity check that the callee's description has rejected m= sections.
2296 ASSERT_NE(nullptr, callee()->pc()->local_description());
2297 const ContentInfo* callee_audio_content =
2298 GetFirstAudioContent(callee()->pc()->local_description()->description());
2299 ASSERT_NE(nullptr, callee_audio_content);
2300 EXPECT_TRUE(callee_audio_content->rejected);
2301 const ContentInfo* callee_video_content =
2302 GetFirstVideoContent(callee()->pc()->local_description()->description());
2303 ASSERT_NE(nullptr, callee_video_content);
2304 EXPECT_TRUE(callee_video_content->rejected);
2305}
2306
2307// This test sets up an audio and video call between two parties. After the
2308// call runs for a while, the caller sends an updated offer with video being
2309// rejected. Once the re-negotiation is done, the video flow should stop and
2310// the audio flow should continue.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002311TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07002312 ASSERT_TRUE(CreatePeerConnectionWrappers());
2313 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002314 caller()->AddAudioVideoTracks();
2315 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002316 caller()->CreateAndSetAndSignalOffer();
2317 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002318 {
2319 MediaExpectations media_expectations;
2320 media_expectations.ExpectBidirectionalAudioAndVideo();
2321 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2322 }
deadbeef1dcb1642017-03-29 21:08:16 -07002323 // Renegotiate, rejecting the video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002324 if (sdp_semantics_ == SdpSemantics::kPlanB) {
2325 caller()->SetGeneratedSdpMunger(
2326 [](cricket::SessionDescription* description) {
2327 for (cricket::ContentInfo& content : description->contents()) {
2328 if (cricket::IsVideoContent(&content)) {
2329 content.rejected = true;
2330 }
2331 }
2332 });
2333 } else {
2334 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
2335 }
deadbeef1dcb1642017-03-29 21:08:16 -07002336 caller()->CreateAndSetAndSignalOffer();
2337 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
2338
2339 // Sanity check that the caller's description has a rejected video section.
2340 ASSERT_NE(nullptr, caller()->pc()->local_description());
2341 const ContentInfo* caller_video_content =
2342 GetFirstVideoContent(caller()->pc()->local_description()->description());
2343 ASSERT_NE(nullptr, caller_video_content);
2344 EXPECT_TRUE(caller_video_content->rejected);
deadbeef1dcb1642017-03-29 21:08:16 -07002345 // Wait for some additional audio frames to be received.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002346 {
2347 MediaExpectations media_expectations;
2348 media_expectations.ExpectBidirectionalAudio();
2349 media_expectations.ExpectNoVideo();
2350 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2351 }
deadbeef1dcb1642017-03-29 21:08:16 -07002352}
2353
Taylor Brandstetter60c8dc82018-04-11 15:20:27 -07002354// Do one offer/answer with audio, another that disables it (rejecting the m=
2355// section), and another that re-enables it. Regression test for:
2356// bugs.webrtc.org/6023
2357TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
2358 ASSERT_TRUE(CreatePeerConnectionWrappers());
2359 ConnectFakeSignaling();
2360
2361 // Add audio track, do normal offer/answer.
2362 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
2363 caller()->CreateLocalAudioTrack();
2364 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
2365 caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2366 caller()->CreateAndSetAndSignalOffer();
2367 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2368
2369 // Remove audio track, and set offer_to_receive_audio to false to cause the
2370 // m= section to be completely disabled, not just "recvonly".
2371 caller()->pc()->RemoveTrack(sender);
2372 PeerConnectionInterface::RTCOfferAnswerOptions options;
2373 options.offer_to_receive_audio = 0;
2374 caller()->SetOfferAnswerOptions(options);
2375 caller()->CreateAndSetAndSignalOffer();
2376 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2377
2378 // Add the audio track again, expecting negotiation to succeed and frames to
2379 // flow.
2380 sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
2381 options.offer_to_receive_audio = 1;
2382 caller()->SetOfferAnswerOptions(options);
2383 caller()->CreateAndSetAndSignalOffer();
2384 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2385
2386 MediaExpectations media_expectations;
2387 media_expectations.CalleeExpectsSomeAudio();
2388 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2389}
2390
deadbeef1dcb1642017-03-29 21:08:16 -07002391// Basic end-to-end test, but without SSRC/MSID signaling. This functionality
2392// is needed to support legacy endpoints.
2393// TODO(deadbeef): When we support the MID extension and demuxing on MID, also
2394// add a test for an end-to-end test without MID signaling either (basically,
2395// the minimum acceptable SDP).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002396TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
deadbeef1dcb1642017-03-29 21:08:16 -07002397 ASSERT_TRUE(CreatePeerConnectionWrappers());
2398 ConnectFakeSignaling();
2399 // Add audio and video, testing that packets can be demuxed on payload type.
Steve Anton15324772018-01-16 10:26:49 -08002400 caller()->AddAudioVideoTracks();
2401 callee()->AddAudioVideoTracks();
deadbeefd8ad7882017-04-18 16:01:17 -07002402 // Remove SSRCs and MSIDs from the received offer SDP.
2403 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
deadbeef1dcb1642017-03-29 21:08:16 -07002404 caller()->CreateAndSetAndSignalOffer();
2405 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002406 MediaExpectations media_expectations;
2407 media_expectations.ExpectBidirectionalAudioAndVideo();
2408 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002409}
2410
Seth Hampson5897a6e2018-04-03 11:16:33 -07002411// Basic end-to-end test, without SSRC signaling. This means that the track
2412// was created properly and frames are delivered when the MSIDs are communicated
2413// with a=msid lines and no a=ssrc lines.
2414TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2415 EndToEndCallWithoutSsrcSignaling) {
2416 const char kStreamId[] = "streamId";
2417 ASSERT_TRUE(CreatePeerConnectionWrappers());
2418 ConnectFakeSignaling();
2419 // Add just audio tracks.
2420 caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
2421 callee()->AddAudioTrack();
2422
2423 // Remove SSRCs from the received offer SDP.
2424 callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
2425 caller()->CreateAndSetAndSignalOffer();
2426 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2427 MediaExpectations media_expectations;
2428 media_expectations.ExpectBidirectionalAudio();
2429 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2430}
2431
Steve Antondf527fd2018-04-27 15:52:03 -07002432// Tests that video flows between multiple video tracks when SSRCs are not
2433// signaled. This exercises the MID RTP header extension which is needed to
2434// demux the incoming video tracks.
2435TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2436 EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
2437 ASSERT_TRUE(CreatePeerConnectionWrappers());
2438 ConnectFakeSignaling();
2439 caller()->AddVideoTrack();
2440 caller()->AddVideoTrack();
2441 callee()->AddVideoTrack();
2442 callee()->AddVideoTrack();
2443
2444 caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2445 callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
2446 caller()->CreateAndSetAndSignalOffer();
2447 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2448 ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
2449 ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
2450
2451 // Expect video to be received in both directions on both tracks.
2452 MediaExpectations media_expectations;
2453 media_expectations.ExpectBidirectionalVideo();
2454 EXPECT_TRUE(ExpectNewFrames(media_expectations));
2455}
2456
Henrik Boström5b147782018-12-04 11:25:05 +01002457TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
2458 ASSERT_TRUE(CreatePeerConnectionWrappers());
2459 ConnectFakeSignaling();
2460 caller()->AddAudioTrack();
2461 caller()->AddVideoTrack();
2462 caller()->CreateAndSetAndSignalOffer();
2463 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2464 auto callee_receivers = callee()->pc()->GetReceivers();
2465 ASSERT_EQ(2u, callee_receivers.size());
2466 EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
2467 EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
2468}
2469
2470TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
2471 ASSERT_TRUE(CreatePeerConnectionWrappers());
2472 ConnectFakeSignaling();
2473 caller()->AddAudioTrack();
2474 caller()->AddVideoTrack();
2475 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2476 caller()->CreateAndSetAndSignalOffer();
2477 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2478 auto callee_receivers = callee()->pc()->GetReceivers();
2479 ASSERT_EQ(2u, callee_receivers.size());
2480 ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
2481 ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
2482 EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
2483 callee_receivers[1]->stream_ids()[0]);
2484 EXPECT_EQ(callee_receivers[0]->streams()[0],
2485 callee_receivers[1]->streams()[0]);
2486}
2487
deadbeef1dcb1642017-03-29 21:08:16 -07002488// Test that if two video tracks are sent (from caller to callee, in this test),
2489// they're transmitted correctly end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002490TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
deadbeef1dcb1642017-03-29 21:08:16 -07002491 ASSERT_TRUE(CreatePeerConnectionWrappers());
2492 ConnectFakeSignaling();
2493 // Add one audio/video stream, and one video-only stream.
Steve Anton15324772018-01-16 10:26:49 -08002494 caller()->AddAudioVideoTracks();
2495 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002496 caller()->CreateAndSetAndSignalOffer();
2497 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton15324772018-01-16 10:26:49 -08002498 ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
Seth Hampson2f0d7022018-02-20 11:54:42 -08002499
2500 MediaExpectations media_expectations;
2501 media_expectations.CalleeExpectsSomeAudioAndVideo();
2502 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002503}
2504
2505static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
2506 bool first = true;
2507 for (cricket::ContentInfo& content : desc->contents()) {
2508 if (first) {
2509 first = false;
2510 continue;
2511 }
2512 content.bundle_only = true;
2513 }
2514 first = true;
2515 for (cricket::TransportInfo& transport : desc->transport_infos()) {
2516 if (first) {
2517 first = false;
2518 continue;
2519 }
2520 transport.description.ice_ufrag.clear();
2521 transport.description.ice_pwd.clear();
2522 transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
2523 transport.description.identity_fingerprint.reset(nullptr);
2524 }
2525}
2526
2527// Test that if applying a true "max bundle" offer, which uses ports of 0,
2528// "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
2529// "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
2530// successfully and media flows.
2531// TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
2532// TODO(deadbeef): Won't need this test once we start generating actual
2533// standards-compliant SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002534TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07002535 EndToEndCallWithSpecCompliantMaxBundleOffer) {
2536 ASSERT_TRUE(CreatePeerConnectionWrappers());
2537 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002538 caller()->AddAudioVideoTracks();
2539 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002540 // Do the equivalent of setting the port to 0, adding a=bundle-only, and
2541 // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
2542 // but the first m= section.
2543 callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
2544 caller()->CreateAndSetAndSignalOffer();
2545 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002546 MediaExpectations media_expectations;
2547 media_expectations.ExpectBidirectionalAudioAndVideo();
2548 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002549}
2550
2551// Test that we can receive the audio output level from a remote audio track.
2552// TODO(deadbeef): Use a fake audio source and verify that the output level is
2553// exactly what the source on the other side was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002554TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002555 ASSERT_TRUE(CreatePeerConnectionWrappers());
2556 ConnectFakeSignaling();
2557 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002558 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002559 caller()->CreateAndSetAndSignalOffer();
2560 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2561
2562 // Get the audio output level stats. Note that the level is not available
2563 // until an RTCP packet has been received.
deadbeefd8ad7882017-04-18 16:01:17 -07002564 EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002565 kMaxWaitForFramesMs);
2566}
2567
2568// Test that an audio input level is reported.
2569// TODO(deadbeef): Use a fake audio source and verify that the input level is
2570// exactly what the source was configured with.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002571TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002572 ASSERT_TRUE(CreatePeerConnectionWrappers());
2573 ConnectFakeSignaling();
2574 // Just add an audio track.
Steve Anton15324772018-01-16 10:26:49 -08002575 caller()->AddAudioTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07002576 caller()->CreateAndSetAndSignalOffer();
2577 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2578
2579 // Get the audio input level stats. The level should be available very
2580 // soon after the test starts.
deadbeefd8ad7882017-04-18 16:01:17 -07002581 EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
deadbeef1dcb1642017-03-29 21:08:16 -07002582 kMaxWaitForStatsMs);
2583}
2584
2585// Test that we can get incoming byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002586TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002587 ASSERT_TRUE(CreatePeerConnectionWrappers());
2588 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002589 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002590 // Do offer/answer, wait for the callee to receive some frames.
2591 caller()->CreateAndSetAndSignalOffer();
2592 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002593
2594 MediaExpectations media_expectations;
2595 media_expectations.CalleeExpectsSomeAudioAndVideo();
2596 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002597
2598 // Get a handle to the remote tracks created, so they can be used as GetStats
2599 // filters.
Mirko Bonadei739baf02019-01-27 17:29:42 +01002600 for (const auto& receiver : callee()->pc()->GetReceivers()) {
Steve Anton15324772018-01-16 10:26:49 -08002601 // We received frames, so we definitely should have nonzero "received bytes"
2602 // stats at this point.
2603 EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
2604 0);
2605 }
deadbeef1dcb1642017-03-29 21:08:16 -07002606}
2607
2608// Test that we can get outgoing byte counts from both audio and video tracks.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002609TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
deadbeef1dcb1642017-03-29 21:08:16 -07002610 ASSERT_TRUE(CreatePeerConnectionWrappers());
2611 ConnectFakeSignaling();
2612 auto audio_track = caller()->CreateLocalAudioTrack();
2613 auto video_track = caller()->CreateLocalVideoTrack();
Steve Anton15324772018-01-16 10:26:49 -08002614 caller()->AddTrack(audio_track);
2615 caller()->AddTrack(video_track);
deadbeef1dcb1642017-03-29 21:08:16 -07002616 // Do offer/answer, wait for the callee to receive some frames.
2617 caller()->CreateAndSetAndSignalOffer();
2618 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002619 MediaExpectations media_expectations;
2620 media_expectations.CalleeExpectsSomeAudioAndVideo();
2621 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002622
2623 // The callee received frames, so we definitely should have nonzero "sent
2624 // bytes" stats at this point.
deadbeefd8ad7882017-04-18 16:01:17 -07002625 EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
2626 EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
2627}
2628
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002629// Test that we can get capture start ntp time.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002630TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002631 ASSERT_TRUE(CreatePeerConnectionWrappers());
2632 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002633 caller()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002634
Steve Anton15324772018-01-16 10:26:49 -08002635 callee()->AddAudioTrack();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002636
2637 // Do offer/answer, wait for the callee to receive some frames.
2638 caller()->CreateAndSetAndSignalOffer();
2639 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2640
2641 // Get the remote audio track created on the receiver, so they can be used as
2642 // GetStats filters.
Steve Antonfc853712018-03-01 13:48:58 -08002643 auto receivers = callee()->pc()->GetReceivers();
2644 ASSERT_EQ(1u, receivers.size());
2645 auto remote_audio_track = receivers[0]->track();
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002646
2647 // Get the audio output level stats. Note that the level is not available
2648 // until an RTCP packet has been received.
Zhi Huange830e682018-03-30 10:48:35 -07002649 EXPECT_TRUE_WAIT(
2650 callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
2651 0,
2652 2 * kMaxWaitForFramesMs);
Fredrik Solenberg73276ad2017-09-14 14:46:47 +02002653}
2654
Steve Antona41959e2018-11-28 11:15:33 -08002655// Test that the track ID is associated with all local and remote SSRC stats
2656// using the old GetStats() and more than 1 audio and more than 1 video track.
2657// This is a regression test for crbug.com/906988
2658TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
2659 OldGetStatsAssociatesTrackIdForManyMediaSections) {
2660 ASSERT_TRUE(CreatePeerConnectionWrappers());
2661 ConnectFakeSignaling();
2662 auto audio_sender_1 = caller()->AddAudioTrack();
2663 auto video_sender_1 = caller()->AddVideoTrack();
2664 auto audio_sender_2 = caller()->AddAudioTrack();
2665 auto video_sender_2 = caller()->AddVideoTrack();
2666 caller()->CreateAndSetAndSignalOffer();
2667 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2668
2669 MediaExpectations media_expectations;
2670 media_expectations.CalleeExpectsSomeAudioAndVideo();
2671 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2672
2673 std::vector<std::string> track_ids = {
2674 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2675 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2676
2677 auto caller_stats = caller()->OldGetStats();
2678 EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2679 auto callee_stats = callee()->OldGetStats();
2680 EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
2681}
2682
Steve Antonffa6ce42018-11-30 09:26:08 -08002683// Test that the new GetStats() returns stats for all outgoing/incoming streams
2684// with the correct track IDs if there are more than one audio and more than one
2685// video senders/receivers.
2686TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
2687 ASSERT_TRUE(CreatePeerConnectionWrappers());
2688 ConnectFakeSignaling();
2689 auto audio_sender_1 = caller()->AddAudioTrack();
2690 auto video_sender_1 = caller()->AddVideoTrack();
2691 auto audio_sender_2 = caller()->AddAudioTrack();
2692 auto video_sender_2 = caller()->AddVideoTrack();
2693 caller()->CreateAndSetAndSignalOffer();
2694 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2695
2696 MediaExpectations media_expectations;
2697 media_expectations.CalleeExpectsSomeAudioAndVideo();
2698 ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
2699
2700 std::vector<std::string> track_ids = {
2701 audio_sender_1->track()->id(), video_sender_1->track()->id(),
2702 audio_sender_2->track()->id(), video_sender_2->track()->id()};
2703
2704 rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
2705 caller()->NewGetStats();
2706 ASSERT_TRUE(caller_report);
2707 auto outbound_stream_stats =
2708 caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
2709 ASSERT_EQ(4u, outbound_stream_stats.size());
2710 std::vector<std::string> outbound_track_ids;
2711 for (const auto& stat : outbound_stream_stats) {
2712 ASSERT_TRUE(stat->bytes_sent.is_defined());
2713 EXPECT_LT(0u, *stat->bytes_sent);
2714 ASSERT_TRUE(stat->track_id.is_defined());
2715 const auto* track_stat =
2716 caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2717 ASSERT_TRUE(track_stat);
2718 outbound_track_ids.push_back(*track_stat->track_identifier);
2719 }
2720 EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
2721
2722 rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
2723 callee()->NewGetStats();
2724 ASSERT_TRUE(callee_report);
2725 auto inbound_stream_stats =
2726 callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2727 ASSERT_EQ(4u, inbound_stream_stats.size());
2728 std::vector<std::string> inbound_track_ids;
2729 for (const auto& stat : inbound_stream_stats) {
2730 ASSERT_TRUE(stat->bytes_received.is_defined());
2731 EXPECT_LT(0u, *stat->bytes_received);
2732 ASSERT_TRUE(stat->track_id.is_defined());
2733 const auto* track_stat =
2734 callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
2735 ASSERT_TRUE(track_stat);
2736 inbound_track_ids.push_back(*track_stat->track_identifier);
2737 }
2738 EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
2739}
2740
2741// Test that we can get stats (using the new stats implementation) for
deadbeefd8ad7882017-04-18 16:01:17 -07002742// unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
2743// SDP.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002744TEST_P(PeerConnectionIntegrationTest,
deadbeefd8ad7882017-04-18 16:01:17 -07002745 GetStatsForUnsignaledStreamWithNewStatsApi) {
2746 ASSERT_TRUE(CreatePeerConnectionWrappers());
2747 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002748 caller()->AddAudioTrack();
deadbeefd8ad7882017-04-18 16:01:17 -07002749 // Remove SSRCs and MSIDs from the received offer SDP.
2750 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2751 caller()->CreateAndSetAndSignalOffer();
2752 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002753 MediaExpectations media_expectations;
2754 media_expectations.CalleeExpectsSomeAudio(1);
2755 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefd8ad7882017-04-18 16:01:17 -07002756
2757 // We received a frame, so we should have nonzero "bytes received" stats for
2758 // the unsignaled stream, if stats are working for it.
2759 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2760 callee()->NewGetStats();
2761 ASSERT_NE(nullptr, report);
2762 auto inbound_stream_stats =
2763 report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2764 ASSERT_EQ(1U, inbound_stream_stats.size());
2765 ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
2766 ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
zhihuangf8164932017-05-19 13:09:47 -07002767 ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
2768}
2769
Taylor Brandstettera4653442018-06-19 09:44:26 -07002770// Same as above but for the legacy stats implementation.
2771TEST_P(PeerConnectionIntegrationTest,
2772 GetStatsForUnsignaledStreamWithOldStatsApi) {
2773 ASSERT_TRUE(CreatePeerConnectionWrappers());
2774 ConnectFakeSignaling();
2775 caller()->AddAudioTrack();
2776 // Remove SSRCs and MSIDs from the received offer SDP.
2777 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2778 caller()->CreateAndSetAndSignalOffer();
2779 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2780
2781 // Note that, since the old stats implementation associates SSRCs with tracks
2782 // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
2783 // associated track ID. So we can't use the track "selector" argument.
2784 //
2785 // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
2786 // return cached stats if not enough time has passed since the last update.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02002787 EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
Taylor Brandstettera4653442018-06-19 09:44:26 -07002788 kDefaultTimeout);
2789}
2790
zhihuangf8164932017-05-19 13:09:47 -07002791// Test that we can successfully get the media related stats (audio level
2792// etc.) for the unsignaled stream.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002793TEST_P(PeerConnectionIntegrationTest,
zhihuangf8164932017-05-19 13:09:47 -07002794 GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
2795 ASSERT_TRUE(CreatePeerConnectionWrappers());
2796 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002797 caller()->AddAudioVideoTracks();
zhihuangf8164932017-05-19 13:09:47 -07002798 // Remove SSRCs and MSIDs from the received offer SDP.
2799 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2800 caller()->CreateAndSetAndSignalOffer();
2801 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002802 MediaExpectations media_expectations;
2803 media_expectations.CalleeExpectsSomeAudio(1);
2804 media_expectations.CalleeExpectsSomeVideo(1);
2805 ASSERT_TRUE(ExpectNewFrames(media_expectations));
zhihuangf8164932017-05-19 13:09:47 -07002806
2807 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2808 callee()->NewGetStats();
2809 ASSERT_NE(nullptr, report);
2810
2811 auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2812 auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
2813 ASSERT_GE(audio_index, 0);
2814 EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
deadbeef1dcb1642017-03-29 21:08:16 -07002815}
2816
deadbeef4e2deab2017-09-20 13:56:21 -07002817// Helper for test below.
2818void ModifySsrcs(cricket::SessionDescription* desc) {
2819 for (ContentInfo& content : desc->contents()) {
Steve Antondf527fd2018-04-27 15:52:03 -07002820 for (StreamParams& stream :
Steve Antonb1c1de12017-12-21 15:14:30 -08002821 content.media_description()->mutable_streams()) {
deadbeef4e2deab2017-09-20 13:56:21 -07002822 for (uint32_t& ssrc : stream.ssrcs) {
2823 ssrc = rtc::CreateRandomId();
2824 }
2825 }
2826 }
2827}
2828
2829// Test that the "RTCMediaSteamTrackStats" object is updated correctly when
2830// SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
2831// This should result in two "RTCInboundRTPStreamStats", but only one
2832// "RTCMediaStreamTrackStats", whose counters go up continuously rather than
2833// being reset to 0 once the SSRC change occurs.
2834//
2835// Regression test for this bug:
2836// https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
2837//
2838// The bug causes the track stats to only represent one of the two streams:
2839// whichever one has the higher SSRC. So with this bug, there was a 50% chance
2840// that the track stat counters would reset to 0 when the new stream is
2841// received, and a 50% chance that they'll stop updating (while
2842// "concealed_samples" continues increasing, due to silence being generated for
2843// the inactive stream).
Seth Hampson2f0d7022018-02-20 11:54:42 -08002844TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08002845 TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
deadbeef4e2deab2017-09-20 13:56:21 -07002846 ASSERT_TRUE(CreatePeerConnectionWrappers());
2847 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002848 caller()->AddAudioTrack();
deadbeef4e2deab2017-09-20 13:56:21 -07002849 // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
2850 // that doesn't signal SSRCs (from the callee's perspective).
2851 callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
2852 caller()->CreateAndSetAndSignalOffer();
2853 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2854 // Wait for 50 audio frames (500ms of audio) to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002855 {
2856 MediaExpectations media_expectations;
2857 media_expectations.CalleeExpectsSomeAudio(50);
2858 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2859 }
deadbeef4e2deab2017-09-20 13:56:21 -07002860 // Some audio frames were received, so we should have nonzero "samples
2861 // received" for the track.
2862 rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
2863 callee()->NewGetStats();
2864 ASSERT_NE(nullptr, report);
2865 auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2866 ASSERT_EQ(1U, track_stats.size());
2867 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2868 ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
2869 // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
2870
2871 // Create a new offer and munge it to cause the caller to use a new SSRC.
2872 caller()->SetGeneratedSdpMunger(ModifySsrcs);
2873 caller()->CreateAndSetAndSignalOffer();
2874 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
2875 // Wait for 25 more audio frames (250ms of audio) to be received, from the new
2876 // SSRC.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002877 {
2878 MediaExpectations media_expectations;
2879 media_expectations.CalleeExpectsSomeAudio(25);
2880 ASSERT_TRUE(ExpectNewFrames(media_expectations));
2881 }
deadbeef4e2deab2017-09-20 13:56:21 -07002882
2883 report = callee()->NewGetStats();
2884 ASSERT_NE(nullptr, report);
2885 track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
2886 ASSERT_EQ(1U, track_stats.size());
2887 ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
2888 // The "total samples received" stat should only be greater than it was
2889 // before.
2890 // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
2891 // Right now, the new SSRC will cause the counters to reset to 0.
2892 // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
2893
2894 // Additionally, the percentage of concealed samples (samples generated to
Steve Anton83119dd2017-11-10 16:19:52 -08002895 // conceal packet loss) should be less than 50%. If it's greater, that's a
deadbeef4e2deab2017-09-20 13:56:21 -07002896 // good sign that we're seeing stats from the old stream that's no longer
2897 // receiving packets, and is generating concealed samples of silence.
Steve Anton83119dd2017-11-10 16:19:52 -08002898 constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
deadbeef4e2deab2017-09-20 13:56:21 -07002899 ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
2900 EXPECT_LT(*track_stats[0]->concealed_samples,
2901 *track_stats[0]->total_samples_received *
2902 kAcceptableConcealedSamplesPercentage);
2903
2904 // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
2905 // sanity check that the SSRC really changed.
2906 // TODO(deadbeef): This isn't working right now, because we're not returning
2907 // *any* stats for the inactive stream. Uncomment when the bug is completely
2908 // fixed.
2909 // auto inbound_stream_stats =
2910 // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
2911 // ASSERT_EQ(2U, inbound_stream_stats.size());
2912}
2913
deadbeef1dcb1642017-03-29 21:08:16 -07002914// Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002915TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002916 PeerConnectionFactory::Options dtls_10_options;
2917 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2918 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2919 dtls_10_options));
2920 ConnectFakeSignaling();
2921 // Do normal offer/answer and wait for some frames to be received in each
2922 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002923 caller()->AddAudioVideoTracks();
2924 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002925 caller()->CreateAndSetAndSignalOffer();
2926 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002927 MediaExpectations media_expectations;
2928 media_expectations.ExpectBidirectionalAudioAndVideo();
2929 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002930}
2931
2932// Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002933TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002934 PeerConnectionFactory::Options dtls_10_options;
2935 dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2936 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
2937 dtls_10_options));
2938 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002939 caller()->AddAudioVideoTracks();
2940 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002941 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002942 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002943 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002944 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002945 kDefaultTimeout);
2946 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002947 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002948 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002949 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002950 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2951 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002952}
2953
2954// Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002955TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
deadbeef1dcb1642017-03-29 21:08:16 -07002956 PeerConnectionFactory::Options dtls_12_options;
2957 dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2958 ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
2959 dtls_12_options));
2960 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08002961 caller()->AddAudioVideoTracks();
2962 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002963 caller()->CreateAndSetAndSignalOffer();
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002964 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07002965 EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
deadbeefd8ad7882017-04-18 16:01:17 -07002966 caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
deadbeef1dcb1642017-03-29 21:08:16 -07002967 kDefaultTimeout);
2968 EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
deadbeefd8ad7882017-04-18 16:01:17 -07002969 caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002970 // TODO(bugs.webrtc.org/9456): Fix it.
Alex Loiko9289eda2018-11-23 16:18:59 +00002971 EXPECT_EQ(1, webrtc::metrics::NumEvents(
Qingsi Wang7fc821d2018-07-12 12:54:53 -07002972 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
2973 kDefaultSrtpCryptoSuite));
deadbeef1dcb1642017-03-29 21:08:16 -07002974}
2975
2976// Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
2977// callee only supports 1.0.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002978TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
deadbeef1dcb1642017-03-29 21:08:16 -07002979 PeerConnectionFactory::Options caller_options;
2980 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
2981 PeerConnectionFactory::Options callee_options;
2982 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
2983 ASSERT_TRUE(
2984 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
2985 ConnectFakeSignaling();
2986 // Do normal offer/answer and wait for some frames to be received in each
2987 // direction.
Steve Anton15324772018-01-16 10:26:49 -08002988 caller()->AddAudioVideoTracks();
2989 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07002990 caller()->CreateAndSetAndSignalOffer();
2991 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08002992 MediaExpectations media_expectations;
2993 media_expectations.ExpectBidirectionalAudioAndVideo();
2994 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07002995}
2996
2997// Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
2998// callee supports 1.2.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002999TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
deadbeef1dcb1642017-03-29 21:08:16 -07003000 PeerConnectionFactory::Options caller_options;
3001 caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
3002 PeerConnectionFactory::Options callee_options;
3003 callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
3004 ASSERT_TRUE(
3005 CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
3006 ConnectFakeSignaling();
3007 // Do normal offer/answer and wait for some frames to be received in each
3008 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003009 caller()->AddAudioVideoTracks();
3010 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003011 caller()->CreateAndSetAndSignalOffer();
3012 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003013 MediaExpectations media_expectations;
3014 media_expectations.ExpectBidirectionalAudioAndVideo();
3015 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003016}
3017
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003018// The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
3019// works as expected; the cipher should only be used if enabled by both sides.
3020TEST_P(PeerConnectionIntegrationTest,
3021 Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
3022 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003023 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003024 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003025 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3026 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003027 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3028 TestNegotiatedCipherSuite(caller_options, callee_options,
3029 expected_cipher_suite);
3030}
3031
3032TEST_P(PeerConnectionIntegrationTest,
3033 Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
3034 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003035 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
3036 false;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003037 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003038 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003039 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
3040 TestNegotiatedCipherSuite(caller_options, callee_options,
3041 expected_cipher_suite);
3042}
3043
3044TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
3045 PeerConnectionFactory::Options caller_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003046 caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003047 PeerConnectionFactory::Options callee_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003048 callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
Taylor Brandstetter5e55fe82018-03-23 11:50:16 -07003049 int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
3050 TestNegotiatedCipherSuite(caller_options, callee_options,
3051 expected_cipher_suite);
3052}
3053
deadbeef1dcb1642017-03-29 21:08:16 -07003054// Test that a non-GCM cipher is used if both sides only support non-GCM.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003055TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003056 bool local_gcm_enabled = false;
3057 bool remote_gcm_enabled = false;
3058 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3059 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3060 expected_cipher_suite);
3061}
3062
3063// Test that a GCM cipher is used if both ends support it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003064TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
deadbeef1dcb1642017-03-29 21:08:16 -07003065 bool local_gcm_enabled = true;
3066 bool remote_gcm_enabled = true;
3067 int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
3068 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3069 expected_cipher_suite);
3070}
3071
3072// Test that GCM isn't used if only the offerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003073TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003074 NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
3075 bool local_gcm_enabled = true;
3076 bool remote_gcm_enabled = false;
3077 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3078 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3079 expected_cipher_suite);
3080}
3081
3082// Test that GCM isn't used if only the answerer supports it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003083TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003084 NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
3085 bool local_gcm_enabled = false;
3086 bool remote_gcm_enabled = true;
3087 int expected_cipher_suite = kDefaultSrtpCryptoSuite;
3088 TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
3089 expected_cipher_suite);
3090}
3091
deadbeef7914b8c2017-04-21 03:23:33 -07003092// Verify that media can be transmitted end-to-end when GCM crypto suites are
3093// enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
3094// only verify that a GCM cipher is negotiated, and not necessarily that SRTP
3095// works with it.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003096TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
deadbeef7914b8c2017-04-21 03:23:33 -07003097 PeerConnectionFactory::Options gcm_options;
Benjamin Wrighta54daf12018-10-11 15:33:17 -07003098 gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
deadbeef7914b8c2017-04-21 03:23:33 -07003099 ASSERT_TRUE(
3100 CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
3101 ConnectFakeSignaling();
3102 // Do normal offer/answer and wait for some frames to be received in each
3103 // direction.
Steve Anton15324772018-01-16 10:26:49 -08003104 caller()->AddAudioVideoTracks();
3105 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003106 caller()->CreateAndSetAndSignalOffer();
3107 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003108 MediaExpectations media_expectations;
3109 media_expectations.ExpectBidirectionalAudioAndVideo();
3110 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003111}
3112
deadbeef1dcb1642017-03-29 21:08:16 -07003113// This test sets up a call between two parties with audio, video and an RTP
3114// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003115TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003116 PeerConnectionInterface::RTCConfiguration rtc_config;
3117 rtc_config.enable_rtp_data_channel = true;
3118 rtc_config.enable_dtls_srtp = false;
3119 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003120 ConnectFakeSignaling();
3121 // Expect that data channel created on caller side will show up for callee as
3122 // well.
3123 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003124 caller()->AddAudioVideoTracks();
3125 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003126 caller()->CreateAndSetAndSignalOffer();
3127 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3128 // Ensure the existence of the RTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003129 MediaExpectations media_expectations;
3130 media_expectations.ExpectBidirectionalAudioAndVideo();
3131 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003132 ASSERT_NE(nullptr, caller()->data_channel());
3133 ASSERT_NE(nullptr, callee()->data_channel());
3134 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3135 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3136
3137 // Ensure data can be sent in both directions.
3138 std::string data = "hello world";
3139 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3140 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3141 kDefaultTimeout);
3142 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3143 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3144 kDefaultTimeout);
3145}
3146
3147// Ensure that an RTP data channel is signaled as closed for the caller when
3148// the callee rejects it in a subsequent offer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003149TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003150 RtpDataChannelSignaledClosedInCalleeOffer) {
3151 // Same procedure as above test.
Niels Möllerf06f9232018-08-07 12:32:18 +02003152 PeerConnectionInterface::RTCConfiguration rtc_config;
3153 rtc_config.enable_rtp_data_channel = true;
3154 rtc_config.enable_dtls_srtp = false;
3155 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003156 ConnectFakeSignaling();
3157 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003158 caller()->AddAudioVideoTracks();
3159 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003160 caller()->CreateAndSetAndSignalOffer();
3161 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3162 ASSERT_NE(nullptr, caller()->data_channel());
3163 ASSERT_NE(nullptr, callee()->data_channel());
3164 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3165 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3166
3167 // Close the data channel on the callee, and do an updated offer/answer.
3168 callee()->data_channel()->Close();
3169 callee()->CreateAndSetAndSignalOffer();
3170 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3171 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3172 EXPECT_FALSE(callee()->data_observer()->IsOpen());
3173}
3174
3175// Tests that data is buffered in an RTP data channel until an observer is
3176// registered for it.
3177//
3178// NOTE: RTP data channels can receive data before the underlying
3179// transport has detected that a channel is writable and thus data can be
3180// received before the data channel state changes to open. That is hard to test
3181// but the same buffering is expected to be used in that case.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003182TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07003183 DataBufferedUntilRtpDataChannelObserverRegistered) {
3184 // Use fake clock and simulated network delay so that we predictably can wait
3185 // until an SCTP message has been delivered without "sleep()"ing.
3186 rtc::ScopedFakeClock fake_clock;
3187 // Some things use a time of "0" as a special value, so we need to start out
3188 // the fake clock at a nonzero time.
3189 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02003190 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07003191 virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
3192 virtual_socket_server()->UpdateDelayDistribution();
3193
Niels Möllerf06f9232018-08-07 12:32:18 +02003194 PeerConnectionInterface::RTCConfiguration rtc_config;
3195 rtc_config.enable_rtp_data_channel = true;
3196 rtc_config.enable_dtls_srtp = false;
3197 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003198 ConnectFakeSignaling();
3199 caller()->CreateDataChannel();
3200 caller()->CreateAndSetAndSignalOffer();
3201 ASSERT_TRUE(caller()->data_channel() != nullptr);
3202 ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
3203 kDefaultTimeout, fake_clock);
3204 ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
3205 kDefaultTimeout, fake_clock);
3206 ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
3207 callee()->data_channel()->state(), kDefaultTimeout,
3208 fake_clock);
3209
3210 // Unregister the observer which is normally automatically registered.
3211 callee()->data_channel()->UnregisterObserver();
3212 // Send data and advance fake clock until it should have been received.
3213 std::string data = "hello world";
3214 caller()->data_channel()->Send(DataBuffer(data));
3215 SIMULATED_WAIT(false, 50, fake_clock);
3216
3217 // Attach data channel and expect data to be received immediately. Note that
3218 // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
3219 // further, but data can be received even if the callback is asynchronous.
3220 MockDataChannelObserver new_observer(callee()->data_channel());
3221 EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
3222 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07003223 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
3224 // If this is not done a DCHECK can be hit in ports.cc, because a large
3225 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07003226 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07003227}
3228
3229// This test sets up a call between two parties with audio, video and but only
3230// the caller client supports RTP data channels.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003231TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003232 PeerConnectionInterface::RTCConfiguration rtc_config_1;
3233 rtc_config_1.enable_rtp_data_channel = true;
deadbeef1dcb1642017-03-29 21:08:16 -07003234 // Must disable DTLS to make negotiation succeed.
Niels Möllerf06f9232018-08-07 12:32:18 +02003235 rtc_config_1.enable_dtls_srtp = false;
3236 PeerConnectionInterface::RTCConfiguration rtc_config_2;
3237 rtc_config_2.enable_dtls_srtp = false;
3238 rtc_config_2.enable_dtls_srtp = false;
3239 ASSERT_TRUE(
3240 CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
deadbeef1dcb1642017-03-29 21:08:16 -07003241 ConnectFakeSignaling();
3242 caller()->CreateDataChannel();
Harald Alvestrandf3736ed2019-04-08 13:09:30 +02003243 ASSERT_TRUE(caller()->data_channel() != nullptr);
Steve Anton15324772018-01-16 10:26:49 -08003244 caller()->AddAudioVideoTracks();
3245 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003246 caller()->CreateAndSetAndSignalOffer();
3247 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3248 // The caller should still have a data channel, but it should be closed, and
3249 // one should ever have been created for the callee.
3250 EXPECT_TRUE(caller()->data_channel() != nullptr);
3251 EXPECT_FALSE(caller()->data_observer()->IsOpen());
3252 EXPECT_EQ(nullptr, callee()->data_channel());
3253}
3254
3255// This test sets up a call between two parties with audio, and video. When
3256// audio and video is setup and flowing, an RTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003257TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
Niels Möllerf06f9232018-08-07 12:32:18 +02003258 PeerConnectionInterface::RTCConfiguration rtc_config;
3259 rtc_config.enable_rtp_data_channel = true;
3260 rtc_config.enable_dtls_srtp = false;
3261 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
deadbeef1dcb1642017-03-29 21:08:16 -07003262 ConnectFakeSignaling();
3263 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003264 caller()->AddAudioVideoTracks();
3265 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003266 caller()->CreateAndSetAndSignalOffer();
3267 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3268 // Create data channel and do new offer and answer.
3269 caller()->CreateDataChannel();
3270 caller()->CreateAndSetAndSignalOffer();
3271 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3272 ASSERT_NE(nullptr, caller()->data_channel());
3273 ASSERT_NE(nullptr, callee()->data_channel());
3274 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3275 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3276 // Ensure data can be sent in both directions.
3277 std::string data = "hello world";
3278 SendRtpDataWithRetries(caller()->data_channel(), data, 5);
3279 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3280 kDefaultTimeout);
3281 SendRtpDataWithRetries(callee()->data_channel(), data, 5);
3282 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3283 kDefaultTimeout);
3284}
3285
3286#ifdef HAVE_SCTP
3287
3288// This test sets up a call between two parties with audio, video and an SCTP
3289// data channel.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003290TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003291 ASSERT_TRUE(CreatePeerConnectionWrappers());
3292 ConnectFakeSignaling();
3293 // Expect that data channel created on caller side will show up for callee as
3294 // well.
3295 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003296 caller()->AddAudioVideoTracks();
3297 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003298 caller()->CreateAndSetAndSignalOffer();
3299 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3300 // Ensure the existence of the SCTP data channel didn't impede audio/video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003301 MediaExpectations media_expectations;
3302 media_expectations.ExpectBidirectionalAudioAndVideo();
3303 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07003304 // Caller data channel should already exist (it created one). Callee data
3305 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3306 ASSERT_NE(nullptr, caller()->data_channel());
3307 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3308 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3309 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3310
3311 // Ensure data can be sent in both directions.
3312 std::string data = "hello world";
3313 caller()->data_channel()->Send(DataBuffer(data));
3314 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3315 kDefaultTimeout);
3316 callee()->data_channel()->Send(DataBuffer(data));
3317 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3318 kDefaultTimeout);
3319}
3320
3321// Ensure that when the callee closes an SCTP data channel, the closing
3322// procedure results in the data channel being closed for the caller as well.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003323TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003324 // Same procedure as above test.
3325 ASSERT_TRUE(CreatePeerConnectionWrappers());
3326 ConnectFakeSignaling();
3327 caller()->CreateDataChannel();
Steve Anton15324772018-01-16 10:26:49 -08003328 caller()->AddAudioVideoTracks();
3329 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003330 caller()->CreateAndSetAndSignalOffer();
3331 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3332 ASSERT_NE(nullptr, caller()->data_channel());
3333 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3334 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3335 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3336
3337 // Close the data channel on the callee side, and wait for it to reach the
3338 // "closed" state on both sides.
3339 callee()->data_channel()->Close();
3340 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3341 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3342}
3343
Seth Hampson2f0d7022018-02-20 11:54:42 -08003344TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
Steve Antonda6c0952017-10-23 11:41:54 -07003345 ASSERT_TRUE(CreatePeerConnectionWrappers());
3346 ConnectFakeSignaling();
3347 webrtc::DataChannelInit init;
3348 init.id = 53;
3349 init.maxRetransmits = 52;
3350 caller()->CreateDataChannel("data-channel", &init);
Steve Anton15324772018-01-16 10:26:49 -08003351 caller()->AddAudioVideoTracks();
3352 callee()->AddAudioVideoTracks();
Steve Antonda6c0952017-10-23 11:41:54 -07003353 caller()->CreateAndSetAndSignalOffer();
3354 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Anton074dece2017-10-24 13:04:12 -07003355 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3356 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003357 // Since "negotiated" is false, the "id" parameter should be ignored.
3358 EXPECT_NE(init.id, callee()->data_channel()->id());
Steve Antonda6c0952017-10-23 11:41:54 -07003359 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3360 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3361 EXPECT_FALSE(callee()->data_channel()->negotiated());
3362}
3363
deadbeef1dcb1642017-03-29 21:08:16 -07003364// Test usrsctp's ability to process unordered data stream, where data actually
3365// arrives out of order using simulated delays. Previously there have been some
3366// bugs in this area.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003367TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
deadbeef1dcb1642017-03-29 21:08:16 -07003368 // Introduce random network delays.
3369 // Otherwise it's not a true "unordered" test.
3370 virtual_socket_server()->set_delay_mean(20);
3371 virtual_socket_server()->set_delay_stddev(5);
3372 virtual_socket_server()->UpdateDelayDistribution();
3373 // Normal procedure, but with unordered data channel config.
3374 ASSERT_TRUE(CreatePeerConnectionWrappers());
3375 ConnectFakeSignaling();
3376 webrtc::DataChannelInit init;
3377 init.ordered = false;
3378 caller()->CreateDataChannel(&init);
3379 caller()->CreateAndSetAndSignalOffer();
3380 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3381 ASSERT_NE(nullptr, caller()->data_channel());
3382 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3383 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3384 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3385
3386 static constexpr int kNumMessages = 100;
3387 // Deliberately chosen to be larger than the MTU so messages get fragmented.
3388 static constexpr size_t kMaxMessageSize = 4096;
3389 // Create and send random messages.
3390 std::vector<std::string> sent_messages;
3391 for (int i = 0; i < kNumMessages; ++i) {
3392 size_t length =
3393 (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
3394 std::string message;
3395 ASSERT_TRUE(rtc::CreateRandomString(length, &message));
3396 caller()->data_channel()->Send(DataBuffer(message));
3397 callee()->data_channel()->Send(DataBuffer(message));
3398 sent_messages.push_back(message);
3399 }
3400
3401 // Wait for all messages to be received.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003402 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003403 caller()->data_observer()->received_message_count(),
3404 kDefaultTimeout);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02003405 EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
deadbeef1dcb1642017-03-29 21:08:16 -07003406 callee()->data_observer()->received_message_count(),
3407 kDefaultTimeout);
3408
3409 // Sort and compare to make sure none of the messages were corrupted.
3410 std::vector<std::string> caller_received_messages =
3411 caller()->data_observer()->messages();
3412 std::vector<std::string> callee_received_messages =
3413 callee()->data_observer()->messages();
Steve Anton64b626b2019-01-28 17:25:26 -08003414 absl::c_sort(sent_messages);
3415 absl::c_sort(caller_received_messages);
3416 absl::c_sort(callee_received_messages);
deadbeef1dcb1642017-03-29 21:08:16 -07003417 EXPECT_EQ(sent_messages, caller_received_messages);
3418 EXPECT_EQ(sent_messages, callee_received_messages);
3419}
3420
3421// This test sets up a call between two parties with audio, and video. When
3422// audio and video are setup and flowing, an SCTP data channel is negotiated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08003423TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
deadbeef1dcb1642017-03-29 21:08:16 -07003424 ASSERT_TRUE(CreatePeerConnectionWrappers());
3425 ConnectFakeSignaling();
3426 // Do initial offer/answer with audio/video.
Steve Anton15324772018-01-16 10:26:49 -08003427 caller()->AddAudioVideoTracks();
3428 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003429 caller()->CreateAndSetAndSignalOffer();
3430 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3431 // Create data channel and do new offer and answer.
3432 caller()->CreateDataChannel();
3433 caller()->CreateAndSetAndSignalOffer();
3434 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3435 // Caller data channel should already exist (it created one). Callee data
3436 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3437 ASSERT_NE(nullptr, caller()->data_channel());
3438 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3439 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3440 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3441 // Ensure data can be sent in both directions.
3442 std::string data = "hello world";
3443 caller()->data_channel()->Send(DataBuffer(data));
3444 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3445 kDefaultTimeout);
3446 callee()->data_channel()->Send(DataBuffer(data));
3447 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3448 kDefaultTimeout);
3449}
3450
deadbeef7914b8c2017-04-21 03:23:33 -07003451// Set up a connection initially just using SCTP data channels, later upgrading
3452// to audio/video, ensuring frames are received end-to-end. Effectively the
3453// inverse of the test above.
3454// This was broken in M57; see https://crbug.com/711243
Seth Hampson2f0d7022018-02-20 11:54:42 -08003455TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
deadbeef7914b8c2017-04-21 03:23:33 -07003456 ASSERT_TRUE(CreatePeerConnectionWrappers());
3457 ConnectFakeSignaling();
3458 // Do initial offer/answer with just data channel.
3459 caller()->CreateDataChannel();
3460 caller()->CreateAndSetAndSignalOffer();
3461 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3462 // Wait until data can be sent over the data channel.
3463 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3464 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3465 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3466
3467 // Do subsequent offer/answer with two-way audio and video. Audio and video
3468 // should end up bundled on the DTLS/ICE transport already used for data.
Steve Anton15324772018-01-16 10:26:49 -08003469 caller()->AddAudioVideoTracks();
3470 callee()->AddAudioVideoTracks();
deadbeef7914b8c2017-04-21 03:23:33 -07003471 caller()->CreateAndSetAndSignalOffer();
3472 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08003473 MediaExpectations media_expectations;
3474 media_expectations.ExpectBidirectionalAudioAndVideo();
3475 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef7914b8c2017-04-21 03:23:33 -07003476}
3477
deadbeef8b7e9ad2017-05-25 09:38:55 -07003478static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
Harald Alvestrand5fc28b12019-05-13 13:36:16 +02003479 cricket::SctpDataContentDescription* dcd_offer =
3480 GetFirstSctpDataContentDescription(desc);
Steve Antonb1c1de12017-12-21 15:14:30 -08003481 ASSERT_TRUE(dcd_offer);
deadbeef8b7e9ad2017-05-25 09:38:55 -07003482 dcd_offer->set_use_sctpmap(false);
3483 dcd_offer->set_protocol("UDP/DTLS/SCTP");
3484}
3485
3486// Test that the data channel works when a spec-compliant SCTP m= section is
3487// offered (using "a=sctp-port" instead of "a=sctpmap", and using
3488// "UDP/DTLS/SCTP" as the protocol).
Seth Hampson2f0d7022018-02-20 11:54:42 -08003489TEST_P(PeerConnectionIntegrationTest,
deadbeef8b7e9ad2017-05-25 09:38:55 -07003490 DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
3491 ASSERT_TRUE(CreatePeerConnectionWrappers());
3492 ConnectFakeSignaling();
3493 caller()->CreateDataChannel();
3494 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
3495 caller()->CreateAndSetAndSignalOffer();
3496 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3497 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3498 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3499 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3500
3501 // Ensure data can be sent in both directions.
3502 std::string data = "hello world";
3503 caller()->data_channel()->Send(DataBuffer(data));
3504 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3505 kDefaultTimeout);
3506 callee()->data_channel()->Send(DataBuffer(data));
3507 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3508 kDefaultTimeout);
3509}
3510
deadbeef1dcb1642017-03-29 21:08:16 -07003511#endif // HAVE_SCTP
3512
Bjorn Mellema2eb0a72018-11-09 10:13:51 -08003513// This test sets up a call between two parties with a media transport data
3514// channel.
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003515TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelEndToEnd) {
3516 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003517 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3518 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003519 rtc_config.use_media_transport_for_data_channels = true;
3520 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3521 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3522 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3523 loopback_media_transports()->second_factory()));
3524 ConnectFakeSignaling();
3525
3526 // Expect that data channel created on caller side will show up for callee as
3527 // well.
3528 caller()->CreateDataChannel();
3529 caller()->CreateAndSetAndSignalOffer();
3530 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3531
3532 // Ensure that the media transport is ready.
3533 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3534 loopback_media_transports()->FlushAsyncInvokes();
3535
3536 // Caller data channel should already exist (it created one). Callee data
3537 // channel may not exist yet, since negotiation happens in-band, not in SDP.
3538 ASSERT_NE(nullptr, caller()->data_channel());
3539 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3540 EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3541 EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3542
3543 // Ensure data can be sent in both directions.
3544 std::string data = "hello world";
3545 caller()->data_channel()->Send(DataBuffer(data));
3546 EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
3547 kDefaultTimeout);
3548 callee()->data_channel()->Send(DataBuffer(data));
3549 EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
3550 kDefaultTimeout);
3551}
3552
3553// Ensure that when the callee closes a media transport data channel, the
3554// closing procedure results in the data channel being closed for the caller
3555// as well.
3556TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelCalleeCloses) {
3557 PeerConnectionInterface::RTCConfiguration rtc_config;
3558 rtc_config.use_media_transport_for_data_channels = true;
3559 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3560 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3561 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3562 loopback_media_transports()->second_factory()));
3563 ConnectFakeSignaling();
3564
3565 // Create a data channel on the caller and signal it to the callee.
3566 caller()->CreateDataChannel();
3567 caller()->CreateAndSetAndSignalOffer();
3568 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3569
3570 // Ensure that the media transport is ready.
3571 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3572 loopback_media_transports()->FlushAsyncInvokes();
3573
3574 // Data channels exist and open on both ends of the connection.
3575 ASSERT_NE(nullptr, caller()->data_channel());
3576 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3577 ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
3578 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
3579
3580 // Close the data channel on the callee side, and wait for it to reach the
3581 // "closed" state on both sides.
3582 callee()->data_channel()->Close();
3583 EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
3584 EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
3585}
3586
3587TEST_P(PeerConnectionIntegrationTest,
3588 MediaTransportDataChannelConfigSentToOtherSide) {
3589 PeerConnectionInterface::RTCConfiguration rtc_config;
3590 rtc_config.use_media_transport_for_data_channels = true;
3591 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3592 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3593 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3594 loopback_media_transports()->second_factory()));
3595 ConnectFakeSignaling();
3596
3597 // Create a data channel with a non-default configuration and signal it to the
3598 // callee.
3599 webrtc::DataChannelInit init;
3600 init.id = 53;
3601 init.maxRetransmits = 52;
3602 caller()->CreateDataChannel("data-channel", &init);
3603 caller()->CreateAndSetAndSignalOffer();
3604 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3605
3606 // Ensure that the media transport is ready.
3607 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3608 loopback_media_transports()->FlushAsyncInvokes();
3609
3610 // Ensure that the data channel exists on the callee with the correct
3611 // configuration.
3612 ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
3613 ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
Harald Alvestrand5c4d2ee2019-04-01 12:58:15 +02003614 // Since "negotiate" is false, the "id" parameter is ignored.
3615 EXPECT_NE(init.id, callee()->data_channel()->id());
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08003616 EXPECT_EQ("data-channel", callee()->data_channel()->label());
3617 EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
3618 EXPECT_FALSE(callee()->data_channel()->negotiated());
3619}
3620
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003621TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgrade) {
3622 PeerConnectionInterface::RTCConfiguration rtc_config;
3623 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3624 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3625 rtc_config.use_media_transport = true;
3626 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3627 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3628 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3629 loopback_media_transports()->second_factory()));
3630 ConnectFakeSignaling();
3631
3632 // Do initial offer/answer with just a video track.
3633 caller()->AddVideoTrack();
3634 callee()->AddVideoTrack();
3635 caller()->CreateAndSetAndSignalOffer();
3636 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3637
3638 // Ensure that the media transport is ready.
3639 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3640 loopback_media_transports()->FlushAsyncInvokes();
3641
3642 // Now add an audio track and do another offer/answer.
3643 caller()->AddAudioTrack();
3644 callee()->AddAudioTrack();
3645 caller()->CreateAndSetAndSignalOffer();
3646 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3647
3648 // Ensure both audio and video frames are received end-to-end.
3649 MediaExpectations media_expectations;
3650 media_expectations.ExpectBidirectionalAudioAndVideo();
3651 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3652
3653 // The second offer should not have generated another media transport.
3654 // Media transport was kept alive, and was not recreated.
3655 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3656 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3657}
3658
3659TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgradeOnTheCallee) {
3660 PeerConnectionInterface::RTCConfiguration rtc_config;
3661 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3662 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3663 rtc_config.use_media_transport = true;
3664 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3665 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3666 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3667 loopback_media_transports()->second_factory()));
3668 ConnectFakeSignaling();
3669
3670 // Do initial offer/answer with just a video track.
3671 caller()->AddVideoTrack();
3672 callee()->AddVideoTrack();
3673 caller()->CreateAndSetAndSignalOffer();
3674 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3675
3676 // Ensure that the media transport is ready.
3677 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3678 loopback_media_transports()->FlushAsyncInvokes();
3679
3680 // Now add an audio track and do another offer/answer.
3681 caller()->AddAudioTrack();
3682 callee()->AddAudioTrack();
3683 callee()->CreateAndSetAndSignalOffer();
3684 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3685
3686 // Ensure both audio and video frames are received end-to-end.
3687 MediaExpectations media_expectations;
3688 media_expectations.ExpectBidirectionalAudioAndVideo();
3689 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3690
3691 // The second offer should not have generated another media transport.
3692 // Media transport was kept alive, and was not recreated.
3693 EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
3694 EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
3695}
3696
Niels Möllerc68d2822018-11-20 14:52:05 +01003697TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalAudio) {
3698 PeerConnectionInterface::RTCConfiguration rtc_config;
Piotr (Peter) Slatalab1ae10b2019-03-01 11:14:05 -08003699 rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3700 rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
Niels Möllerc68d2822018-11-20 14:52:05 +01003701 rtc_config.use_media_transport = true;
3702 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3703 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3704 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3705 loopback_media_transports()->second_factory()));
3706 ConnectFakeSignaling();
3707
3708 caller()->AddAudioTrack();
3709 callee()->AddAudioTrack();
3710 // Start offer/answer exchange and wait for it to complete.
3711 caller()->CreateAndSetAndSignalOffer();
3712 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3713
3714 // Ensure that the media transport is ready.
3715 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3716 loopback_media_transports()->FlushAsyncInvokes();
3717
3718 MediaExpectations media_expectations;
3719 media_expectations.ExpectBidirectionalAudio();
3720 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3721
3722 webrtc::MediaTransportPair::Stats first_stats =
3723 loopback_media_transports()->FirstStats();
3724 webrtc::MediaTransportPair::Stats second_stats =
3725 loopback_media_transports()->SecondStats();
3726
3727 EXPECT_GT(first_stats.received_audio_frames, 0);
3728 EXPECT_GE(second_stats.sent_audio_frames, first_stats.received_audio_frames);
3729
3730 EXPECT_GT(second_stats.received_audio_frames, 0);
3731 EXPECT_GE(first_stats.sent_audio_frames, second_stats.received_audio_frames);
3732}
3733
Niels Möller46879152019-01-07 15:54:47 +01003734TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalVideo) {
3735 PeerConnectionInterface::RTCConfiguration rtc_config;
3736 rtc_config.use_media_transport = true;
3737 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3738 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3739 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3740 loopback_media_transports()->second_factory()));
3741 ConnectFakeSignaling();
3742
3743 caller()->AddVideoTrack();
3744 callee()->AddVideoTrack();
3745 // Start offer/answer exchange and wait for it to complete.
3746 caller()->CreateAndSetAndSignalOffer();
3747 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3748
3749 // Ensure that the media transport is ready.
3750 loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
3751 loopback_media_transports()->FlushAsyncInvokes();
3752
3753 MediaExpectations media_expectations;
3754 media_expectations.ExpectBidirectionalVideo();
3755 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3756
3757 webrtc::MediaTransportPair::Stats first_stats =
3758 loopback_media_transports()->FirstStats();
3759 webrtc::MediaTransportPair::Stats second_stats =
3760 loopback_media_transports()->SecondStats();
3761
3762 EXPECT_GT(first_stats.received_video_frames, 0);
3763 EXPECT_GE(second_stats.sent_video_frames, first_stats.received_video_frames);
3764
3765 EXPECT_GT(second_stats.received_video_frames, 0);
3766 EXPECT_GE(first_stats.sent_video_frames, second_stats.received_video_frames);
3767}
3768
Piotr (Peter) Slatala55b91b92019-01-25 13:31:15 -08003769TEST_P(PeerConnectionIntegrationTest,
3770 MediaTransportDataChannelUsesRtpBidirectionalVideo) {
3771 PeerConnectionInterface::RTCConfiguration rtc_config;
3772 rtc_config.use_media_transport = false;
3773 rtc_config.use_media_transport_for_data_channels = true;
3774 rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
3775 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
3776 rtc_config, rtc_config, loopback_media_transports()->first_factory(),
3777 loopback_media_transports()->second_factory()));
3778 ConnectFakeSignaling();
3779
3780 caller()->AddVideoTrack();
3781 callee()->AddVideoTrack();
3782 // Start offer/answer exchange and wait for it to complete.
3783 caller()->CreateAndSetAndSignalOffer();
3784 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3785
3786 MediaExpectations media_expectations;
3787 media_expectations.ExpectBidirectionalVideo();
3788 ASSERT_TRUE(ExpectNewFrames(media_expectations));
3789}
3790
deadbeef1dcb1642017-03-29 21:08:16 -07003791// Test that the ICE connection and gathering states eventually reach
3792// "complete".
Seth Hampson2f0d7022018-02-20 11:54:42 -08003793TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
deadbeef1dcb1642017-03-29 21:08:16 -07003794 ASSERT_TRUE(CreatePeerConnectionWrappers());
3795 ConnectFakeSignaling();
3796 // Do normal offer/answer.
Steve Anton15324772018-01-16 10:26:49 -08003797 caller()->AddAudioVideoTracks();
3798 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07003799 caller()->CreateAndSetAndSignalOffer();
3800 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3801 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3802 caller()->ice_gathering_state(), kMaxWaitForFramesMs);
3803 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
3804 callee()->ice_gathering_state(), kMaxWaitForFramesMs);
3805 // After the best candidate pair is selected and all candidates are signaled,
3806 // the ICE connection state should reach "complete".
3807 // TODO(deadbeef): Currently, the ICE "controlled" agent (the
3808 // answerer/"callee" by default) only reaches "connected". When this is
3809 // fixed, this test should be updated.
3810 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3811 caller()->ice_connection_state(), kDefaultTimeout);
Alex Loiko9289eda2018-11-23 16:18:59 +00003812 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3813 callee()->ice_connection_state(), kDefaultTimeout);
deadbeef1dcb1642017-03-29 21:08:16 -07003814}
3815
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003816constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
3817 cricket::PORTALLOCATOR_DISABLE_RELAY |
3818 cricket::PORTALLOCATOR_DISABLE_TCP;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003819
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003820// Use a mock resolver to resolve the hostname back to the original IP on both
3821// sides and check that the ICE connection connects.
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003822TEST_P(PeerConnectionIntegrationTest,
3823 IceStatesReachCompletionWithRemoteHostname) {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003824 auto caller_resolver_factory =
3825 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3826 auto callee_resolver_factory =
3827 absl::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
3828 NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
3829 NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003830
3831 // This also verifies that the injected AsyncResolverFactory is used by
3832 // P2PTransportChannel.
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003833 EXPECT_CALL(*caller_resolver_factory, Create())
3834 .WillOnce(Return(&caller_async_resolver));
3835 webrtc::PeerConnectionDependencies caller_deps(nullptr);
3836 caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
3837
3838 EXPECT_CALL(*callee_resolver_factory, Create())
3839 .WillOnce(Return(&callee_async_resolver));
3840 webrtc::PeerConnectionDependencies callee_deps(nullptr);
3841 callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
3842
3843 PeerConnectionInterface::RTCConfiguration config;
3844 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
3845 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
3846
3847 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
3848 config, std::move(caller_deps), config, std::move(callee_deps)));
3849
3850 caller()->SetRemoteAsyncResolver(&callee_async_resolver);
3851 callee()->SetRemoteAsyncResolver(&caller_async_resolver);
3852
3853 // Enable hostname candidates with mDNS names.
Qingsi Wangecd30542019-05-22 14:34:56 -07003854 caller()->SetMdnsResponder(
3855 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
3856 callee()->SetMdnsResponder(
3857 absl::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003858
3859 SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003860
3861 ConnectFakeSignaling();
3862 caller()->AddAudioVideoTracks();
3863 callee()->AddAudioVideoTracks();
3864 caller()->CreateAndSetAndSignalOffer();
3865 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
3866 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
3867 caller()->ice_connection_state(), kDefaultTimeout);
3868 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
3869 callee()->ice_connection_state(), kDefaultTimeout);
Jeroen de Borst833979f2018-12-13 08:25:54 -08003870
3871 EXPECT_EQ(1, webrtc::metrics::NumEvents(
3872 "WebRTC.PeerConnection.CandidatePairType_UDP",
3873 webrtc::kIceCandidatePairHostNameHostName));
Zach Stein6fcdc2f2018-08-23 16:25:55 -07003874}
3875
Steve Antonede9ca52017-10-16 13:04:27 -07003876// Test that firewalling the ICE connection causes the clients to identify the
3877// disconnected state and then removing the firewall causes them to reconnect.
3878class PeerConnectionIntegrationIceStatesTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08003879 : public PeerConnectionIntegrationBaseTest,
3880 public ::testing::WithParamInterface<
3881 std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
Steve Antonede9ca52017-10-16 13:04:27 -07003882 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08003883 PeerConnectionIntegrationIceStatesTest()
3884 : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
3885 port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
Steve Antonede9ca52017-10-16 13:04:27 -07003886 }
3887
3888 void StartStunServer(const SocketAddress& server_address) {
3889 stun_server_.reset(
3890 cricket::TestStunServer::Create(network_thread(), server_address));
3891 }
3892
3893 bool TestIPv6() {
3894 return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
3895 }
3896
3897 void SetPortAllocatorFlags() {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08003898 PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
3899 port_allocator_flags_, port_allocator_flags_);
Steve Antonede9ca52017-10-16 13:04:27 -07003900 }
3901
3902 std::vector<SocketAddress> CallerAddresses() {
3903 std::vector<SocketAddress> addresses;
3904 addresses.push_back(SocketAddress("1.1.1.1", 0));
3905 if (TestIPv6()) {
3906 addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
3907 }
3908 return addresses;
3909 }
3910
3911 std::vector<SocketAddress> CalleeAddresses() {
3912 std::vector<SocketAddress> addresses;
3913 addresses.push_back(SocketAddress("2.2.2.2", 0));
3914 if (TestIPv6()) {
3915 addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
3916 }
3917 return addresses;
3918 }
3919
3920 void SetUpNetworkInterfaces() {
3921 // Remove the default interfaces added by the test infrastructure.
Qingsi Wangecd30542019-05-22 14:34:56 -07003922 caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
3923 callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
Steve Antonede9ca52017-10-16 13:04:27 -07003924
3925 // Add network addresses for test.
3926 for (const auto& caller_address : CallerAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003927 caller()->network_manager()->AddInterface(caller_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003928 }
3929 for (const auto& callee_address : CalleeAddresses()) {
Qingsi Wangecd30542019-05-22 14:34:56 -07003930 callee()->network_manager()->AddInterface(callee_address);
Steve Antonede9ca52017-10-16 13:04:27 -07003931 }
3932 }
3933
3934 private:
3935 uint32_t port_allocator_flags_;
3936 std::unique_ptr<cricket::TestStunServer> stun_server_;
3937};
3938
3939// Tests that the PeerConnection goes through all the ICE gathering/connection
3940// states over the duration of the call. This includes Disconnected and Failed
3941// states, induced by putting a firewall between the peers and waiting for them
3942// to time out.
Steve Anton83119dd2017-11-10 16:19:52 -08003943TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
Jonas Olssonb75d9e92019-02-22 10:33:29 +01003944 rtc::ScopedFakeClock fake_clock;
3945 // Some things use a time of "0" as a special value, so we need to start out
3946 // the fake clock at a nonzero time.
3947 fake_clock.AdvanceTime(TimeDelta::seconds(1));
Steve Antonede9ca52017-10-16 13:04:27 -07003948
3949 const SocketAddress kStunServerAddress =
3950 SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
3951 StartStunServer(kStunServerAddress);
3952
3953 PeerConnectionInterface::RTCConfiguration config;
3954 PeerConnectionInterface::IceServer ice_stun_server;
3955 ice_stun_server.urls.push_back(
3956 "stun:" + kStunServerAddress.HostAsURIString() + ":" +
3957 kStunServerAddress.PortAsString());
3958 config.servers.push_back(ice_stun_server);
3959
3960 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
3961 ConnectFakeSignaling();
3962 SetPortAllocatorFlags();
3963 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08003964 caller()->AddAudioVideoTracks();
3965 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07003966
3967 // Initial state before anything happens.
3968 ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
3969 caller()->ice_gathering_state());
3970 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3971 caller()->ice_connection_state());
Jonas Olsson7a6739e2019-01-15 16:31:55 +01003972 ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
3973 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07003974
3975 // Start the call by creating the offer, setting it as the local description,
3976 // then sending it to the peer who will respond with an answer. This happens
3977 // asynchronously so that we can watch the states as it runs in the
3978 // background.
3979 caller()->CreateAndSetAndSignalOffer();
3980
Jonas Olsson7a6739e2019-01-15 16:31:55 +01003981 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
3982 caller()->ice_connection_state());
Jonas Olssonacd8ae72019-02-25 15:26:24 +01003983 ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olsson7a6739e2019-01-15 16:31:55 +01003984 caller()->standardized_ice_connection_state());
Steve Antonede9ca52017-10-16 13:04:27 -07003985
3986 // Verify that the observer was notified of the intermediate transitions.
3987 EXPECT_THAT(caller()->ice_connection_state_history(),
3988 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3989 PeerConnectionInterface::kIceConnectionConnected,
3990 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olssonacd8ae72019-02-25 15:26:24 +01003991 EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
3992 ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
3993 PeerConnectionInterface::kIceConnectionConnected,
3994 PeerConnectionInterface::kIceConnectionCompleted));
Jonas Olsson635474e2018-10-18 15:58:17 +02003995 EXPECT_THAT(
3996 caller()->peer_connection_state_history(),
3997 ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
Jonas Olsson635474e2018-10-18 15:58:17 +02003998 PeerConnectionInterface::PeerConnectionState::kConnected));
Steve Antonede9ca52017-10-16 13:04:27 -07003999 EXPECT_THAT(caller()->ice_gathering_state_history(),
4000 ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
4001 PeerConnectionInterface::kIceGatheringComplete));
4002
4003 // Block connections to/from the caller and wait for ICE to become
4004 // disconnected.
4005 for (const auto& caller_address : CallerAddresses()) {
4006 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4007 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004008 RTC_LOG(LS_INFO) << "Firewall rules applied";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004009 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4010 caller()->ice_connection_state(), kDefaultTimeout,
4011 fake_clock);
4012 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
4013 caller()->standardized_ice_connection_state(),
4014 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004015
4016 // Let ICE re-establish by removing the firewall rules.
4017 firewall()->ClearRules();
Mirko Bonadei675513b2017-11-09 11:09:25 +01004018 RTC_LOG(LS_INFO) << "Firewall rules cleared";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004019 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4020 caller()->ice_connection_state(), kDefaultTimeout,
4021 fake_clock);
Jonas Olssonacd8ae72019-02-25 15:26:24 +01004022 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004023 caller()->standardized_ice_connection_state(),
4024 kDefaultTimeout, fake_clock);
Steve Antonede9ca52017-10-16 13:04:27 -07004025
4026 // According to RFC7675, if there is no response within 30 seconds then the
4027 // peer should consider the other side to have rejected the connection. This
Steve Anton83119dd2017-11-10 16:19:52 -08004028 // is signaled by the state transitioning to "failed".
Steve Antonede9ca52017-10-16 13:04:27 -07004029 constexpr int kConsentTimeout = 30000;
4030 for (const auto& caller_address : CallerAddresses()) {
4031 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4032 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004033 RTC_LOG(LS_INFO) << "Firewall rules applied again";
Jonas Olssonb75d9e92019-02-22 10:33:29 +01004034 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4035 caller()->ice_connection_state(), kConsentTimeout,
4036 fake_clock);
4037 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4038 caller()->standardized_ice_connection_state(),
4039 kConsentTimeout, fake_clock);
4040
4041 // We need to manually close the peerconnections before the fake clock goes
4042 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4043 // return to using non-faked time.
4044 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4045 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
4046}
4047
4048// Tests that if the connection doesn't get set up properly we eventually reach
4049// the "failed" iceConnectionState.
4050TEST_P(PeerConnectionIntegrationIceStatesTest, IceStateSetupFailure) {
4051 rtc::ScopedFakeClock fake_clock;
4052 // Some things use a time of "0" as a special value, so we need to start out
4053 // the fake clock at a nonzero time.
4054 fake_clock.AdvanceTime(TimeDelta::seconds(1));
4055
4056 // Block connections to/from the caller and wait for ICE to become
4057 // disconnected.
4058 for (const auto& caller_address : CallerAddresses()) {
4059 firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
4060 }
4061
4062 ASSERT_TRUE(CreatePeerConnectionWrappers());
4063 ConnectFakeSignaling();
4064 SetPortAllocatorFlags();
4065 SetUpNetworkInterfaces();
4066 caller()->AddAudioVideoTracks();
4067 caller()->CreateAndSetAndSignalOffer();
4068
4069 // According to RFC7675, if there is no response within 30 seconds then the
4070 // peer should consider the other side to have rejected the connection. This
4071 // is signaled by the state transitioning to "failed".
4072 constexpr int kConsentTimeout = 30000;
4073 ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
4074 caller()->standardized_ice_connection_state(),
4075 kConsentTimeout, fake_clock);
4076
4077 // We need to manually close the peerconnections before the fake clock goes
4078 // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
4079 // return to using non-faked time.
4080 delete SetCallerPcWrapperAndReturnCurrent(nullptr);
4081 delete SetCalleePcWrapperAndReturnCurrent(nullptr);
Steve Antonede9ca52017-10-16 13:04:27 -07004082}
4083
4084// Tests that the best connection is set to the appropriate IPv4/IPv6 connection
4085// and that the statistics in the metric observers are updated correctly.
4086TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
4087 ASSERT_TRUE(CreatePeerConnectionWrappers());
4088 ConnectFakeSignaling();
4089 SetPortAllocatorFlags();
4090 SetUpNetworkInterfaces();
Steve Anton15324772018-01-16 10:26:49 -08004091 caller()->AddAudioVideoTracks();
4092 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004093 caller()->CreateAndSetAndSignalOffer();
4094
4095 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4096
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004097 // TODO(bugs.webrtc.org/9456): Fix it.
4098 const int num_best_ipv4 = webrtc::metrics::NumEvents(
4099 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
4100 const int num_best_ipv6 = webrtc::metrics::NumEvents(
4101 "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004102 if (TestIPv6()) {
4103 // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
4104 // connection.
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004105 EXPECT_EQ(0, num_best_ipv4);
4106 EXPECT_EQ(1, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004107 } else {
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004108 EXPECT_EQ(1, num_best_ipv4);
4109 EXPECT_EQ(0, num_best_ipv6);
Steve Antonede9ca52017-10-16 13:04:27 -07004110 }
4111
Qingsi Wang7fc821d2018-07-12 12:54:53 -07004112 EXPECT_EQ(0, webrtc::metrics::NumEvents(
4113 "WebRTC.PeerConnection.CandidatePairType_UDP",
4114 webrtc::kIceCandidatePairHostHost));
4115 EXPECT_EQ(1, webrtc::metrics::NumEvents(
4116 "WebRTC.PeerConnection.CandidatePairType_UDP",
4117 webrtc::kIceCandidatePairHostPublicHostPublic));
Steve Antonede9ca52017-10-16 13:04:27 -07004118}
4119
4120constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
4121 cricket::PORTALLOCATOR_DISABLE_STUN |
4122 cricket::PORTALLOCATOR_DISABLE_RELAY;
4123constexpr uint32_t kFlagsIPv6NoStun =
4124 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
4125 cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
4126constexpr uint32_t kFlagsIPv4Stun =
4127 cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
4128
Mirko Bonadeic84f6612019-01-31 12:20:57 +01004129INSTANTIATE_TEST_SUITE_P(
Seth Hampson2f0d7022018-02-20 11:54:42 -08004130 PeerConnectionIntegrationTest,
4131 PeerConnectionIntegrationIceStatesTest,
4132 Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
4133 Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
4134 std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
4135 std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
Steve Antonede9ca52017-10-16 13:04:27 -07004136
deadbeef1dcb1642017-03-29 21:08:16 -07004137// This test sets up a call between two parties with audio and video.
4138// During the call, the caller restarts ICE and the test verifies that
4139// new ICE candidates are generated and audio and video still can flow, and the
4140// ICE state reaches completed again.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004141TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
deadbeef1dcb1642017-03-29 21:08:16 -07004142 ASSERT_TRUE(CreatePeerConnectionWrappers());
4143 ConnectFakeSignaling();
4144 // Do normal offer/answer and wait for ICE to complete.
Steve Anton15324772018-01-16 10:26:49 -08004145 caller()->AddAudioVideoTracks();
4146 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004147 caller()->CreateAndSetAndSignalOffer();
4148 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4149 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4150 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004151 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4152 callee()->ice_connection_state(), kMaxWaitForFramesMs);
deadbeef1dcb1642017-03-29 21:08:16 -07004153
4154 // To verify that the ICE restart actually occurs, get
4155 // ufrag/password/candidates before and after restart.
4156 // Create an SDP string of the first audio candidate for both clients.
4157 const webrtc::IceCandidateCollection* audio_candidates_caller =
4158 caller()->pc()->local_description()->candidates(0);
4159 const webrtc::IceCandidateCollection* audio_candidates_callee =
4160 callee()->pc()->local_description()->candidates(0);
4161 ASSERT_GT(audio_candidates_caller->count(), 0u);
4162 ASSERT_GT(audio_candidates_callee->count(), 0u);
4163 std::string caller_candidate_pre_restart;
4164 ASSERT_TRUE(
4165 audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
4166 std::string callee_candidate_pre_restart;
4167 ASSERT_TRUE(
4168 audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
4169 const cricket::SessionDescription* desc =
4170 caller()->pc()->local_description()->description();
4171 std::string caller_ufrag_pre_restart =
4172 desc->transport_infos()[0].description.ice_ufrag;
4173 desc = callee()->pc()->local_description()->description();
4174 std::string callee_ufrag_pre_restart =
4175 desc->transport_infos()[0].description.ice_ufrag;
4176
4177 // Have the caller initiate an ICE restart.
4178 caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
4179 caller()->CreateAndSetAndSignalOffer();
4180 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4181 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4182 caller()->ice_connection_state(), kMaxWaitForFramesMs);
Alex Loiko9289eda2018-11-23 16:18:59 +00004183 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
deadbeef1dcb1642017-03-29 21:08:16 -07004184 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4185
4186 // Grab the ufrags/candidates again.
4187 audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
4188 audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
4189 ASSERT_GT(audio_candidates_caller->count(), 0u);
4190 ASSERT_GT(audio_candidates_callee->count(), 0u);
4191 std::string caller_candidate_post_restart;
4192 ASSERT_TRUE(
4193 audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
4194 std::string callee_candidate_post_restart;
4195 ASSERT_TRUE(
4196 audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
4197 desc = caller()->pc()->local_description()->description();
4198 std::string caller_ufrag_post_restart =
4199 desc->transport_infos()[0].description.ice_ufrag;
4200 desc = callee()->pc()->local_description()->description();
4201 std::string callee_ufrag_post_restart =
4202 desc->transport_infos()[0].description.ice_ufrag;
4203 // Sanity check that an ICE restart was actually negotiated in SDP.
4204 ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
4205 ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
4206 ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
4207 ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
4208
4209 // Ensure that additional frames are received after the ICE restart.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004210 MediaExpectations media_expectations;
4211 media_expectations.ExpectBidirectionalAudioAndVideo();
4212 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004213}
4214
4215// Verify that audio/video can be received end-to-end when ICE renomination is
4216// enabled.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004217TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
deadbeef1dcb1642017-03-29 21:08:16 -07004218 PeerConnectionInterface::RTCConfiguration config;
4219 config.enable_ice_renomination = true;
4220 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
4221 ConnectFakeSignaling();
4222 // Do normal offer/answer and wait for some frames to be received in each
4223 // direction.
Steve Anton15324772018-01-16 10:26:49 -08004224 caller()->AddAudioVideoTracks();
4225 callee()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004226 caller()->CreateAndSetAndSignalOffer();
4227 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4228 // Sanity check that ICE renomination was actually negotiated.
4229 const cricket::SessionDescription* desc =
4230 caller()->pc()->local_description()->description();
4231 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004232 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004233 }
4234 desc = callee()->pc()->local_description()->description();
4235 for (const cricket::TransportInfo& info : desc->transport_infos()) {
Steve Anton64b626b2019-01-28 17:25:26 -08004236 ASSERT_THAT(info.description.transport_options, Contains("renomination"));
deadbeef1dcb1642017-03-29 21:08:16 -07004237 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08004238 MediaExpectations media_expectations;
4239 media_expectations.ExpectBidirectionalAudioAndVideo();
4240 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004241}
4242
Steve Anton6f25b092017-10-23 09:39:20 -07004243// With a max bundle policy and RTCP muxing, adding a new media description to
4244// the connection should not affect ICE at all because the new media will use
4245// the existing connection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004246TEST_P(PeerConnectionIntegrationTest,
Steve Anton83119dd2017-11-10 16:19:52 -08004247 AddMediaToConnectedBundleDoesNotRestartIce) {
Steve Anton6f25b092017-10-23 09:39:20 -07004248 PeerConnectionInterface::RTCConfiguration config;
4249 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
4250 config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
4251 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
4252 config, PeerConnectionInterface::RTCConfiguration()));
4253 ConnectFakeSignaling();
4254
Steve Anton15324772018-01-16 10:26:49 -08004255 caller()->AddAudioTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004256 caller()->CreateAndSetAndSignalOffer();
4257 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Steve Antonff52f1b2017-10-26 12:24:50 -07004258 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
4259 caller()->ice_connection_state(), kDefaultTimeout);
Steve Anton6f25b092017-10-23 09:39:20 -07004260
4261 caller()->clear_ice_connection_state_history();
4262
Steve Anton15324772018-01-16 10:26:49 -08004263 caller()->AddVideoTrack();
Steve Anton6f25b092017-10-23 09:39:20 -07004264 caller()->CreateAndSetAndSignalOffer();
4265 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4266
4267 EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
4268}
4269
deadbeef1dcb1642017-03-29 21:08:16 -07004270// This test sets up a call between two parties with audio and video. It then
4271// renegotiates setting the video m-line to "port 0", then later renegotiates
4272// again, enabling video.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004273TEST_P(PeerConnectionIntegrationTest,
deadbeef1dcb1642017-03-29 21:08:16 -07004274 VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
4275 ASSERT_TRUE(CreatePeerConnectionWrappers());
4276 ConnectFakeSignaling();
4277
4278 // Do initial negotiation, only sending media from the caller. Will result in
4279 // video and audio recvonly "m=" sections.
Steve Anton15324772018-01-16 10:26:49 -08004280 caller()->AddAudioVideoTracks();
deadbeef1dcb1642017-03-29 21:08:16 -07004281 caller()->CreateAndSetAndSignalOffer();
4282 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4283
4284 // Negotiate again, disabling the video "m=" section (the callee will set the
4285 // port to 0 due to offer_to_receive_video = 0).
Seth Hampson2f0d7022018-02-20 11:54:42 -08004286 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4287 PeerConnectionInterface::RTCOfferAnswerOptions options;
4288 options.offer_to_receive_video = 0;
4289 callee()->SetOfferAnswerOptions(options);
4290 } else {
4291 callee()->SetRemoteOfferHandler([this] {
4292 callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
4293 });
4294 }
deadbeef1dcb1642017-03-29 21:08:16 -07004295 caller()->CreateAndSetAndSignalOffer();
4296 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4297 // Sanity check that video "m=" section was actually rejected.
4298 const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
4299 callee()->pc()->local_description()->description());
4300 ASSERT_NE(nullptr, answer_video_content);
4301 ASSERT_TRUE(answer_video_content->rejected);
4302
4303 // Enable video and do negotiation again, making sure video is received
4304 // end-to-end, also adding media stream to callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004305 if (sdp_semantics_ == SdpSemantics::kPlanB) {
4306 PeerConnectionInterface::RTCOfferAnswerOptions options;
4307 options.offer_to_receive_video = 1;
4308 callee()->SetOfferAnswerOptions(options);
4309 } else {
4310 // The caller's transceiver is stopped, so we need to add another track.
4311 auto caller_transceiver =
4312 caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
4313 EXPECT_TRUE(caller_transceiver->stopped());
4314 caller()->AddVideoTrack();
4315 }
4316 callee()->AddVideoTrack();
4317 callee()->SetRemoteOfferHandler(nullptr);
deadbeef1dcb1642017-03-29 21:08:16 -07004318 caller()->CreateAndSetAndSignalOffer();
4319 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004320
deadbeef1dcb1642017-03-29 21:08:16 -07004321 // Verify the caller receives frames from the newly added stream, and the
4322 // callee receives additional frames from the re-enabled video m= section.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004323 MediaExpectations media_expectations;
4324 media_expectations.CalleeExpectsSomeAudio();
4325 media_expectations.ExpectBidirectionalVideo();
4326 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004327}
4328
deadbeef1dcb1642017-03-29 21:08:16 -07004329// This tests that if we negotiate after calling CreateSender but before we
4330// have a track, then set a track later, frames from the newly-set track are
4331// received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004332TEST_F(PeerConnectionIntegrationTestPlanB,
deadbeef1dcb1642017-03-29 21:08:16 -07004333 MediaFlowsAfterEarlyWarmupWithCreateSender) {
4334 ASSERT_TRUE(CreatePeerConnectionWrappers());
4335 ConnectFakeSignaling();
4336 auto caller_audio_sender =
4337 caller()->pc()->CreateSender("audio", "caller_stream");
4338 auto caller_video_sender =
4339 caller()->pc()->CreateSender("video", "caller_stream");
4340 auto callee_audio_sender =
4341 callee()->pc()->CreateSender("audio", "callee_stream");
4342 auto callee_video_sender =
4343 callee()->pc()->CreateSender("video", "callee_stream");
4344 caller()->CreateAndSetAndSignalOffer();
4345 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4346 // Wait for ICE to complete, without any tracks being set.
4347 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4348 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4349 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4350 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4351 // Now set the tracks, and expect frames to immediately start flowing.
4352 EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4353 EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4354 EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4355 EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
Seth Hampson2f0d7022018-02-20 11:54:42 -08004356 MediaExpectations media_expectations;
4357 media_expectations.ExpectBidirectionalAudioAndVideo();
4358 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4359}
4360
4361// This tests that if we negotiate after calling AddTransceiver but before we
4362// have a track, then set a track later, frames from the newly-set tracks are
4363// received end-to-end.
4364TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
4365 MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
4366 ASSERT_TRUE(CreatePeerConnectionWrappers());
4367 ConnectFakeSignaling();
4368 auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
4369 ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
4370 auto caller_audio_sender = audio_result.MoveValue()->sender();
4371 auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
4372 ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
4373 auto caller_video_sender = video_result.MoveValue()->sender();
4374 callee()->SetRemoteOfferHandler([this] {
4375 ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
4376 callee()->pc()->GetTransceivers()[0]->SetDirection(
4377 RtpTransceiverDirection::kSendRecv);
4378 callee()->pc()->GetTransceivers()[1]->SetDirection(
4379 RtpTransceiverDirection::kSendRecv);
4380 });
4381 caller()->CreateAndSetAndSignalOffer();
4382 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4383 // Wait for ICE to complete, without any tracks being set.
4384 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
4385 caller()->ice_connection_state(), kMaxWaitForFramesMs);
4386 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4387 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4388 // Now set the tracks, and expect frames to immediately start flowing.
4389 auto callee_audio_sender = callee()->pc()->GetSenders()[0];
4390 auto callee_video_sender = callee()->pc()->GetSenders()[1];
4391 ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
4392 ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
4393 ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
4394 ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
4395 MediaExpectations media_expectations;
4396 media_expectations.ExpectBidirectionalAudioAndVideo();
4397 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004398}
4399
4400// This test verifies that a remote video track can be added via AddStream,
4401// and sent end-to-end. For this particular test, it's simply echoed back
4402// from the caller to the callee, rather than being forwarded to a third
4403// PeerConnection.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004404TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
deadbeef1dcb1642017-03-29 21:08:16 -07004405 ASSERT_TRUE(CreatePeerConnectionWrappers());
4406 ConnectFakeSignaling();
4407 // Just send a video track from the caller.
Steve Anton15324772018-01-16 10:26:49 -08004408 caller()->AddVideoTrack();
deadbeef1dcb1642017-03-29 21:08:16 -07004409 caller()->CreateAndSetAndSignalOffer();
4410 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
Mirko Bonadeie12c1fe2018-07-03 12:53:23 +02004411 ASSERT_EQ(1U, callee()->remote_streams()->count());
deadbeef1dcb1642017-03-29 21:08:16 -07004412
4413 // Echo the stream back, and do a new offer/anwer (initiated by callee this
4414 // time).
4415 callee()->pc()->AddStream(callee()->remote_streams()->at(0));
4416 callee()->CreateAndSetAndSignalOffer();
4417 ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
4418
Seth Hampson2f0d7022018-02-20 11:54:42 -08004419 MediaExpectations media_expectations;
4420 media_expectations.ExpectBidirectionalVideo();
4421 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeef1dcb1642017-03-29 21:08:16 -07004422}
4423
4424// Test that we achieve the expected end-to-end connection time, using a
4425// fake clock and simulated latency on the media and signaling paths.
4426// We use a TURN<->TURN connection because this is usually the quickest to
4427// set up initially, especially when we're confident the connection will work
4428// and can start sending media before we get a STUN response.
4429//
4430// With various optimizations enabled, here are the network delays we expect to
4431// be on the critical path:
4432// 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
4433// signaling answer (with DTLS fingerprint).
4434// 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
4435// using TURN<->TURN pair, and DTLS exchange is 4 packets,
4436// the first of which should have arrived before the answer.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004437TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
deadbeef1dcb1642017-03-29 21:08:16 -07004438 rtc::ScopedFakeClock fake_clock;
4439 // Some things use a time of "0" as a special value, so we need to start out
4440 // the fake clock at a nonzero time.
4441 // TODO(deadbeef): Fix this.
Sebastian Jansson5f83cf02018-05-08 14:52:22 +02004442 fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
deadbeef1dcb1642017-03-29 21:08:16 -07004443
4444 static constexpr int media_hop_delay_ms = 50;
4445 static constexpr int signaling_trip_delay_ms = 500;
4446 // For explanation of these values, see comment above.
4447 static constexpr int required_media_hops = 9;
4448 static constexpr int required_signaling_trips = 2;
4449 // For internal delays (such as posting an event asychronously).
4450 static constexpr int allowed_internal_delay_ms = 20;
4451 static constexpr int total_connection_time_ms =
4452 media_hop_delay_ms * required_media_hops +
4453 signaling_trip_delay_ms * required_signaling_trips +
4454 allowed_internal_delay_ms;
4455
4456 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4457 3478};
4458 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4459 0};
4460 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4461 3478};
4462 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4463 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004464 cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
4465 turn_server_1_internal_address, turn_server_1_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004466
Seth Hampsonaed71642018-06-11 07:41:32 -07004467 cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
4468 turn_server_2_internal_address, turn_server_2_external_address);
deadbeef1dcb1642017-03-29 21:08:16 -07004469 // Bypass permission check on received packets so media can be sent before
4470 // the candidate is signaled.
Seth Hampsonaed71642018-06-11 07:41:32 -07004471 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
4472 turn_server_1->set_enable_permission_checks(false);
4473 });
4474 network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
4475 turn_server_2->set_enable_permission_checks(false);
4476 });
deadbeef1dcb1642017-03-29 21:08:16 -07004477
4478 PeerConnectionInterface::RTCConfiguration client_1_config;
4479 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4480 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4481 ice_server_1.username = "test";
4482 ice_server_1.password = "test";
4483 client_1_config.servers.push_back(ice_server_1);
4484 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4485 client_1_config.presume_writable_when_fully_relayed = true;
4486
4487 PeerConnectionInterface::RTCConfiguration client_2_config;
4488 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4489 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4490 ice_server_2.username = "test";
4491 ice_server_2.password = "test";
4492 client_2_config.servers.push_back(ice_server_2);
4493 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4494 client_2_config.presume_writable_when_fully_relayed = true;
4495
4496 ASSERT_TRUE(
4497 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4498 // Set up the simulated delays.
4499 SetSignalingDelayMs(signaling_trip_delay_ms);
4500 ConnectFakeSignaling();
4501 virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
4502 virtual_socket_server()->UpdateDelayDistribution();
4503
4504 // Set "offer to receive audio/video" without adding any tracks, so we just
4505 // set up ICE/DTLS with no media.
4506 PeerConnectionInterface::RTCOfferAnswerOptions options;
4507 options.offer_to_receive_audio = 1;
4508 options.offer_to_receive_video = 1;
4509 caller()->SetOfferAnswerOptions(options);
4510 caller()->CreateAndSetAndSignalOffer();
deadbeef71452802017-05-07 17:21:01 -07004511 EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
4512 fake_clock);
Seth Hampson1d4a76d2018-06-19 14:31:41 -07004513 // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
4514 // If this is not done a DCHECK can be hit in ports.cc, because a large
4515 // negative number is calculated for the rtt due to the global clock changing.
Steve Antond91969e2019-05-30 12:27:03 -07004516 ClosePeerConnections();
deadbeef1dcb1642017-03-29 21:08:16 -07004517}
4518
Jonas Orelandbdcee282017-10-10 14:01:40 +02004519// Verify that a TurnCustomizer passed in through RTCConfiguration
4520// is actually used by the underlying TURN candidate pair.
4521// Note that turnport_unittest.cc contains more detailed, lower-level tests.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004522TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
Jonas Orelandbdcee282017-10-10 14:01:40 +02004523 static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
4524 3478};
4525 static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
4526 0};
4527 static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
4528 3478};
4529 static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
4530 0};
Seth Hampsonaed71642018-06-11 07:41:32 -07004531 CreateTurnServer(turn_server_1_internal_address,
4532 turn_server_1_external_address);
4533 CreateTurnServer(turn_server_2_internal_address,
4534 turn_server_2_external_address);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004535
4536 PeerConnectionInterface::RTCConfiguration client_1_config;
4537 webrtc::PeerConnectionInterface::IceServer ice_server_1;
4538 ice_server_1.urls.push_back("turn:88.88.88.0:3478");
4539 ice_server_1.username = "test";
4540 ice_server_1.password = "test";
4541 client_1_config.servers.push_back(ice_server_1);
4542 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004543 auto* customizer1 = CreateTurnCustomizer();
4544 client_1_config.turn_customizer = customizer1;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004545
4546 PeerConnectionInterface::RTCConfiguration client_2_config;
4547 webrtc::PeerConnectionInterface::IceServer ice_server_2;
4548 ice_server_2.urls.push_back("turn:99.99.99.0:3478");
4549 ice_server_2.username = "test";
4550 ice_server_2.password = "test";
4551 client_2_config.servers.push_back(ice_server_2);
4552 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
Seth Hampsonaed71642018-06-11 07:41:32 -07004553 auto* customizer2 = CreateTurnCustomizer();
4554 client_2_config.turn_customizer = customizer2;
Jonas Orelandbdcee282017-10-10 14:01:40 +02004555
4556 ASSERT_TRUE(
4557 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4558 ConnectFakeSignaling();
4559
4560 // Set "offer to receive audio/video" without adding any tracks, so we just
4561 // set up ICE/DTLS with no media.
4562 PeerConnectionInterface::RTCOfferAnswerOptions options;
4563 options.offer_to_receive_audio = 1;
4564 options.offer_to_receive_video = 1;
4565 caller()->SetOfferAnswerOptions(options);
4566 caller()->CreateAndSetAndSignalOffer();
4567 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4568
Seth Hampsonaed71642018-06-11 07:41:32 -07004569 ExpectTurnCustomizerCountersIncremented(customizer1);
4570 ExpectTurnCustomizerCountersIncremented(customizer2);
Jonas Orelandbdcee282017-10-10 14:01:40 +02004571}
4572
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004573// Verifies that you can use TCP instead of UDP to connect to a TURN server and
4574// send media between the caller and the callee.
4575TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
4576 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4577 3478};
4578 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4579
4580 // Enable TCP for the fake turn server.
Seth Hampsonaed71642018-06-11 07:41:32 -07004581 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4582 cricket::PROTO_TCP);
Benjamin Wright2d5f3cb2018-05-22 14:46:06 -07004583
4584 webrtc::PeerConnectionInterface::IceServer ice_server;
4585 ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
4586 ice_server.username = "test";
4587 ice_server.password = "test";
4588
4589 PeerConnectionInterface::RTCConfiguration client_1_config;
4590 client_1_config.servers.push_back(ice_server);
4591 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4592
4593 PeerConnectionInterface::RTCConfiguration client_2_config;
4594 client_2_config.servers.push_back(ice_server);
4595 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4596
4597 ASSERT_TRUE(
4598 CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
4599
4600 // Do normal offer/answer and wait for ICE to complete.
4601 ConnectFakeSignaling();
4602 caller()->AddAudioVideoTracks();
4603 callee()->AddAudioVideoTracks();
4604 caller()->CreateAndSetAndSignalOffer();
4605 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4606 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
4607 callee()->ice_connection_state(), kMaxWaitForFramesMs);
4608
4609 MediaExpectations media_expectations;
4610 media_expectations.ExpectBidirectionalAudioAndVideo();
4611 EXPECT_TRUE(ExpectNewFrames(media_expectations));
4612}
4613
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004614// Verify that a SSLCertificateVerifier passed in through
4615// PeerConnectionDependencies is actually used by the underlying SSL
4616// implementation to determine whether a certificate presented by the TURN
4617// server is accepted by the client. Note that openssladapter_unittest.cc
4618// contains more detailed, lower-level tests.
4619TEST_P(PeerConnectionIntegrationTest,
4620 SSLCertificateVerifierUsedForTurnConnections) {
4621 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4622 3478};
4623 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4624
4625 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4626 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004627 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4628 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004629
4630 webrtc::PeerConnectionInterface::IceServer ice_server;
4631 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4632 ice_server.username = "test";
4633 ice_server.password = "test";
4634
4635 PeerConnectionInterface::RTCConfiguration client_1_config;
4636 client_1_config.servers.push_back(ice_server);
4637 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4638
4639 PeerConnectionInterface::RTCConfiguration client_2_config;
4640 client_2_config.servers.push_back(ice_server);
4641 // Setting the type to kRelay forces the connection to go through a TURN
4642 // server.
4643 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4644
4645 // Get a copy to the pointer so we can verify calls later.
4646 rtc::TestCertificateVerifier* client_1_cert_verifier =
4647 new rtc::TestCertificateVerifier();
4648 client_1_cert_verifier->verify_certificate_ = true;
4649 rtc::TestCertificateVerifier* client_2_cert_verifier =
4650 new rtc::TestCertificateVerifier();
4651 client_2_cert_verifier->verify_certificate_ = true;
4652
4653 // Create the dependencies with the test certificate verifier.
4654 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4655 client_1_deps.tls_cert_verifier =
4656 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4657 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4658 client_2_deps.tls_cert_verifier =
4659 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4660
4661 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4662 client_1_config, std::move(client_1_deps), client_2_config,
4663 std::move(client_2_deps)));
4664 ConnectFakeSignaling();
4665
4666 // Set "offer to receive audio/video" without adding any tracks, so we just
4667 // set up ICE/DTLS with no media.
4668 PeerConnectionInterface::RTCOfferAnswerOptions options;
4669 options.offer_to_receive_audio = 1;
4670 options.offer_to_receive_video = 1;
4671 caller()->SetOfferAnswerOptions(options);
4672 caller()->CreateAndSetAndSignalOffer();
4673 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
4674
4675 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4676 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004677}
4678
4679TEST_P(PeerConnectionIntegrationTest,
4680 SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
4681 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
4682 3478};
4683 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
4684
4685 // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
4686 // that host name verification passes on the fake certificate.
Seth Hampsonaed71642018-06-11 07:41:32 -07004687 CreateTurnServer(turn_server_internal_address, turn_server_external_address,
4688 cricket::PROTO_TLS, "88.88.88.0");
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004689
4690 webrtc::PeerConnectionInterface::IceServer ice_server;
4691 ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
4692 ice_server.username = "test";
4693 ice_server.password = "test";
4694
4695 PeerConnectionInterface::RTCConfiguration client_1_config;
4696 client_1_config.servers.push_back(ice_server);
4697 client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
4698
4699 PeerConnectionInterface::RTCConfiguration client_2_config;
4700 client_2_config.servers.push_back(ice_server);
4701 // Setting the type to kRelay forces the connection to go through a TURN
4702 // server.
4703 client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
4704
4705 // Get a copy to the pointer so we can verify calls later.
4706 rtc::TestCertificateVerifier* client_1_cert_verifier =
4707 new rtc::TestCertificateVerifier();
4708 client_1_cert_verifier->verify_certificate_ = false;
4709 rtc::TestCertificateVerifier* client_2_cert_verifier =
4710 new rtc::TestCertificateVerifier();
4711 client_2_cert_verifier->verify_certificate_ = false;
4712
4713 // Create the dependencies with the test certificate verifier.
4714 webrtc::PeerConnectionDependencies client_1_deps(nullptr);
4715 client_1_deps.tls_cert_verifier =
4716 std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
4717 webrtc::PeerConnectionDependencies client_2_deps(nullptr);
4718 client_2_deps.tls_cert_verifier =
4719 std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
4720
4721 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
4722 client_1_config, std::move(client_1_deps), client_2_config,
4723 std::move(client_2_deps)));
4724 ConnectFakeSignaling();
4725
4726 // Set "offer to receive audio/video" without adding any tracks, so we just
4727 // set up ICE/DTLS with no media.
4728 PeerConnectionInterface::RTCOfferAnswerOptions options;
4729 options.offer_to_receive_audio = 1;
4730 options.offer_to_receive_video = 1;
4731 caller()->SetOfferAnswerOptions(options);
4732 caller()->CreateAndSetAndSignalOffer();
4733 bool wait_res = true;
4734 // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
4735 // properly, should be able to just wait for a state of "failed" instead of
4736 // waiting a fixed 10 seconds.
4737 WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
4738 ASSERT_FALSE(wait_res);
4739
4740 EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
4741 EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004742}
4743
deadbeefc964d0b2017-04-03 10:03:35 -07004744// Test that audio and video flow end-to-end when codec names don't use the
4745// expected casing, given that they're supposed to be case insensitive. To test
4746// this, all but one codec is removed from each media description, and its
4747// casing is changed.
4748//
4749// In the past, this has regressed and caused crashes/black video, due to the
4750// fact that code at some layers was doing case-insensitive comparisons and
4751// code at other layers was not.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004752TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
deadbeefc964d0b2017-04-03 10:03:35 -07004753 ASSERT_TRUE(CreatePeerConnectionWrappers());
4754 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004755 caller()->AddAudioVideoTracks();
4756 callee()->AddAudioVideoTracks();
deadbeefc964d0b2017-04-03 10:03:35 -07004757
4758 // Remove all but one audio/video codec (opus and VP8), and change the
4759 // casing of the caller's generated offer.
4760 caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
4761 cricket::AudioContentDescription* audio =
4762 GetFirstAudioContentDescription(description);
4763 ASSERT_NE(nullptr, audio);
4764 auto audio_codecs = audio->codecs();
4765 audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
4766 [](const cricket::AudioCodec& codec) {
4767 return codec.name != "opus";
4768 }),
4769 audio_codecs.end());
4770 ASSERT_EQ(1u, audio_codecs.size());
4771 audio_codecs[0].name = "OpUs";
4772 audio->set_codecs(audio_codecs);
4773
4774 cricket::VideoContentDescription* video =
4775 GetFirstVideoContentDescription(description);
4776 ASSERT_NE(nullptr, video);
4777 auto video_codecs = video->codecs();
4778 video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
4779 [](const cricket::VideoCodec& codec) {
4780 return codec.name != "VP8";
4781 }),
4782 video_codecs.end());
4783 ASSERT_EQ(1u, video_codecs.size());
4784 video_codecs[0].name = "vP8";
4785 video->set_codecs(video_codecs);
4786 });
4787
4788 caller()->CreateAndSetAndSignalOffer();
4789 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4790
4791 // Verify frames are still received end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004792 MediaExpectations media_expectations;
4793 media_expectations.ExpectBidirectionalAudioAndVideo();
4794 ASSERT_TRUE(ExpectNewFrames(media_expectations));
deadbeefc964d0b2017-04-03 10:03:35 -07004795}
4796
Jonas Oreland49ac5952018-09-26 16:04:32 +02004797TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
hbos8d609f62017-04-10 07:39:05 -07004798 ASSERT_TRUE(CreatePeerConnectionWrappers());
4799 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08004800 caller()->AddAudioTrack();
hbos8d609f62017-04-10 07:39:05 -07004801 caller()->CreateAndSetAndSignalOffer();
4802 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
deadbeefd8ad7882017-04-18 16:01:17 -07004803 // Wait for one audio frame to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004804 MediaExpectations media_expectations;
4805 media_expectations.CalleeExpectsSomeAudio(1);
4806 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Jonas Oreland49ac5952018-09-26 16:04:32 +02004807 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
hbos8d609f62017-04-10 07:39:05 -07004808 auto receiver = callee()->pc()->GetReceivers()[0];
4809 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
Jonas Oreland49ac5952018-09-26 16:04:32 +02004810 auto sources = receiver->GetSources();
hbos8d609f62017-04-10 07:39:05 -07004811 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4812 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
Jonas Oreland49ac5952018-09-26 16:04:32 +02004813 sources[0].source_id());
4814 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
4815}
4816
4817TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
4818 ASSERT_TRUE(CreatePeerConnectionWrappers());
4819 ConnectFakeSignaling();
4820 caller()->AddVideoTrack();
4821 caller()->CreateAndSetAndSignalOffer();
4822 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4823 // Wait for one video frame to be received by the callee.
4824 MediaExpectations media_expectations;
4825 media_expectations.CalleeExpectsSomeVideo(1);
4826 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4827 ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
4828 auto receiver = callee()->pc()->GetReceivers()[0];
4829 ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
4830 auto sources = receiver->GetSources();
4831 ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
4832 EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
4833 sources[0].source_id());
4834 EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
hbos8d609f62017-04-10 07:39:05 -07004835}
4836
deadbeef2f425aa2017-04-14 10:41:32 -07004837// Test that if a track is removed and added again with a different stream ID,
4838// the new stream ID is successfully communicated in SDP and media continues to
4839// flow end-to-end.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004840// TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
4841// it will not reuse a transceiver that has already been sending. After creating
4842// a new transceiver it tries to create an offer with two senders of the same
4843// track ids and it fails.
4844TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
deadbeef2f425aa2017-04-14 10:41:32 -07004845 ASSERT_TRUE(CreatePeerConnectionWrappers());
4846 ConnectFakeSignaling();
4847
deadbeef2f425aa2017-04-14 10:41:32 -07004848 // Add track using stream 1, do offer/answer.
4849 rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
4850 caller()->CreateLocalAudioTrack();
4851 rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
Steve Antond78323f2018-07-11 11:13:44 -07004852 caller()->AddTrack(track, {"stream_1"});
deadbeef2f425aa2017-04-14 10:41:32 -07004853 caller()->CreateAndSetAndSignalOffer();
4854 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004855 {
4856 MediaExpectations media_expectations;
4857 media_expectations.CalleeExpectsSomeAudio(1);
4858 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4859 }
deadbeef2f425aa2017-04-14 10:41:32 -07004860 // Remove the sender, and create a new one with the new stream.
4861 caller()->pc()->RemoveTrack(sender);
Steve Antond78323f2018-07-11 11:13:44 -07004862 sender = caller()->AddTrack(track, {"stream_2"});
deadbeef2f425aa2017-04-14 10:41:32 -07004863 caller()->CreateAndSetAndSignalOffer();
4864 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4865 // Wait for additional audio frames to be received by the callee.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004866 {
4867 MediaExpectations media_expectations;
4868 media_expectations.CalleeExpectsSomeAudio();
4869 ASSERT_TRUE(ExpectNewFrames(media_expectations));
4870 }
deadbeef2f425aa2017-04-14 10:41:32 -07004871}
4872
Seth Hampson2f0d7022018-02-20 11:54:42 -08004873TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
Elad Alon99c3fe52017-10-13 16:29:40 +02004874 ASSERT_TRUE(CreatePeerConnectionWrappers());
4875 ConnectFakeSignaling();
4876
Karl Wiberg918f50c2018-07-05 11:40:33 +02004877 auto output = absl::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
Mirko Bonadei6a489f22019-04-09 15:11:12 +02004878 ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
4879 ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
Elad Alon99c3fe52017-10-13 16:29:40 +02004880 EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
Bjorn Tereliusde939432017-11-20 17:38:14 +01004881 EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
4882 std::move(output), webrtc::RtcEventLog::kImmediateOutput));
Elad Alon99c3fe52017-10-13 16:29:40 +02004883
Steve Anton15324772018-01-16 10:26:49 -08004884 caller()->AddAudioVideoTracks();
Elad Alon99c3fe52017-10-13 16:29:40 +02004885 caller()->CreateAndSetAndSignalOffer();
4886 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4887}
4888
Steve Antonede9ca52017-10-16 13:04:27 -07004889// Test that if candidates are only signaled by applying full session
4890// descriptions (instead of using AddIceCandidate), the peers can connect to
4891// each other and exchange media.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004892TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
Steve Antonede9ca52017-10-16 13:04:27 -07004893 ASSERT_TRUE(CreatePeerConnectionWrappers());
4894 // Each side will signal the session descriptions but not candidates.
4895 ConnectFakeSignalingForSdpOnly();
4896
4897 // Add audio video track and exchange the initial offer/answer with media
4898 // information only. This will start ICE gathering on each side.
Steve Anton15324772018-01-16 10:26:49 -08004899 caller()->AddAudioVideoTracks();
4900 callee()->AddAudioVideoTracks();
Steve Antonede9ca52017-10-16 13:04:27 -07004901 caller()->CreateAndSetAndSignalOffer();
4902
4903 // Wait for all candidates to be gathered on both the caller and callee.
4904 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4905 caller()->ice_gathering_state(), kDefaultTimeout);
4906 ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
4907 callee()->ice_gathering_state(), kDefaultTimeout);
4908
4909 // The candidates will now be included in the session description, so
4910 // signaling them will start the ICE connection.
4911 caller()->CreateAndSetAndSignalOffer();
4912 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4913
4914 // Ensure that media flows in both directions.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004915 MediaExpectations media_expectations;
4916 media_expectations.ExpectBidirectionalAudioAndVideo();
4917 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Antonede9ca52017-10-16 13:04:27 -07004918}
4919
henrika5f6bf242017-11-01 11:06:56 +01004920// Test that SetAudioPlayout can be used to disable audio playout from the
4921// start, then later enable it. This may be useful, for example, if the caller
4922// needs to play a local ringtone until some event occurs, after which it
4923// switches to playing the received audio.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004924TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
henrika5f6bf242017-11-01 11:06:56 +01004925 ASSERT_TRUE(CreatePeerConnectionWrappers());
4926 ConnectFakeSignaling();
4927
4928 // Set up audio-only call where audio playout is disabled on caller's side.
4929 caller()->pc()->SetAudioPlayout(false);
Steve Anton15324772018-01-16 10:26:49 -08004930 caller()->AddAudioTrack();
4931 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004932 caller()->CreateAndSetAndSignalOffer();
4933 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4934
4935 // Pump messages for a second.
4936 WAIT(false, 1000);
4937 // Since audio playout is disabled, the caller shouldn't have received
4938 // anything (at the playout level, at least).
4939 EXPECT_EQ(0, caller()->audio_frames_received());
4940 // As a sanity check, make sure the callee (for which playout isn't disabled)
4941 // did still see frames on its audio level.
4942 ASSERT_GT(callee()->audio_frames_received(), 0);
4943
4944 // Enable playout again, and ensure audio starts flowing.
4945 caller()->pc()->SetAudioPlayout(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08004946 MediaExpectations media_expectations;
4947 media_expectations.ExpectBidirectionalAudio();
4948 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika5f6bf242017-11-01 11:06:56 +01004949}
4950
4951double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
4952 auto report = pc->NewGetStats();
4953 auto track_stats_list =
4954 report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
4955 const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
4956 for (const auto* track_stats : track_stats_list) {
4957 if (track_stats->remote_source.is_defined() &&
4958 *track_stats->remote_source) {
4959 remote_track_stats = track_stats;
4960 break;
4961 }
4962 }
4963
4964 if (!remote_track_stats->total_audio_energy.is_defined()) {
4965 return 0.0;
4966 }
4967 return *remote_track_stats->total_audio_energy;
4968}
4969
4970// Test that if audio playout is disabled via the SetAudioPlayout() method, then
4971// incoming audio is still processed and statistics are generated.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004972TEST_P(PeerConnectionIntegrationTest,
henrika5f6bf242017-11-01 11:06:56 +01004973 DisableAudioPlayoutStillGeneratesAudioStats) {
4974 ASSERT_TRUE(CreatePeerConnectionWrappers());
4975 ConnectFakeSignaling();
4976
4977 // Set up audio-only call where playout is disabled but audio-processing is
4978 // still active.
Steve Anton15324772018-01-16 10:26:49 -08004979 caller()->AddAudioTrack();
4980 callee()->AddAudioTrack();
henrika5f6bf242017-11-01 11:06:56 +01004981 caller()->pc()->SetAudioPlayout(false);
4982
4983 caller()->CreateAndSetAndSignalOffer();
4984 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
4985
4986 // Wait for the callee to receive audio stats.
4987 EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
4988}
4989
henrika4f167df2017-11-01 14:45:55 +01004990// Test that SetAudioRecording can be used to disable audio recording from the
4991// start, then later enable it. This may be useful, for example, if the caller
4992// wants to ensure that no audio resources are active before a certain state
4993// is reached.
Seth Hampson2f0d7022018-02-20 11:54:42 -08004994TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
henrika4f167df2017-11-01 14:45:55 +01004995 ASSERT_TRUE(CreatePeerConnectionWrappers());
4996 ConnectFakeSignaling();
4997
4998 // Set up audio-only call where audio recording is disabled on caller's side.
4999 caller()->pc()->SetAudioRecording(false);
Steve Anton15324772018-01-16 10:26:49 -08005000 caller()->AddAudioTrack();
5001 callee()->AddAudioTrack();
henrika4f167df2017-11-01 14:45:55 +01005002 caller()->CreateAndSetAndSignalOffer();
5003 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5004
5005 // Pump messages for a second.
5006 WAIT(false, 1000);
5007 // Since caller has disabled audio recording, the callee shouldn't have
5008 // received anything.
5009 EXPECT_EQ(0, callee()->audio_frames_received());
5010 // As a sanity check, make sure the caller did still see frames on its
5011 // audio level since audio recording is enabled on the calle side.
5012 ASSERT_GT(caller()->audio_frames_received(), 0);
5013
5014 // Enable audio recording again, and ensure audio starts flowing.
5015 caller()->pc()->SetAudioRecording(true);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005016 MediaExpectations media_expectations;
5017 media_expectations.ExpectBidirectionalAudio();
5018 ASSERT_TRUE(ExpectNewFrames(media_expectations));
henrika4f167df2017-11-01 14:45:55 +01005019}
5020
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005021// Test that after closing PeerConnections, they stop sending any packets (ICE,
5022// DTLS, RTP...).
Seth Hampson2f0d7022018-02-20 11:54:42 -08005023TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005024 // Set up audio/video/data, wait for some frames to be received.
5025 ASSERT_TRUE(CreatePeerConnectionWrappers());
5026 ConnectFakeSignaling();
Steve Anton15324772018-01-16 10:26:49 -08005027 caller()->AddAudioVideoTracks();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005028#ifdef HAVE_SCTP
5029 caller()->CreateDataChannel();
5030#endif
5031 caller()->CreateAndSetAndSignalOffer();
5032 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
Seth Hampson2f0d7022018-02-20 11:54:42 -08005033 MediaExpectations media_expectations;
5034 media_expectations.CalleeExpectsSomeAudioAndVideo();
5035 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005036 // Close PeerConnections.
Steve Antond91969e2019-05-30 12:27:03 -07005037 ClosePeerConnections();
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005038 // Pump messages for a second, and ensure no new packets end up sent.
5039 uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
5040 WAIT(false, 1000);
5041 uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
5042 EXPECT_EQ(sent_packets_a, sent_packets_b);
5043}
5044
Steve Anton7eca0932018-03-30 15:18:41 -07005045// Test that transport stats are generated by the RTCStatsCollector for a
5046// connection that only involves data channels. This is a regression test for
5047// crbug.com/826972.
5048#ifdef HAVE_SCTP
5049TEST_P(PeerConnectionIntegrationTest,
5050 TransportStatsReportedForDataChannelOnlyConnection) {
5051 ASSERT_TRUE(CreatePeerConnectionWrappers());
5052 ConnectFakeSignaling();
5053 caller()->CreateDataChannel();
5054
5055 caller()->CreateAndSetAndSignalOffer();
5056 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5057 ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
5058
5059 auto caller_report = caller()->NewGetStats();
5060 EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
5061 auto callee_report = callee()->NewGetStats();
5062 EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
5063}
5064#endif // HAVE_SCTP
5065
Qingsi Wang7685e862018-06-11 20:15:46 -07005066TEST_P(PeerConnectionIntegrationTest,
5067 IceEventsGeneratedAndLoggedInRtcEventLog) {
5068 ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
5069 ConnectFakeSignaling();
5070 PeerConnectionInterface::RTCOfferAnswerOptions options;
5071 options.offer_to_receive_audio = 1;
5072 caller()->SetOfferAnswerOptions(options);
5073 caller()->CreateAndSetAndSignalOffer();
5074 ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
5075 ASSERT_NE(nullptr, caller()->event_log_factory());
5076 ASSERT_NE(nullptr, callee()->event_log_factory());
5077 webrtc::FakeRtcEventLog* caller_event_log =
5078 static_cast<webrtc::FakeRtcEventLog*>(
5079 caller()->event_log_factory()->last_log_created());
5080 webrtc::FakeRtcEventLog* callee_event_log =
5081 static_cast<webrtc::FakeRtcEventLog*>(
5082 callee()->event_log_factory()->last_log_created());
5083 ASSERT_NE(nullptr, caller_event_log);
5084 ASSERT_NE(nullptr, callee_event_log);
5085 int caller_ice_config_count = caller_event_log->GetEventCount(
5086 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5087 int caller_ice_event_count = caller_event_log->GetEventCount(
5088 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5089 int callee_ice_config_count = callee_event_log->GetEventCount(
5090 webrtc::RtcEvent::Type::IceCandidatePairConfig);
5091 int callee_ice_event_count = callee_event_log->GetEventCount(
5092 webrtc::RtcEvent::Type::IceCandidatePairEvent);
5093 EXPECT_LT(0, caller_ice_config_count);
5094 EXPECT_LT(0, caller_ice_event_count);
5095 EXPECT_LT(0, callee_ice_config_count);
5096 EXPECT_LT(0, callee_ice_event_count);
5097}
5098
Qingsi Wangc129c352019-04-18 10:41:58 -07005099TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
Qingsi Wangc129c352019-04-18 10:41:58 -07005100 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5101 3478};
5102 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5103
5104 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5105
5106 webrtc::PeerConnectionInterface::IceServer ice_server;
5107 ice_server.urls.push_back("turn:88.88.88.0:3478");
5108 ice_server.username = "test";
5109 ice_server.password = "test";
5110
5111 PeerConnectionInterface::RTCConfiguration caller_config;
5112 caller_config.servers.push_back(ice_server);
5113 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5114 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005115 caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005116
5117 PeerConnectionInterface::RTCConfiguration callee_config;
5118 callee_config.servers.push_back(ice_server);
5119 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5120 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
Qingsi Wang1fe119f2019-05-31 16:55:33 -07005121 callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
Qingsi Wangc129c352019-04-18 10:41:58 -07005122
5123 ASSERT_TRUE(
5124 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5125
5126 // Do normal offer/answer and wait for ICE to complete.
5127 ConnectFakeSignaling();
5128 caller()->AddAudioVideoTracks();
5129 callee()->AddAudioVideoTracks();
5130 caller()->CreateAndSetAndSignalOffer();
5131 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5132 // Since we are doing continual gathering, the ICE transport does not reach
5133 // kIceGatheringComplete (see
5134 // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
5135 // kIceConnectionComplete.
5136 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5137 caller()->ice_connection_state(), kDefaultTimeout);
5138 EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
5139 callee()->ice_connection_state(), kDefaultTimeout);
5140 // Note that we cannot use the metric
5141 // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
5142 // metric is only populated when we reach kIceConnectionComplete in the
5143 // current implementation.
5144 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5145 caller()->last_candidate_gathered().type());
5146 EXPECT_EQ(cricket::RELAY_PORT_TYPE,
5147 callee()->last_candidate_gathered().type());
5148
5149 // Loosen the caller's candidate filter.
5150 caller_config = caller()->pc()->GetConfiguration();
5151 caller_config.type = webrtc::PeerConnectionInterface::kAll;
5152 caller()->pc()->SetConfiguration(caller_config);
5153 // We should have gathered a new host candidate.
5154 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5155 caller()->last_candidate_gathered().type(), kDefaultTimeout);
5156
5157 // Loosen the callee's candidate filter.
5158 callee_config = callee()->pc()->GetConfiguration();
5159 callee_config.type = webrtc::PeerConnectionInterface::kAll;
5160 callee()->pc()->SetConfiguration(callee_config);
5161 EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
5162 callee()->last_candidate_gathered().type(), kDefaultTimeout);
Steve Antond91969e2019-05-30 12:27:03 -07005163
5164 // PeerConnections must be closed before ScopedFieldTrials goes out of scope.
5165 ClosePeerConnections();
Qingsi Wangc129c352019-04-18 10:41:58 -07005166}
5167
Eldar Relloda13ea22019-06-01 12:23:43 +03005168TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
5169 webrtc::test::ScopedFieldTrials field_trials(
5170 "WebRTC-GatherOnCandidateFilterChanged/Enabled/");
5171 static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
5172 3478};
5173 static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
5174
5175 CreateTurnServer(turn_server_internal_address, turn_server_external_address);
5176
5177 webrtc::PeerConnectionInterface::IceServer ice_server;
5178 ice_server.urls.push_back("turn:88.88.88.0:3478");
5179 ice_server.username = "test";
5180 ice_server.password = "123";
5181
5182 PeerConnectionInterface::RTCConfiguration caller_config;
5183 caller_config.servers.push_back(ice_server);
5184 caller_config.type = webrtc::PeerConnectionInterface::kRelay;
5185 caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5186
5187 PeerConnectionInterface::RTCConfiguration callee_config;
5188 callee_config.servers.push_back(ice_server);
5189 callee_config.type = webrtc::PeerConnectionInterface::kRelay;
5190 callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
5191
5192 ASSERT_TRUE(
5193 CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
5194
5195 // Do normal offer/answer and wait for ICE to complete.
5196 ConnectFakeSignaling();
5197 caller()->AddAudioVideoTracks();
5198 callee()->AddAudioVideoTracks();
5199 caller()->CreateAndSetAndSignalOffer();
5200 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5201 EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
5202 EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
5203 EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
5204 EXPECT_NE(std::string::npos,
5205 caller()->error_event().host_candidate.find(":"));
5206}
5207
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005208INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
5209 PeerConnectionIntegrationTest,
5210 Values(SdpSemantics::kPlanB,
5211 SdpSemantics::kUnifiedPlan));
Steve Antond3679212018-01-17 17:41:02 -08005212
Steve Anton74255ff2018-01-24 18:32:57 -08005213// Tests that verify interoperability between Plan B and Unified Plan
5214// PeerConnections.
5215class PeerConnectionIntegrationInteropTest
Seth Hampson2f0d7022018-02-20 11:54:42 -08005216 : public PeerConnectionIntegrationBaseTest,
Steve Anton74255ff2018-01-24 18:32:57 -08005217 public ::testing::WithParamInterface<
5218 std::tuple<SdpSemantics, SdpSemantics>> {
5219 protected:
Seth Hampson2f0d7022018-02-20 11:54:42 -08005220 // Setting the SdpSemantics for the base test to kDefault does not matter
5221 // because we specify not to use the test semantics when creating
5222 // PeerConnectionWrappers.
Steve Anton74255ff2018-01-24 18:32:57 -08005223 PeerConnectionIntegrationInteropTest()
Steve Anton3acffc32018-04-12 17:21:03 -07005224 : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
Seth Hampson2f0d7022018-02-20 11:54:42 -08005225 caller_semantics_(std::get<0>(GetParam())),
Steve Anton74255ff2018-01-24 18:32:57 -08005226 callee_semantics_(std::get<1>(GetParam())) {}
5227
5228 bool CreatePeerConnectionWrappersWithSemantics() {
Steve Anton3acffc32018-04-12 17:21:03 -07005229 return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
5230 callee_semantics_);
Steve Anton74255ff2018-01-24 18:32:57 -08005231 }
5232
5233 const SdpSemantics caller_semantics_;
5234 const SdpSemantics callee_semantics_;
5235};
5236
5237TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
5238 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5239 ConnectFakeSignaling();
5240
5241 caller()->CreateAndSetAndSignalOffer();
5242 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5243}
5244
5245TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
5246 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5247 ConnectFakeSignaling();
5248 auto audio_sender = caller()->AddAudioTrack();
5249
5250 caller()->CreateAndSetAndSignalOffer();
5251 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5252
5253 // Verify that one audio receiver has been created on the remote and that it
5254 // has the same track ID as the sending track.
5255 auto receivers = callee()->pc()->GetReceivers();
5256 ASSERT_EQ(1u, receivers.size());
5257 EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
5258 EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
5259
Seth Hampson2f0d7022018-02-20 11:54:42 -08005260 MediaExpectations media_expectations;
5261 media_expectations.CalleeExpectsSomeAudio();
5262 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005263}
5264
5265TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
5266 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5267 ConnectFakeSignaling();
5268 auto video_sender = caller()->AddVideoTrack();
5269 auto audio_sender = caller()->AddAudioTrack();
5270
5271 caller()->CreateAndSetAndSignalOffer();
5272 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5273
5274 // Verify that one audio and one video receiver have been created on the
5275 // remote and that they have the same track IDs as the sending tracks.
5276 auto audio_receivers =
5277 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
5278 ASSERT_EQ(1u, audio_receivers.size());
5279 EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
5280 auto video_receivers =
5281 callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
5282 ASSERT_EQ(1u, video_receivers.size());
5283 EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
5284
Seth Hampson2f0d7022018-02-20 11:54:42 -08005285 MediaExpectations media_expectations;
5286 media_expectations.CalleeExpectsSomeAudioAndVideo();
5287 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005288}
5289
5290TEST_P(PeerConnectionIntegrationInteropTest,
5291 OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
5292 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5293 ConnectFakeSignaling();
5294 caller()->AddAudioVideoTracks();
5295 callee()->AddAudioVideoTracks();
5296
5297 caller()->CreateAndSetAndSignalOffer();
5298 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5299
Seth Hampson2f0d7022018-02-20 11:54:42 -08005300 MediaExpectations media_expectations;
5301 media_expectations.ExpectBidirectionalAudioAndVideo();
5302 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005303}
5304
5305TEST_P(PeerConnectionIntegrationInteropTest,
5306 ReverseRolesOneAudioLocalToOneVideoRemote) {
5307 ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
5308 ConnectFakeSignaling();
5309 caller()->AddAudioTrack();
5310 callee()->AddVideoTrack();
5311
5312 caller()->CreateAndSetAndSignalOffer();
5313 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5314
5315 // Verify that only the audio track has been negotiated.
5316 EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
5317 // Might also check that the callee's NegotiationNeeded flag is set.
5318
5319 // Reverse roles.
5320 callee()->CreateAndSetAndSignalOffer();
5321 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5322
Seth Hampson2f0d7022018-02-20 11:54:42 -08005323 MediaExpectations media_expectations;
5324 media_expectations.CallerExpectsSomeVideo();
5325 media_expectations.CalleeExpectsSomeAudio();
5326 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005327}
5328
Mirko Bonadeic84f6612019-01-31 12:20:57 +01005329INSTANTIATE_TEST_SUITE_P(
Steve Antonba42e992018-04-09 14:10:01 -07005330 PeerConnectionIntegrationTest,
5331 PeerConnectionIntegrationInteropTest,
5332 Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
5333 std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
5334
5335// Test that if the Unified Plan side offers two video tracks then the Plan B
5336// side will only see the first one and ignore the second.
5337TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
Steve Anton3acffc32018-04-12 17:21:03 -07005338 ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
5339 SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
Steve Anton74255ff2018-01-24 18:32:57 -08005340 ConnectFakeSignaling();
5341 auto first_sender = caller()->AddVideoTrack();
5342 caller()->AddVideoTrack();
5343
5344 caller()->CreateAndSetAndSignalOffer();
5345 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5346
5347 // Verify that there is only one receiver and it corresponds to the first
5348 // added track.
5349 auto receivers = callee()->pc()->GetReceivers();
5350 ASSERT_EQ(1u, receivers.size());
5351 EXPECT_TRUE(receivers[0]->track()->enabled());
5352 EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
5353
Seth Hampson2f0d7022018-02-20 11:54:42 -08005354 MediaExpectations media_expectations;
5355 media_expectations.CalleeExpectsSomeVideo();
5356 ASSERT_TRUE(ExpectNewFrames(media_expectations));
Steve Anton74255ff2018-01-24 18:32:57 -08005357}
5358
Steve Anton2bed3972019-01-04 17:04:30 -08005359// Test that if the initial offer tagged BUNDLE section is rejected due to its
5360// associated RtpTransceiver being stopped and another transceiver is added,
5361// then renegotiation causes the callee to receive the new video track without
5362// error.
5363// This is a regression test for bugs.webrtc.org/9954
5364TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5365 ReOfferWithStoppedBundleTaggedTransceiver) {
5366 RTCConfiguration config;
5367 config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
5368 ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
5369 ConnectFakeSignaling();
5370 auto audio_transceiver_or_error =
5371 caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
5372 ASSERT_TRUE(audio_transceiver_or_error.ok());
5373 auto audio_transceiver = audio_transceiver_or_error.MoveValue();
5374
5375 caller()->CreateAndSetAndSignalOffer();
5376 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5377 {
5378 MediaExpectations media_expectations;
5379 media_expectations.CalleeExpectsSomeAudio();
5380 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5381 }
5382
5383 audio_transceiver->Stop();
5384 caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
5385
5386 caller()->CreateAndSetAndSignalOffer();
5387 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5388 {
5389 MediaExpectations media_expectations;
5390 media_expectations.CalleeExpectsSomeVideo();
5391 ASSERT_TRUE(ExpectNewFrames(media_expectations));
5392 }
5393}
5394
Harald Alvestrandd61f2a72019-05-08 20:20:59 +02005395#ifdef HAVE_SCTP
5396
5397TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
5398 EndToEndCallWithBundledSctpDataChannel) {
5399 ASSERT_TRUE(CreatePeerConnectionWrappers());
5400 ConnectFakeSignaling();
5401 caller()->CreateDataChannel();
5402 caller()->AddAudioVideoTracks();
5403 callee()->AddAudioVideoTracks();
5404 caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
5405 caller()->CreateAndSetAndSignalOffer();
5406 ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
5407 // Ensure that media and data are multiplexed on the same DTLS transport.
5408 // This only works on Unified Plan, because transports are not exposed in plan
5409 // B.
5410 auto sctp_info = caller()->pc()->GetSctpTransport()->Information();
5411 EXPECT_EQ(sctp_info.dtls_transport(),
5412 caller()->pc()->GetSenders()[0]->dtls_transport());
5413}
5414
5415#endif // HAVE_SCTP
5416
deadbeef1dcb1642017-03-29 21:08:16 -07005417} // namespace
Mirko Bonadeiab64e8a2018-12-12 12:10:18 +01005418} // namespace webrtc
deadbeef1dcb1642017-03-29 21:08:16 -07005419
5420#endif // if !defined(THREAD_SANITIZER)